Sangeetha
Sangeetha

Reputation: 69

How to assign value inside the item template lable in asp.net?

Codebehind,

I am getting below error Object reference not set to an instance of an object.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

          string  a = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "item_id")) ;
          string b = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "order_id"));
            Label lbl = (Label)GridView1.FindControl("Label5");

                int sum = int.Parse(a) + int.Parse(b);
                lbl.Text += sum.ToString();

        }
    }

Upvotes: 1

Views: 1923

Answers (3)

Khan Ataur Rahman
Khan Ataur Rahman

Reputation: 33

make sure that your grid item label id is same as code behind FindControl id.

foreach (GridViewRow row in gv_Name.Rows)                        {
{
 Label name = (Label)row.FindControl("lblitemNameId");
}

Upvotes: 1

Tleck Aipov
Tleck Aipov

Reputation: 494

Label lbl = (Label)GridView1.FindControl("Label5"); Write this in OnDataBound Event.

Upvotes: 1

Alex Filipovici
Alex Filipovici

Reputation: 32541

Based on the location of your Label5 control, there should be two possibilities:

  1. If the label is added to the Gridview1.Controls collection, then you should be able to reach it in the following method:

    void GridView1_PreRender(object sender, EventArgs e)
    {
        Label lbl = (Label)GridView1.FindControl("Label5");
    
    }
    
  2. If the label is added for each row, for example like this:

    void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        var label = new Label();
        label.ID = "Label5";
        label.Text = "label";
        var cell = new TableCell();
        cell.Controls.Add(label);
        e.Row.Controls.Add(cell);
    }
    

    in order to find the label in your GridView1_RowDataBound method, you should use:

    e.Row.FindControl("Label5");
    

Upvotes: 1

Related Questions