Archana B.R
Archana B.R

Reputation: 407

How to make DropDownList automatically be selected based on the Label.Text

I have a DropDownlist in the GridView, which should be visible only when edit is clicked. I have bound the DropDownList from code behind. When I click on Edit, the label value of that cell should automatically get selected in the DropDownList.

The code I have tried is:

protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            SqlCommand cmd = new SqlCommand("SELECT Location_Name FROM Location_Table");
            DropDownList bind_drop = (e.Row.FindControl("DropList") as DropDownList);
            bind_drop.DataSource = this.ExecuteQuery(cmd, "SELECT");
            bind_drop.DataTextField = "Location_Name";
            bind_drop.DataValueField = "Location_Name";
            bind_drop.DataBind();

            string Loc_type = (e.Row.FindControl("id2") as Label).Text.Trim();               
            bind_drop.Items.FindByValue(Loc_type).Selected = true;
        }
    }

When I run the code, it gives an exception error Object reference not set in the last line of the above code. Cannot find out whats wrong. Kindly help

Upvotes: 0

Views: 277

Answers (1)

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28990

You must ensure that your list contains label value.

var index = DropDownList1.Items.IndexOf(Loc_type );
if(index > 0)
{
  DropDownList1.SelectedIndex = index;
}
else
{
  Console.WriteLine("item does not exist");
}

Upvotes: 1

Related Questions