在EditItemTemplate中使用DropDownList的GridView

时间:2011-08-25 14:07:51

标签: c# asp.net gridview drop-down-menu updating

我在EditItemTemplate中有一个带有adrpDownList的GridView。原始数据在标签中,在编辑模式下转移到ddl。当按下编辑按钮时,我收到了一个例外:System.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数据源中的任何内容。我非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

确保在尝试设置其值之前绑定下拉列表。

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

答案 1 :(得分:0)

问题显然是我的城市数据是从右到左的语言(希伯来语)所以当ItemTemplate标签绑定到数据时它会添加前导空格,因此当绑定到ddl SelectedValue时,它无法找到该项目ddl项目列表。我通过捕获RowEditing事件解决了这个问题,并使用Trim()函数从标签中提取了文本,并将修剪后的值放入名为city的字符串变量中。然后在RowDataBound事件(问题中的代码)中选择ddl中的正确项目成功。因为ddl没有绑定到GridView的数据,所以我无法更新city列。为此,我捕获了ddl的SelectedIndexChanged事件,并将所选值放在名为ViewState [“CitySelect”]的ViewState对象中。然后在更新时,我按如下方式捕获了RowUpdating事件,这启用了根据城市ddl更改成功更新包括city列的行,即使它没有绑定到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"];
    }

如果有人能提出更简单的建议我会很感激。