ASP.NET开发:如何切换GridView编辑模板并保存CheckBoxList到数据库
Solution for GridView CheckBoxList Edit & Save in ASP.NET
Let's break down how to handle both your requirements with clear, actionable code:
1. Setup GridView Markup
First, complete your GridView template to properly show a read-only label in view mode and the CheckBoxList when editing:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" OnRowEditing="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound" OnRowUpdating="GridView1_RowUpdating"> <Columns> <asp:CommandField ShowEditButton="True" ShowUpdateButton="True" ShowCancelButton="True"/> <asp:TemplateField HeaderText="LeagueExpert" SortExpression="LeagueExpert"> <!-- View mode: Display selected values as text --> <ItemTemplate> <asp:Label ID="lblLeagueExpert" runat="server" Text='<%# Eval("LeagueExpert") %>'></asp:Label> </ItemTemplate> <!-- Edit mode: Show CheckBoxList for selection --> <EditItemTemplate> <asp:CheckBoxList ID="cblLeagueExpert" runat="server" RepeatColumns="2"> <!-- Add your desired options here, or bind dynamically --> <asp:ListItem Text="Football" Value="Football"></asp:ListItem> <asp:ListItem Text="Basketball" Value="Basketball"></asp:ListItem> <asp:ListItem Text="Tennis" Value="Tennis"></asp:ListItem> <asp:ListItem Text="Baseball" Value="Baseball"></asp:ListItem> </asp:CheckBoxList> </EditItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <!-- Configure your SqlDataSource with update support --> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:YourDatabaseConnection %>" SelectCommand="SELECT ID, LeagueExpert FROM YourTableName" UpdateCommand="UPDATE YourTableName SET LeagueExpert = @LeagueExpert WHERE ID = @ID"> <UpdateParameters> <asp:Parameter Name="LeagueExpert" Type="String" /> <asp:Parameter Name="ID" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource>
2. Handle Edit Mode Switch & Populate CheckBoxList
Add these code-behind methods to switch to edit mode and pre-select values from the database:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { // Set the selected row to edit mode GridView1.EditIndex = e.NewEditIndex; GridView1.DataBind(); } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { // Only process rows in edit mode if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) { // Find the CheckBoxList in the edit row CheckBoxList cblLeagueExpert = (CheckBoxList)e.Row.FindControl("cblLeagueExpert"); // Get the existing comma-separated value from the database string existingValues = DataBinder.Eval(e.Row.DataItem, "LeagueExpert").ToString(); string[] selectedValues = existingValues.Split(','); // Pre-select the matching items in the CheckBoxList foreach (ListItem item in cblLeagueExpert.Items) { item.Selected = selectedValues.Contains(item.Value); } } }
3. Save CheckBoxList Selections to Database
Add this method to capture selected values and update the database when the user clicks "Update":
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { // Get the current edit row GridViewRow row = GridView1.Rows[e.RowIndex]; // Retrieve the CheckBoxList from the row CheckBoxList cblLeagueExpert = (CheckBoxList)row.FindControl("cblLeagueExpert"); // Combine selected values into a comma-separated string string selectedValues = string.Join(",", cblLeagueExpert.Items.Cast<ListItem>() .Where(item => item.Selected) .Select(item => item.Value)); // Get the record ID from GridView DataKeys int recordId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value); // Update the SqlDataSource parameters SqlDataSource1.UpdateParameters["LeagueExpert"].DefaultValue = selectedValues; SqlDataSource1.UpdateParameters["ID"].DefaultValue = recordId.ToString(); // Execute the update SqlDataSource1.Update(); // Exit edit mode and refresh the GridView GridView1.EditIndex = -1; GridView1.DataBind(); }
Key Notes:
- I assumed your
LeagueExpertcolumn stores values as a comma-separated string (common for multi-select values). Adjust the split/join logic if you use a different storage format. - Make sure to replace
YourDatabaseConnectionandYourTableNamewith your actual connection string and table name.
内容的提问来源于stack exchange,提问作者user7052482
相关产品推荐
相关产品推荐

