dataGridView1.DataSource = testDataSet.Tables[0];

版权声明:本文为博主原创文章,未经博主允许不得转载。
- using System;
- using System.Data;
- using System.Windows.Forms;
- using System.Data.SqlClient;
- namespace DataGrid实验2
- {
- public partial class Form1 : Form
- {
- public SqlDataAdapter da;
- public DataSet ds;
- public DataTable dt;
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- Datasetsyan();
- //dataGridView1.Rows.Add();
- }
- public void Datasetsyan()
- {
- string connString = @"
- server = localhost;
- integrated security = true;
- database = student
- ";
- // query
- string sql = @"
- select
- studentID,
- studentName,
- studentSex
- from
- stu
- ";
- // create connection
- SqlConnection conn = new SqlConnection(connString);
- try
- {
- // open connection
- conn.Open();
- // create data adapter
- da = new SqlDataAdapter(sql, conn);
- // create dataset
- ds = new DataSet();
- // fill dataset
- da.Fill(ds);//, "stu"
- // get data table
- dt = ds.Tables[0];//"stu"
- }
- catch (Exception e)
- { MessageBox.Show(e.ToString()); }
- finally
- {
- conn.Close();
- }
- }
- private void button1_Click(object sender, EventArgs e)
- {
- dataGridView1.DataSource = dt; //数据源绑定
- }
- private void button2_Click(object sender, EventArgs e)
- {
- SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(da);
- da.UpdateCommand = myCommandBuilder.GetUpdateCommand(); //更新数据库
- da.Update(ds);
- }
- private void button3_Click(object sender, EventArgs e)
- {
- dataGridView1.Rows.Remove(dataGridView1.CurrentRow); // 移除当前行
- }
- private void button4_Click(object sender, EventArgs e)
- {
- dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[0].Value= textBox1.Text;
- dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[1].Value = textBox2.Text; //添加行
- dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[2].Value = textBox3.Text;
- }
- }
- }<pre class="csharp" name="code">实验结果:可以对DataGridView的数据进行删除,添加,并保存到数据库</pre>