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

如何使用C#在Telerik RadGridView中通过复选框删除数据库记录

Got it, let’s break down exactly how to add checkbox-based record deletion to Telerik’s RadGridView using C#—I’ve implemented this multiple times, so here’s a practical, step-by-step solution that covers all the bases:

1. Add a CheckBox Column to Your RadGridView

First, you need a way for users to select rows. You can do this either in the Visual Studio designer or via code:

Option 1: Code-Based Column Addition

// Create and configure the checkbox column
var checkBoxColumn = new GridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "Select";
checkBoxColumn.Name = "SelectColumn"; // Unique name to reference later
checkBoxColumn.Width = 80;

// Insert it as the first column for visibility
radGridView1.Columns.Insert(0, checkBoxColumn);

Option 2: Designer-Based Addition

  1. Open your form in the designer, select the RadGridView.
  2. Click the tiny arrow to open the GridView Tasks menu.
  3. Choose Edit Columns, then click Add and select GridViewCheckBoxColumn.
  4. Set its Name to SelectColumn and HeaderText to "Select", then save.
2. Capture Selected Rows for Deletion

Add a delete button to your form, then write code to collect all checked rows when the button is clicked:

private void btnDeleteSelected_Click(object sender, EventArgs e)
{
    // Collect all rows with the checkbox checked
    var selectedRows = new List<GridViewDataRowInfo>();
    foreach (GridViewDataRowInfo row in radGridView1.Rows)
    {
        if (Convert.ToBoolean(row.Cells["SelectColumn"].Value))
        {
            selectedRows.Add(row);
        }
    }

    // Guard against empty selection
    if (selectedRows.Count == 0)
    {
        MessageBox.Show("Please select at least one record to delete.", "No Rows Selected");
        return;
    }

    // Confirm deletion to prevent accidental clicks
    var confirmResult = MessageBox.Show(
        $"Are you sure you want to delete {selectedRows.Count} record(s)?",
        "Confirm Deletion",
        MessageBoxButtons.YesNo,
        MessageBoxIcon.Warning);
    
    if (confirmResult != DialogResult.Yes)
    {
        return;
    }

    // Proceed to delete logic (covered next)
    DeleteSelectedRecords(selectedRows);
}
3. Delete Records from the Database

Now implement the actual database deletion. I’ll use ADO.NET with transactions to ensure all deletes succeed or fail together (no partial deletions):

private void DeleteSelectedRecords(List<GridViewDataRowInfo> selectedRows)
{
    // Replace with your actual connection string
    var connectionString = "Server=YOUR_SERVER;Database=YOUR_DB;Trusted_Connection=True;";
    
    using (var conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using (var transaction = conn.BeginTransaction())
        {
            try
            {
                foreach (var row in selectedRows)
                {
                    // Replace "Id" with your table's primary key column name
                    var recordId = Convert.ToInt32(row.Cells["Id"].Value);
                    var deleteQuery = "DELETE FROM YourTableName WHERE Id = @RecordId";

                    using (var cmd = new SqlCommand(deleteQuery, conn, transaction))
                    {
                        cmd.Parameters.AddWithValue("@RecordId", recordId);
                        cmd.ExecuteNonQuery();
                    }
                }

                // Commit only if all deletes work
                transaction.Commit();
                MessageBox.Show("Records deleted successfully!", "Success");

                // Refresh the grid to remove deleted rows
                // If using a bound list (e.g., List<YourModel>), remove items from the list first then refresh
                radGridView1.Reload(); 
            }
            catch (Exception ex)
            {
                // Rollback on any error
                transaction.Rollback();
                MessageBox.Show($"Error deleting records: {ex.Message}", "Deletion Failed");
            }
        }
    }
}
4. Key Best Practices to Remember
  • Data Source Sync: If you’re binding to an in-memory list (like List<Customer>) instead of a direct database source, remove the deleted items from the list before calling radGridView1.Refresh().
  • Batch Deletes: For large numbers of rows, use a table-valued parameter to delete all records in one query instead of looping (much faster).
  • Validation: Add checks for read-only rows or locked records if your app requires it.
  • Error Logging: Beyond showing a message box, log errors to a file or service for debugging later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:06:02