Hi
In below code it gives error - TextBox txt = (TextBox)gr.Cells[gr.Cells.Count - 1].FindControl("txtDate");
In View PageSource it is showing something like this -
C#
protected void lnkAdd_Click(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gr in grdPlanning.Rows)
{
if (gr.RowType == DataControlRowType.DataRow)
{
if (gr.Cells[0].Text == "146")
{
TextBox txt = (TextBox)gr.Cells[gr.Cells.Count - 1].FindControl("txtDate");
string Ques = txt.Text;
}
}
}
}
}C#
protected void gr_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center;
TextBox txtDate = new TextBox();
txtDate.CssClass = "form-control";
txtDate.DataBind();
e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(txtDate);
}
}Thanks

Rajkiran SwainRank #165 · 14.4K reputationPosted May 5, 2023, 5:56 AM EDT
TextBox txt = gr.Cells[gr.Cells.Count - 1].FindControl("txtDate") as TextBox; if (txt != null) { string Ques = txt.Text; // Do something with Ques }The error "Object reference not set to an instance of the Object" occurs when you try to access a property or method of an object that is null or has not been instantiated. In this case, the error is likely being caused by the line
TextBox txt = (TextBox)gr.Cells[gr.Cells.Count - 1].FindControl("txtDate");whereFindControlis returningnull, so when you try to cast it to aTextBox, it throws the error.To fix this, you should first check if the control returned by
FindControlis not null before trying to cast it to aTextBox. You can use the null-conditional operator?.to perform this check in a concise way. Here's an example of how to do this:Ramco RamcoRank #462 · 5.4K reputationPosted May 5, 2023, 5:59 AM EDT
Hi Rajkiran
Why it is returning null . Is there anything wrong in my below code
protected void gr_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (e.Row.RowType != DataControlRowType.DataRow) return; e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center; TextBox txtDate = new TextBox(); txtDate.CssClass = "form-control"; txtDate.DataBind(); e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(txtDate); } }I want to access this Textbox
Thanks
Rajkiran SwainRank #165 · 14.4K reputationPosted May 5, 2023, 6:10 AM EDT
It's possible that the code is returning null because the
FindControlmethod is not finding the control with the ID "txtDate" in the GridView row. This could happen if the control is not being created or added to the row in thegr_RowDataBoundmethod.Ramco RamcoRank #462 · 5.4K reputationPosted May 5, 2023, 6:16 AM EDT
Hi RajKiran
If u see my Post i have created in GridView RowDataBound
try { if (e.Row.RowType != DataControlRowType.DataRow) return; e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center; TextBox txtDate = new TextBox(); txtDate.CssClass = "form-control"; txtDate.DataBind(); e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(txtDate); }Thanks