GridView与EditItemTemplate中的DropDownList
我在EditItemTemplate中有一个带有adrpDownList的GridView。原始数据在标签中,并且在编辑模式下被转移到ddl。当按下编辑按钮,我收到一个exeption:System.ArgumentOutOfRangeException:'ddlCities'有一个SelectedValue是无效的,因为它不存在于项目列表中。 我发现了一个类似的问题在这里和适应代码到我的需求如下(其中城市是在GridView的ItemTemplate中从标签收到一个字符串):GridView与EditItemTemplate中的DropDownList
protected void gvClients_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (!string.IsNullOrEmpty(city))
{
ddlTemp = (DropDownList)e.Row.Cells[7].FindControl("ddlCities");
if (ddlTemp != null)
{
ListItem item = ddlTemp.Items.FindByValue(city);
if (item != null)
{
item.Selected = true;
}
}
}
}
为了使其工作,我不得不擦除SelectedValue = <%#绑定(“城市”)%>否则上述例外再次发生。但是现在我想根据在ddl中选择的值更新我的数据,并且我没有成功这样做,因为ddl没有绑定到gridView数据源中的任何内容。我非常感谢帮助。
的问题显然是,我的城市的数据是从右到左语言(希伯来语),所以当的ItemTemplate标签绑定到它绑定时添加前导空格,因此数据的DDL的SelectedValue它不能在ddl项目列表中找到该项目。我通过捕获RowEditing事件解决了这个问题,并使用Trim()函数从标签中提取文本,并将修剪后的值放入名为city的字符串变量中。然后在RowDataBound事件(问题中的代码)中,在ddl中选择适当的项目成功。因为ddl没有绑定到GridView的数据,所以我无法更新城市列。为此,我捕获了ddl的SelectedIndexChanged事件,并将所选值放入名为ViewState [“CitySelect”]的ViewState对象中。然后,在更新时,我发现RowUpdating事件如下所示,即使它未绑定到gridView数据源,也会根据城市ddl更改成功更新包含城市列的行。
protected void gvClients_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvClients.Rows[e.RowIndex];
if (ViewState["CitySelect"] != null)
{
e.NewValues.Remove("city");
string tempCity = (string)ViewState["CitySelect"];
e.NewValues.Add("city",tempCity);
row.Cells[7].Text = (string)e.NewValues["city"];
}
else
row.Cells[7].Text = (string)e.OldValues["city"];
}
如果有人可以提出更简单的建议,我将不胜感激。
确保在尝试设置其值之前绑定下拉菜单。
Control ddlCtrl = e.Row.FindControl("ddlCities");
if (ddlCtrl != null)
{
DropDownList ddlCities = ddlCtrl as DropDownList;
//using a datasource control
CitiesDataSourceControl.DataBind();
if (ddlCities.Items.Count > 0)
{
ListItem item = ddlCities.Items.FindByValue("Boston");
if (item != null)
item.Selected = true;
}
}
他们会解决所有问题吗? –
@Bala R:感谢您的评论。我修改了我的答案。 –
dropDownList通过智能标签绑定到数据源,并且在那里也设置DataTextField和DataValueField。 –