You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 LeagueExpert column 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 YourDatabaseConnection and YourTableName with your actual connection string and table name.

内容的提问来源于stack exchange,提问作者user7052482

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:04:08