Wednesday 8 May 2019

asp.net - Textbox object is not able to create using find control




In my code there is one gridview1 . While clicking on edit button getting error
Object reference not set to an instance of an object. all my columns are template fields.id is the datakey. and I am able to fetch the datas from database too. What is wrong here. ?



  protected void Edit_Button_Click(object sender, EventArgs e)
{
GridViewRow gr = (GridViewRow)((Button)sender).NamingContainer;

int id = Convert.ToInt32(GridView1.DataKeys[gr.RowIndex].Value);

cmd = new SqlCommand("select * from students where id = '"+id+"'",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);

TextBox name = (TextBox)GridView1.Rows[gr.RowIndex].FindControl("name_TextBox");




name.Text = "bhavin";
}


and this is my aspx page.













.
.
.
.













Answer



Without your client side code (html) it is a bit hard.



But as you said you use templated columns.



Didn't you forget to place your textbox with ID="name_TextBox"in an EditItemTemplate?



like that :




    









The problem is you can't access control in Gridview_RowEditing. Controls will be rendered after this event (if my memory is still reliable : such a time I moved to MVC).

If you manage this event, you have to bind gridview, ex :



 protected void YourGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//you tell Gridview which row gonna be editing :
YourGridView.PageIndex = e.NewPageIndex;
//then you Bind data to the GridView (as you bind data as you did on load for instance)
YourGridView.DataSource = YourDataSetOrDataTable
YourGridView.DataBind();
}




If you want to access a control, you can use gridView_rowDataBound() event instead.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...