日期:2014-05-19  浏览次数:20534 次

怎么在.aspx文件中初始化datagrid的EditItemTemplate的DropDownList

<asp:TemplateColumn   HeaderText= "部门 ">
<ItemTemplate>
<asp:Label   id=Label3   runat= "server "   Text= ' <%#   DataBinder.Eval(Container,   "DataItem.dname ")   %> '>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList   id= "DDL_name "   runat= "server "> </asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>


private   void   dgd_employlist_EditCommand(object   source,   DataGridCommandEventArgs   e)
{
dgd_employlist.EditItemIndex   =(int)e.Item   .ItemIndex   ;
//初始化DDL_name部门选择下拉表
 
string   conn=   ConfigurationSettings.AppSettings[ "dsn "];
//连接本地计算机的MMS数据库
SqlConnection   cn0=   new   SqlConnection   (conn);
cn0.Open   ();
string   mysql= "select   *   from   depart   ";
SqlCommand   cmm=new   SqlCommand     (mysql,cn0);
SqlDataReader   dr=cmm.ExecuteReader   ();
while(dr.Read   ())
{
DropDownList   ddl=((DropDownList)e.Item.FindControl   ( "DDL_name "));
ddl.Items.Add   (new   ListItem(dr[ "dname "].ToString(),dr[ "dno "].ToString()   ));
}
cn0.Close   ();
BindGrid();  
}

------解决方案--------------------
ItemDataBinded事件中处理
------解决方案--------------------
请参考

private void dgrdTitles_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.EditItem || e.Item.ItemType == ListItemType.AlternatingItem)
{
//保存当前行的type的值
DataRowView drv = (DataRowView)e.Item.DataItem;
string strType = drv[ "type "].ToString();

//对DropDownList做数据绑定
DropDownList dropTemp = (DropDownList)e.Item.Cells[2].Controls[1];

string strSql = "select distinct type from titles ";
dadPubs.SelectCommand.CommandText = strSql;

DataSet dstTemp = new DataSet();
dadPubs.Fill(dstTemp, "types ");

dropTemp.DataSource = dstTemp.Tables[ "types "];
dropTemp.DataTextField = "type ";
dropTemp.DataBind();

//到DropDownList中根据type的值去找需要设置为选中状态的项目,将其设置为选中
ListItem item = dropTemp.Items.FindByText(strType);
if(item != null)
{
item.Selected = true;
}
}
}