天天看点

C#操作dataGridView添加数据库中数据,删除dataGridView中的数据

C#操作dataGridView添加数据库中数据,删除dataGridView中的数据

这是我的一篇总结文章,供大家学习参考,便于自己以后的学习。

http://blog.sina.com.cn/s/blog_149e9d2ec0102vur0.html

首先需要using System.Data.SqlClient;

添加数据前:

C#操作dataGridView添加数据库中数据,删除dataGridView中的数据

首先创建数据库(SQLserver2008): create database library on ( name = 'library',--逻辑文件名 filename = 'E:\SQLServer2008\library.mdf',--物理文件名 size = 3MB, maxsize = 10, filegrowth=20% )

log on  ( name = 'library_log', filename='E:\SQLServer2008\library_log.ldf', size = 2MB, maxsize = 20MB, filegrowth = 1MB ) 然后创建一个表,并插入数据: create table student ( id int not null primary key, name varchar(10) not null, sex varchar(2)default '男'  )

insert into student(id, name, sex)values(1,'腾飞','男'),(2,'天地','女'),(3,'顾倩云','女'),(4,'李刚','男') 注:如果数据表命令创建不成功,可以用界面点击操作完成。

C#代码:       private void btn_AddData_Click(object sender,EventArgs e)//数据添加        {           //方法一            //stringid = "4";            //stringname = "Jim";            //stringsex = "男";            //string[]row = { id, name, sex };           //dataGridView1.Rows.Add(row);

          //方法二           //创建行,添加行            stringconStr = @"Data Source=.;initial Catalog=library;User ID =sa;Pwd=241475";           SqlConnection conn = new SqlConnection(conStr);//连接数据库            try            {               conn.Open();//打开数据库               string strSql = "select *from student";//SQL语句

              SqlCommand comm = newSqlCommand(strSql, conn);//执行SQL命令               SqlDataAdapter sda = newSqlDataAdapter(comm);               DataSet ds = newDataSet();               sda.Fill(ds,"student");               dataGridView1.DataSource =ds;               dataGridView1.DataMember ="student";

             dataGridView1.Columns[0].HeaderText = "编号";//更改列名称              //设置dataGridView1控件第一列的列宽              dataGridView1.Columns[0].Width = 85;

             dataGridView1.Columns[1].HeaderText = "姓名";              //设置dataGridView1控件第二列的列宽              dataGridView1.Columns[1].Width = 110;

             dataGridView1.Columns[2].HeaderText = "性别";              //设置dataGridView1控件第三列的列宽              dataGridView1.Columns[2].Width = 105;

                          }            catch(Exception ex)            {               MessageBox.Show(" " +ex);            }           finally            {               conn.Close();            }

       }

完成后显示:

C#操作dataGridView添加数据库中数据,删除dataGridView中的数据

删除dataGridView中的数据: C#代码:        private void btn_DelData_Click(object sender,EventArgs e)        {           //dataGridView1.AllowUserToAddRows = false;//删除最后一行的空白行           dataGridView1.Rows.Remove(dataGridView1.CurrentRow);//删除当前光标所在行            //dataGridView1.Rows.Clear();//删除所有行        }

dataGridviewView中添加和删除功能就实现了,恭喜你已经学会了怎么用了。

可供:学习借鉴