mayowa ogundele
mayowa ogundele

Reputation: 463

Gridview with C# adding rows

I want to add a row to my gridview. i succeeded in adding text boxes, but i cannot extract the value It keeps telling me that object reference not set to an instance of an object. At this line it halts

string acc = Convert.ToString(((TextBox)GridView1.FooterRow.FindControl("accountID")).Text);

Please what am i doing wrong

Upvotes: 1

Views: 604

Answers (2)

sajanyamaha
sajanyamaha

Reputation: 3198

Ok first check wether its a footer row ,then find the textBox in it

protected void grdAccounts_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.Footer)
  {
   //get text box value here
  }
}

In Button Click

try this

GridViewRow row = GridView1.FooterRow; 
firstName = ((TextBox)row.FindControl("TextBox1")).Text;

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460018

  1. You don't need to convert a string to a string(TextBox.Text returns already a string).

How and where have you added the TextBox to the footer-row?

i added the TextBox to the footer row in GridView1_RowDataBound

RowDataBound isn't the right method for dynamic controls since it is called only on databinding and not on every postback. But dynamical controls need to be recreated on every postback.

So use RowCreated instead to create controls dynamically and use RowDataBound to databind them.

protected void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        TextBox tb = new TextBox();
        tb.ID = "accountID";
        e.Row.Cells[indexOfColumn].Controls.Add(tb);
    }
}

Upvotes: 1

Related Questions