Add Columns to DataGrid Programmatically in C#

Sometimes we need to create the column in DataGrid dynamically. By using the following code, you can create BoundColumn and HyperLinkColumn to DataGrid Programmatically using C#. Adding BoundColumn and HyperLinkColumn to DataGrid

  public void AddboundandHyperLinkColumn()
        // First add a simple bound column
        BoundColumn nameColumn = new BoundColumn();
        nameColumn.DataField = "ProductName";
        nameColumn.DataFormatString = "{0}";
        nameColumn.HeaderText = "Product";

        // Now add the HyperLink column
        HyperLinkColumn linkColumn = new HyperLinkColumn();
        linkColumn.DataTextField = "ProductName";
        linkColumn.DataTextFormatString = "{0} Details";
        linkColumn.DataNavigateUrlField = "ProductID";
        linkColumn.DataNavigateUrlFormatString = "/MyApp/ProductDetails.aspx={0}";
        linkColumn.HeaderText = "Details";

        // Add the link in a BoundColumn
        // where the text can be the same for all rows
        BoundColumn blinkColumn = new BoundColumn();
        blinkColumn.DataField = "ProductID";
        blinkColumn.DataFormatString = "Details";
        blinkColumn.HeaderText = "Details";

        DataGrid1.AutoGenerateColumns = false;

        DataTable dt = GetNorthwindProductTable();
        DataGrid1.DataSource = dt;

Note that I added three columns. The first was a simple text column (BoundColumn) with the product name. For the second column, I added a link to a product details page using the HyperLinkColumn. For the third column, I showed an alternate way of adding a link column if the link text can be the same for all rows, such as “Details”. Just added the HTML link tag as text to the BoundColumn. It will be rendered as an HTML link when you view the page.

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads