在GridView中添加一个字段,并且需要在编辑的时候以DropDownList的形式展现出来,同时要求展示的时候要求显示的数据保存不变。
首先,点击Gridview右上角Gridview 任务 (Gridview Tasks),选择编辑列(Edit Colums),将某字段(比如Place)转化为模板列(Convert this field into a TemplateField )。
然后,进入前台代码 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显示的值,很明显都是从数据库读出来的数据,是一样的值。
接着,进入Gridview的编辑操作(GridView1_RowEditing)事件:
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)
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string script = "";
string bookingID = GridView1.DataKeys[e.RowIndex].Value.ToString();
DropDownList ddl = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("dropdlst_p");
if (DBHandler.UpdateCPList(bookingID, ddl.SelectedValue, userID))//此方法作用是判断是否更新成功,取出droplst_p的选择项进行判断
{
script = "alert('Update Successfully!');";
}
else
{
script = "alert('Update Failed!');";
}
ScriptManager.RegisterStartupScript(this, typeof(Page), "startup", script, true);
gridRpt.EditIndex = -1;//取消编辑状态
BindGV();//重新绑定GridView数据源
}