今天记录一下在gridview中,如果有dropdownlist的情况下使用gridview自带编辑模式的方法。
好吧,今天的这个问题有点绕,详细解释一下目的。
因为gridview中的某些列的数据是从basedata里面带出来的,在编辑gridview的时候,user是想手动选择列值,而不是手动输入(输入不对的话,系统会报错),以上是背景。
OK,想了想,在gridview中可以这样实现这个功能,用gridview自带的编辑模板,数据呈现用label绑定,数据编辑的时候用dropdownlist,下面贴出代码:
前台:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound"> <Columns> <asp:TemplateField HeaderText="category"> <ItemTemplate> <asp:Label ID="label1" runat="server" Text='<%#Bind("category") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="label2" runat="server" Text='<%#Bind("category") %>' CssClass="hideColumn"></asp:Label> <asp:DropDownList ID="drpCategory" runat="server" Width="156px"> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> <asp:CommandField HeaderText="删除" ShowDeleteButton="True" /> </Columns> </asp:GridView>
后台:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGridView(); } } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; BindGridView(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; BindGridView(); } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { int itest = e.Row.RowIndex; if (GridView1.EditIndex == 0) { Label label2 = (Label)e.Row.FindControl("label2"); string strCategory = label2.Text.Trim(); DropDownList drpCategory = (DropDownList)e.Row.FindControl("drpCategory"); BindDropDownList(drpCategory,strCategory); } } } private void BindDropDownList(DropDownList drpCategory,string strCategory) { DataTable dt = new DataTable(); dt.Columns.Add("category"); drpCategory.DataSource = dt; drpCategory.DataBind(); drpCategory.DataTextField = "category"; drpCategory.DataValueField = "category"; drpCategory.Items.Insert(0, new ListItem("请选择", "0")); drpCategory.Items.Insert(1, new ListItem("test1", "test1")); drpCategory.Items.Insert(2, new ListItem("test2", "test2")); drpCategory.Items.Insert(3, new ListItem("test", "test")); drpCategory.SelectedValue = strCategory; } private void BindGridView() { DataTable dt = new DataTable(); dt.Columns.Add("category"); //dt.Rows.Add(dt.NewRow()); DataRow row = dt.NewRow(); row["category"] = "test"; dt.Rows.Add(row); this.GridView1.DataSource = dt; this.GridView1.DataBind(); }
效果截图:
点击编辑
显示dropdownlist,并绑定了label的值
OK,写完啦,睡觉~明天周一继续努力!