zoukankan      html  css  js  c++  java
  • 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"];
            }
        }
    }
  • 相关阅读:
    利用数据库复制技术 实现MSSQL数据同步更新
    育子两篇你会教育自已的小孩吗
    hdu 1046 Gridland (找规律题)
    hdu 1022 Train Problem I (栈的操作,还水了半天)
    hdu 4022 Bombing (强大的map一对多的映射)
    POJ 1702 Eva's Balance (数论,平衡三进制)
    hdu 3951 Coin Game (博弈)
    hdu 1058 Humble Numbers (DP初步)
    hdu 2084 数塔 (DP初步)
    hdu 1056 HangOver (打表水题)
  • 原文地址:https://www.cnblogs.com/scottckt/p/1268703.html
Copyright © 2011-2022 走看看