如何根据Label.Text自动选择DropDownList

时间:2012-10-12 15:28:39

标签: c# asp.net gridview

DropDownlist中有一个GridView,只有在点击编辑时才会显示DropDownList。我从代码中绑定了DropDownList。当我点击编辑时,该单元格的标签值应自动在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; } } 中选择。

我尝试的代码是:

{{1}}

当我运行代码时,它会在上面代码的最后一行中给出异常错误对象引用未设置。 无法找出什么是错的。请帮助

1 个答案:

答案 0 :(得分:1)

您必须确保您的列表包含标签值。

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