以下是一个示例,可能需要进行一些更改以适应您的代码。这个想法是使用 BindingSource 设置 DataGridView 数据源,该数据源具有表中所需的列以获取成员详细信息。数据操作在一个类中,用于将前端操作与数据操作分开。请注意,不需要过度杀伤的 SqlDataAdapter。
对于删除操作,最好使用主键,因为这是恒定的,而名称可能会在某些时候发生变化。
以下类是读取和删除操作的模型,请确保您了解它不是复制粘贴解决方案,因此请在尝试之前花时间阅读代码。
数据类
using System.Collections.Generic;
using System.Data.SqlClient;
namespace YourNamespace
{
public class MembershipOperations
{
/// <summary>
/// Connection string to your database
/// - change TODO to your environment
/// - Integrated Security (check this too)
/// </summary>
private static readonly string _connectionString =
"Data Source=****TODO****;" +
"Initial Catalog=****TODO****;" +
"Integrated Security=True";
/// <summary>
/// Delete a single member by primary key
/// Recommend adding a try-catch to the open and ExecuteNonQuery lines
/// </summary>
/// <param name="memberIdentifier">Member primary key</param>
/// <returns>
/// Success of the operation
/// </returns>
public static bool RemoveSingleOrder(int memberIdentifier)
{
bool success = false;
string deleteStatement = "DELETE FROM membersdetails WHERE id = @id";
using (var cn = new SqlConnection { ConnectionString = _connectionString })
{
using (var cmd = new SqlCommand { Connection = cn, CommandText = deleteStatement })
{
cmd.Parameters.AddWithValue("id", memberIdentifier);
cn.Open();
success = cmd.ExecuteNonQuery() == 1;
}
}
return success;
}
/// <summary>
/// Provides a list which in the frontend a user can select
/// a member such as a ComboBox or ListBox etc.
///
/// When they select a user you have code to cast the selected item
/// to a MemberDetails instance and pass the primary key to the RemoveSingleOrder
/// method.
///
/// Note in the frontend if there are many members consider providing a incremental
/// search feature to the frontend control displaying member details.
/// </summary>
/// <returns></returns>
public static List<MemberDetails> GetMemberDetails()
{
var memberDetails = new List<MemberDetails>();
/*
* - Create a connection and command object with
* SELECT column names including 'id' primary key
*
* - Use a DataReader to loop through records into
* memberDetails variable
*/
return memberDetails;
}
}
/// <summary>
/// Place in a class file named MemberDetails.cs
/// </summary>
public class MemberDetails
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// more properties
/// <summary>
/// Optional, can assist with debugging and/or
/// for display purposes
/// </summary>
/// <returns></returns>
public override string ToString() => $"{FirstName} {LastName}";
}
}
帮助方法用默认按钮提问是否,不是是。
使用 System.Windows.Forms;
namespace YourNamespace
{
public static class Dialogs
{
public static bool Question(string text)
{
return (MessageBox.Show(
text,
Application.ProductName,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes);
}
}
}
表单代码
using System;
using System.Windows.Forms;
namespace YourNamespace
{
public partial class Form1 : Form
{
private readonly BindingSource _membersBindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
Shown += Form1_Shown;
}
/// <summary>
/// Setup columns in the IDE for MembersDataGridView that
/// exclude the primary key
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Shown(object sender, EventArgs e)
{
MembersDataGridView.AutoGenerateColumns = false;
_membersBindingSource.DataSource = MembershipOperations.GetMemberDetails();
MembersDataGridView.DataSource = _membersBindingSource;
}
private void RemoveMemberButton_Click(object sender, EventArgs e)
{
if (_membersBindingSource.Current == null) return;
var member = (MemberDetails)_membersBindingSource.Current;
if (!Dialogs.Question($"Remove {member}")) return;
if (!MembershipOperations.RemoveSingleOrder(member.Id))
{
MessageBox.Show($"Failed to remove {member}");
}
}
}
}