c# 删除表中的行


删除行,使用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"];
        }
    }
}
原文地址:https://www.cnblogs.com/scottckt/p/1268703.html