首页 > 学院 > 开发设计 > 正文

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

2019-11-06 07:44:40
字体:
来源:转载
供稿:网友

数据库的主键为ID,如果不设,C#访问会有问题,问题描述:对于不返回任何键列信息的 SelectCommand,不支持 DeleteCommand 的动态 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]);

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表