在应用DataGrid的编辑模版列的时候,要用到DropDownList控件,用来显示所有的类别以便在编辑时可以修改类别,TextBox控件可以直接设置Text='<%# DataBinder.Eval(Container.DataItem,"type") %>,这样编辑模版列中的TextBox控件就可以绑定当前的数据了,但是DropDownList不能这么简单,开始的时候我想再点击编辑按钮时绑定DropDownList,即在EditCommand事件中绑定,
DataSet ds=new DataSet();
DataInitial di=new DataInitial();
ds=di.GetArticleType(Convert.ToInt32(NewsType.Btype),0);
DropDownList ddlst=(DropDownList)e.Item.FindControl("ddl_Btype");
ddlst.DataSource=ds;
ddlst.DataBind();
但在这ddlst得不到任何值,后来网上一搜说要在ItemDataBound
事件里绑定,ItemDataBound 事件里的代码如下:
DataInitial di=new DataInitial();
ds=di.GetArticleType(Convert.ToInt32(NewsType.Btype),0);
DropDownList ddlst=(DropDownList)e.Item.FindControl("ddl_Btype");
ddlst.DataSource=ds;
ddlst.DataBind();
if (e.Item.ItemType==ListItemType.EditItem)//确定是编辑项
{
DataSet ds=new DataSet();
DataInitial di=new DataInitial();
ds=di.GetArticleType(Convert.ToInt32(NewsType.Btype),0);
DropDownList ddlst=(DropDownList)e.Item.FindControl("ddl_Btype");
ddlst.DataSource=ds;
ddlst.DataBind();
ddlst.SelectedValue=btypeid.ToString();
}
这样DropDownList就得到值了,后来MSDN上查看ItemDataBound事件:“当项被数据绑定到 DataGrid 控件后,将引发
ItemDataBound 事件。此事件为您提供了在客户端显示数据项之前访问该数据项的最后机会。当引发此事件后,该数据项将被设为空,并且不再可用
”。上面这段即为MSDN上的解释,我们在程序中无论点击编辑,更新或者删除时都会调用一下数据绑定方法,ItemDataBound
事件是对数据项最后访问机会,所以要在此时绑定我们的DropDownList,如果在DataGrid绑定完后 在绑定DropDownList会无效。{
DataSet ds=new DataSet();
DataInitial di=new DataInitial();
ds=di.GetArticleType(Convert.ToInt32(NewsType.Btype),0);
DropDownList ddlst=(DropDownList)e.Item.FindControl("ddl_Btype");
ddlst.DataSource=ds;
ddlst.DataBind();
ddlst.SelectedValue=btypeid.ToString();
}