C# 的DataGridView 操做数据库 插入,更新,删除


数据库的主键为ID,若是不设,C#访问会有问题,问题描述:对于不返回任何键列信息的 SelectCommand,不支持 DeleteCommand 的动态 SQL 生成sql



C#代码:数据库

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;




namespace WindowsFormsApplication2
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            BindDataSource();
        }
        string url = null;
        string command = null;
        SqlConnection connect = null;
        SqlDataAdapter adapter = null;
        DataSet tables = null;
        private void BindDataSource()
        {
            url = "server=.;database='STU';uid='sa';pwd='123'";
            connect = new SqlConnection(url);
            connect.Open();
            command = "select * from stu1";
            adapter = new SqlDataAdapter(command,connect);
            tables = new DataSet();
            adapter.Fill(tables,"stu1");
            dataGridView1.DataSource = tables;
            dataGridView1.DataMember = "stu1";
            connect.Close();
           
        }


        private void insert(string id,string name)
        {

            DataRow row = tables.Tables[0].NewRow();
            
            row["ID"] = id;
            row["Name"] = name;
            tables.Tables[0].Rows.Add(row);

            upadte();
        }
        private void upadte()
        {
            SqlCommandBuilder sql_command = new SqlCommandBuilder(adapter);
            adapter.Update(tables.Tables[0]);
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {


        }


        private void button1_Click(object sender, EventArgs e)
        {
            if ((this.textBox1.Text !="") && (this.textBox2.Text != ""))
            {
                insert(this.textBox1.Text, this.textBox2.Text);
            }
            else
                MessageBox.Show("请完整信息");
        }


        private void button2_Click(object sender, EventArgs e)
        {
          /*  DataTable dtShow = new DataTable();
          //  dtShow = (DataTable)this.dataGridView1.DataSource;
            //使用for循环遍历行
            for (int i = 0; i < dtShow.Rows.Count; i++)
            {
                //使用ImportRow方法复制dtShow中的值
                //dtUpdate.ImportRow(dtShow.Rows[i]);
                tables.Tables[0].ImportRow(dtShow.Rows[i]);
            }
           */
           // SqlCommandBuilder sql_command = new SqlCommandBuilder(adapter);
            // adapter.Update(tables.Tables[0]);
ui


            upadte();


        }


        private void button3_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
            upadte();
        }
    }
}
this