在GridView的EditItemTemplate中对控件进行数据绑定

in Develop

gridview内置的编辑功能大大缩短了开发的周期,同时,利用它自带的这些功能大大节省了时间
以前在做开发时,利用gridview的编辑能时,在EditTemplate中添加一些诸如DropDownlist控件等,不知道如何给这些DropDownList绑定一些数据,
在.cs中用FindControls()怎么也找不到这些控件.只得作罢,今日又遇上此类问题,看来是躲不了了,只能解决它了.
因为GridView有一个RowCreated事件,无论是在生成行还是在编辑行时,都会触发该事件,所以,从它下手了,

protected void _gv_main_RowCreated(object sender, GridViewRowEventArgs e)
{
//这里注意Row的RowState属性的枚举
if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
DropDownList dd = (DropDownList)e.Row.FindControl("_dd_colorList");
string[] colorArray = Enum.GetNames(typeof(System.Drawing.KnownColor));
foreach (string color in colorArray)
{
ListItem item = new ListItem(color, color);
item.Attributes.Add("style", "background-color:" + color); dd.Items.Add(item);
}
}
}

这样就可以进行绑定了正在为此沾沾自喜时却发现,点击gridview的更新时,无法获取dropdownlist选中的值看来, 并未结束.
于是,在sqldatasource控件的Updating事件中来解决(因为gridview是绑定在一个sqldatasource上的)

protected void _gv_source_Updating(object sender, SqlDataSourceCommandEventArgs e) {
//找到当前编辑的行,并找到dropdownlist控件
DropDownList dd = (DropDownList)_gv_main.Rows[_gv_main.EditIndex].FindControl("_dd_colorList");
e.Command.Parameters["@color"].Value = dd.SelectedValue; //设定值
}

至此,问题得以解决。

3 Comments

3 Comments

  1. 刚刚碰到这个问题,根据你的思路,终于绑定上下拉列表了。谢谢哈。:d
    但是现在还有一个问题,就是没有办法根据原先的值自动选择项,这个怎么解决?:p

  2. @帅青蛙:
    DropDownList有一个SelectedValue属性,可以利用这个^_^

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>