在edittitemtemplate中使用下拉列表的GridView

本文关键字:下拉列表 GridView edittitemtemplate | 更新日期: 2023-09-27 18:06:34

我有一个GridView与adrpDownList在一个EditItemTemplate。原始数据在标签中,并在编辑模式下传输到ddl。当按下编辑按钮时,我收到一个异常:系统。ArgumentOutOfRangeException: 'ddlCities'有一个无效的SelectedValue,因为它不存在于项目列表中。我在这里发现了一个类似的问题,并根据我的需求调整了代码,如下所示(其中city是从gridView的itemTemplate中的标签接收的字符串):

 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 = <%# Bind("City") %>,否则上述异常再次发生。但现在我想根据ddl中选择的值更新我的数据,我没有成功这样做,因为ddl没有绑定到gridView数据源中的任何东西。我将非常感谢你的帮助。

在edittitemtemplate中使用下拉列表的GridView

在尝试设置下拉菜单的值之前,请确保绑定了下拉菜单。

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;
    }
}

问题显然是我的城市数据是在从右到左的语言(希伯来语),所以当ItemTemplate标签绑定到数据时,它会添加前导空格,因此当绑定到ddl SelectedValue时,它无法在ddl项目列表中找到项目。我通过捕捉RowEditing事件解决了这个问题,并使用Trim()函数从标签中提取文本,并将修剪后的值放入一个名为city的字符串变量中。然后在RowDataBound事件(问题中的代码)中,成功地在ddl中选择了适当的项。因为ddl没有绑定到GridView的数据,所以我无法更新城市列。为此,我捕获了ddl的SelectedIndexChanged事件,并将选中的值放在一个名为ViewState["CitySelect"]的ViewState对象中。然后,当更新时,我捕获了RowUpdating事件,如下所示,它允许根据城市ddl更改成功更新包含城市列的行,即使它没有绑定到gridView数据源。

 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"];
    }

如果有人能提出更简单的建议,我将不胜感激。