请教:在datagrid里绑定dropdownlist的问题
我想要的效果是:
点击“编辑”,出现下拉列表,并且下拉列表选中用户级别的那一项
请问应该怎么做?
.aspx代码:
......
<asp:TemplateColumn HeaderText= "用户级别 ">
<HeaderStyle Width= "180px "> </HeaderStyle>
<ItemTemplate>
<%# getuserclassname(DataBinder.Eval(Container.DataItem, "userclass ").ToString())%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList id= "ddl_userclass " runat= "server " Width= "100px ">
<asp:ListItem Value= "1 "> 超级管理员 </asp:ListItem>
<asp:ListItem Value= "2 "> 一般管理员 </asp:ListItem>
<asp:ListItem Value= "3 "> 注册会员 </asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>
......
.aspx.cs代码:
......
public string getuserclassname(string userclass)
{
switch(userclass)
{
case "1 ":return "超级管理员 ";break;
case "2 ":return "一般管理员 ";break;
default:return "注册会员 ";break;
}
}
......
------解决方案--------------------//给段代码你参考,是从数据库里读出来的
public class DataGridTemplateColumn2 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgrdTitles;
SqlConnection conPubs;
SqlDataAdapter dadPubs;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
conPubs = new SqlConnection( "server=.;uid=sa;pwd=;database=pubs ");
if(!IsPostBack)
{
BindDataGrid();
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.dgrdTitles.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgrdTitles_CancelCommand);
this.dgrdTitles.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgrdTitles_EditCommand);
this.dgrdTitles.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgrdTitles_ItemDataBound);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void BindDataGrid()
{
dadPubs = new SqlDataAdapter();
dadPubs.SelectCommand = new SqlCommand( "select * from titles ",conPubs);
DataSet dstPubs = new DataSet();
dadPubs.Fill(dstPubs);
this.dgrdTitles.DataSource = dstPubs;
this.dgrdTitles.DataBind();
}
private void dgrdTitles_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
this.dgrdTitles.EditItemIndex = e.Item.ItemIndex;
this.BindDataGrid();
}
private void dgrdTitles_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.EditItem)
{
//保存当前行的type的值
DataRowView drv = (DataRowView)e.Item.DataItem;
string strType = drv[ "type "].ToString();