天天看點

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中添加和删除功能就實作了,恭喜你已經學會了怎麼用了。

可供:學習借鑒