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 -
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;
}
}
}
}
}
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
Ramco RamcoPosted May 5, 2023, 10:16 AM
Hi RajKiran
If u see my Post i have created in GridView RowDataBound
Thanks
Rajkiran SwainPosted May 5, 2023, 10:10 AM
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 RamcoPosted May 5, 2023, 9:59 AM
Hi Rajkiran
Why it is returning null . Is there anything wrong in my below code
I want to access this Textbox
Thanks
Rajkiran SwainPosted May 5, 2023, 9:56 AM
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: