在GridView中添加一个字段,并且需要在编辑的时候以DropDownList的形式展现出来,同时要求展示的时候要求显示的数据保存不变。
然后,进入前台代码 xxx.aspx页面,对该字段的列进行编辑:
<%------------------------------------ Place------------------------------------%> <asp:TemplateField HeaderText="Place"> <EditItemTemplate> <asp:DropDownList ID="dropdlst_p" runat="server"> <asp:ListItem Value="1">A窗口</asp:ListItem> <asp:ListItem Value='2'>B窗口</asp:ListItem> <asp:ListItem Value='3'>C窗口</asp:ListItem> <asp:ListItem Value='4'>D窗口</asp:ListItem> <asp:ListItem Value='5'>E窗口</asp:ListItem> <asp:ListItem Value='6'>F窗口</asp:ListItem> </asp:DropDownList><asp:Label ID="lblHidden" runat="server" Text='<%# Bind("Place") %>' Visible="false"></asp:Label> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblP" runat="server" Text='<%# Bind("Place") %>'></asp:Label> </ItemTemplate> <HeaderStyle Font-Bold="True" Font-Size="9pt" Width="200px" /> <ItemStyle Font-Size="9pt" Width="400px" Wrap="False" /> </asp:TemplateField>对上面两个Label说明:第一个Label将在后面用到取值,作为中间变量的作用,不需要显示出来,所以隐藏了;而第二个Label的就是GridView显示的值,很明显都是从数据库读出来的数据,是一样的值。
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex;//进入编辑状态 BindGV();//对Gridview绑定数据 DropDownList dropdl=(DropDownList)GridView1.Rows[e.NewEditIndex].FindControl("dropdlst_p"); string selectedText = ((Label)GridView1.Rows[e.NewEditIndex].FindControl("lblHidden")).Text;//取出DropDownList "dropdlst_p"原先显示的数据 for (int i = 0; i < dropdl.Items.Count; i++)//遍历dropdlst_p中的所有数据 { if (dropdl.Items[i].Text == selectedText) { dropdl.Items[i].Selected = true;//选中dropdlst_p的原先显示的数据项 } } }最后,对数据进行更新(GridView1_RowUpdating)
联系客服