0

I need edit the row of GridView in RowDataBound event.

If tried edit one row with field Area not null value I don't have problem, but if tried edit one row with field Area null or empty value I have the classic error :

Object reference not set to an instance of an object

On the line :

ddlCities.Items.FindByValue(hdnval.Value).Selected = true;

I think that inserted in my code this condition resolve the problem but without success :

if (!string.IsNullOrEmpty(hdnval.Value))
{
    ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
}
else
{
    ddlCities.Items.FindByValue(hdnval.Value).Selected = false;
}

Please help me, thank you in advance.

My code below.

protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && gvProducts.EditIndex == e.Row.RowIndex)
    {
        DropDownList ddlCities = (DropDownList)e.Row.FindControl("Area");
        HiddenField hdnval = (HiddenField)e.Row.FindControl("hdnArea");
        string query = " Select distinct Area from ... ; ";
        OdbcCommand cmd = new OdbcCommand(query);
        ddlCities.DataSource = GetData(cmd);
        ddlCities.DataTextField = "Area";
        ddlCities.DataValueField = "Area";
        ddlCities.DataBind();

        if (!string.IsNullOrEmpty(hdnval.Value))
        {
            ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
        }
        else
        {
            ddlCities.Items.FindByValue(hdnval.Value).Selected = false;
        }
    }
}
Antonio Mailtraq
  • 1,397
  • 5
  • 34
  • 82

1 Answers1

0

Please try :

if(ddlCities.Items.FindByValue(hdnval.Value) != null)
{
  ddlCities.Items.FindByValue(hdnval.Value).Selected = true;
}

I hope I have helped you.

Hamamelis
  • 1,983
  • 8
  • 27
  • 41