Hi
I have below code . I have attached image. When i loop thru Gridview it should show Data value but it shows
When i am tryying this it gives error - Object reference mot set to an instance of the Object.
foreach (GridViewRow gr in grdPlanning.Rows)
{
//string sessionDate = "";
if (gr.RowType == DataControlRowType.DataRow)
{
if (gr.Cells[0].Text == "146")
{
string sign5 = ((TextBox)gr.FindControl("txtDate")).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, 9:25 AM
Hi Tuhin
If u see in my earlier code in gr_RowDataBound i have defined txtDate. Why this issue is coming
Thanks
Tuhin PaulPosted May 5, 2023, 9:24 AM
The `FindControl` method returns `null` if the control is not found, so you should check if the result is not `null` before using it. Here's an example:
Alternatively, you can use C# 8's "nullable reference types" feature to specify that `txtDate` may be null:
Note the use of the `?` after the `TextBox` type to indicate that the variable can be null.
Ramco RamcoPosted May 5, 2023, 9:17 AM
Hi Tuhin
When i write this it gives null
Thanks
Tuhin PaulPosted May 5, 2023, 8:59 AM
Part 1:
The ` ` that you see in the GridView cell is a non-breaking space character, which is used to create space between words or characters without allowing line breaks. In your code, you are checking if `gr.Cells[0].Text == "146"`, which means you are comparing the text in the first cell of the GridView row to the string "146". If the text in the cell is actually ` ` (which is not visible to the user), then the condition will not be true. To check for the ` ` character, you can use `Server.HtmlDecode` method to decode the cell's text and replace ` ` with an empty string.
Part 2:
Regarding the error "Object reference not set to an instance of the Object", it means that you are trying to access a property or method of an object that is `null`. In your case, it is possible that `gr.FindControl("txtDate")` is returning `null`, which means that the TextBox control with ID "txtDate" is not found in the current GridView row. You can add a null check to avoid this error: