A2oz

How to Find Header Row Control in GridView in ASP.NET C#?

Published in ASP.NET GridView 2 mins read

You can access the header row control in a GridView in ASP.NET C# using the HeaderRow property. This property returns a GridViewRow object representing the header row of the GridView.

Here's how you can find and use the header row control:

  1. Accessing the Header Row:

    GridViewRow headerRow = GridView1.HeaderRow;
  2. Finding Controls Within the Header Row:
    You can find controls within the header row using the FindControl method. For example, to find a Label control with the ID "lblHeader":

    Label lblHeader = (Label)headerRow.FindControl("lblHeader");
  3. Modifying Header Row Content:
    You can modify the text or properties of controls within the header row:

    lblHeader.Text = "New Header Text";
  4. Adding Controls to the Header Row:
    You can add controls to the header row using the Controls collection of the GridViewRow object. For example, to add a Button control:

    Button btnNew = new Button();
    btnNew.ID = "btnNew";
    btnNew.Text = "Add New";
    headerRow.Controls.Add(btnNew);

Practical Insights:

  • You can use the header row to display static information, such as column headings or titles.
  • You can dynamically change the header row content based on user actions or data changes.
  • You can add buttons or other interactive controls to the header row to provide functionality like sorting or filtering.

Example:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // Get the header row
        GridViewRow headerRow = GridView1.HeaderRow;

        // Find the label control within the header row
        Label lblHeader = (Label)headerRow.FindControl("lblHeader");

        // Change the header text
        lblHeader.Text = "Updated Header Text";

        // Add a button to the header row
        Button btnNew = new Button();
        btnNew.ID = "btnNew";
        btnNew.Text = "Add New";
        headerRow.Controls.Add(btnNew);
    }
}

Conclusion:

By using the HeaderRow property and related methods, you can easily access and manipulate the header row control in your ASP.NET C# GridView.

Related Articles