user3721173
user3721173

Reputation: 41

Set data to a label in GridView

I have a label in an asp GridView and I want to set bind data to it.
Here is my RowDataBound method:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    var name = (Label)e.Row.FindControl("Label_name");
    name.Text ="sara";      
    name.DataBind();
}

and here is my GridView:

<asp:GridView ID="GridViewCertificateType" runat="server" AutoGenerateColumns="False"   OnRowDataBound="GridView1_RowDataBound" >

<asp:Label ID="Label_name" runat="server" Text="" ></asp:Label>

But after name.Text ="sara";, I receive this exception:

Object reference not set to an instance of an object. 

Upvotes: 0

Views: 2030

Answers (2)

j.f.
j.f.

Reputation: 3939

In your RowDataBound method, make sure you have a condition to check what the type of the row is. This event will be called for every row in your GridView, including header and footer rows. If Label_name is not found in the header row, you'll have a null object. Once you do that, get rid of name.DataBind();, as it is not needed.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var name = (Label)e.Row.FindControl("Label_name");
        name.Text = "sara"; 
    }
}

Upvotes: 1

Farrokh
Farrokh

Reputation: 1167

try this

var name= (Label)e.Row.Cells[X].FindControl("Label_name");
name.Text ="sara";      
name.DataBind();

X means index of column

Upvotes: 1

Related Questions