2
votes

I am generating gridview dynamically. Here is the code

Design Code

<asp:GridView Width="100%" CssClass="TTable" ID="MainGridView" OnDataBound = "OnDataBound" runat="server" AutoGenerateColumns="False" onrowdatabound="GridView_RowDataBound">
            <Columns>
            </Columns>
</asp:GridView>

Code Behind :

private void createGridView(DataTable gridviewdt)
    {
        MainGridView.Columns.Clear();
        //Iterate through the columns of the datatable to set the data bound field dynamically.
        foreach (DataColumn col in gridviewdt.Columns)
        {
            //Declare the bound field and allocate memory for the bound field.
            BoundField bfield = new BoundField();

            //Initalize the DataField value.
            bfield.DataField = col.ColumnName;

            //Initialize the HeaderText field value.
            bfield.HeaderText = col.ColumnName;

            //Add the newly created bound field to the GridView.
            MainGridView.Columns.Add(bfield);

        }

    }

// Bind Datatable to gridview
MainGridView.DataSource = gridviewdt;
MainGridView.DataBind();

In the above code, I would like to put hyperlink on particular columns data. If I put the hyperlink directly on the Datatable, then it shows it as it is without executing.

<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>

How can I add above link button on some gridview columns ?

1

1 Answers

2
votes

If we want to add a LinkButton declaratively in gridview control then we wrap it inside the TemplateField and not inside a BoundField. Also I am not sure why you are looping through the DataTable (which I guess is the source of the gridview). Correct way to do is by adding the TemplateField to columns collection before binding the data to gridview and finally add the control in RowDataBound event which is raised for each row which is bound to the gridview.

You can use this:-

In Page_Load :-

if (!IsPostBack)
{
   TemplateField myTemplate = new TemplateField();
   myTemplate.HeaderText = "MyLinkButton";
   MainGridView.Columns.Add(myTemplate);
   BindGrid();
}

Here, BindGrid is the method which will simply bind the data to your gridview:-

private void BindGrid()
{
   MainGridView.DataSource = GetData(); \\Your data source here
   MainGridView.DataBind();
}

Finally add the LinkButton control in the RowDataBound event of gridview like this:-

protected void MainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
       LinkButton myLink = new LinkButton();
       myLink.ID = "LinkButton1";
       myLink.Text = "LinkButton";
       myLink.Click += myLink_Click;
       e.Row.Cells[0].Controls.Add(myLink);
   }
}

Please note since I have added just 1 column (in the page load) thus I am using e.Row.Cells[0] to get the first column. If you add multiple columns then you will have to change the code accordingly.