刪除行,使用DataRow.Delete()方法。Delete()方法不執行刪除操作,僅僅標記要刪除的行。需使用Update方法確認刪除。
using System.Data.SqlClient;
namespace DeleteingData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//刪除按鈕事件
btnDelete.Click += new EventHandler(btnDelete_Click);
ShowData();
}
string sConnection = "Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123";
DataSet dsSet = new DataSet();
SqlDataAdapter sdaAdapter = null;
SqlCommandBuilder scbBuilder = null;
/// <summary>
/// 顯示表中資料
/// </summary>
private void ShowData()
{
//建立Connection
SqlConnection scConnection = new SqlConnection(sConnection);
//建立Command
SqlCommand scCommand = scConnection.CreateCommand();
scCommand.CommandText = "select customerID,companyName from customers";
//建立Adapter
sdaAdapter = new SqlDataAdapter(scCommand);
//該對象負責產生用於更新資料庫的SQL語句,不必自己建立這些語句
scbBuilder = new SqlCommandBuilder(sdaAdapter);
//得到資料
sdaAdapter.Fill(dsSet, "customers");
dgvView.DataSource = dsSet.Tables["customers"];
}
void btnDelete_Click(object sender, EventArgs e)
{
Delete();
}
private void Delete()
{
DataColumn[] dcKeys = new DataColumn[1];
dcKeys[0] = dsSet.Tables["customers"].Columns["customerID"];
//設定表的主鍵
dsSet.Tables["customers"].PrimaryKey = dcKeys;
//尋找主鍵包含的行
DataRow drFindRow = dsSet.Tables["customers"].Rows.Find("ZaCzi");
//刪除資料(此方法不執行刪除操作,僅僅標記要刪除的行)
drFindRow.Delete();
//執行刪除
sdaAdapter.Update(dsSet, "customers");
//重新顯示資料
dgvView.DataSource = dsSet.Tables["customers"];
}
}
}