dataGridView1.DataSource = testDataSet.Tables[0];



DataSet,DataGridView的相关操作


1. using System;  
2. using System.Data;  
3. using System.Windows.Forms;  
4. using System.Data.SqlClient;  
5.   
6. namespace DataGrid实验2  
7. {  
8. public partial class Form1 : Form  
9.     {  
10. public SqlDataAdapter da;  
11. public DataSet ds;  
12. public DataTable dt;  
13. public Form1()  
14.         {  
15.             InitializeComponent();  
16.         }  
17.   
18. private void Form1_Load(object sender, EventArgs e)  
19.         {  
20.             Datasetsyan();  
21. //dataGridView1.Rows.Add();  
22.   
23.         }  
24. public void Datasetsyan()  
25.         {  
26. string connString = @"  
27.             server = localhost;  
28. true;  
29.             database = student  
30.          ";  
31.   
32. // query  
33. string sql = @"  
34.             select  
35.                studentID,  
36.                studentName,  
37.                studentSex  
38.             from  
39.                stu  
40.          ";  
41.   
42. // create connection  
43. new SqlConnection(connString);  
44.   
45. try  
46.             {  
47. // open connection  
48.                 conn.Open();  
49.   
50. // create data adapter  
51. new SqlDataAdapter(sql, conn);  
52. // create dataset  
53.   
54. new DataSet();  
55. // fill dataset  
56. //, "stu"  
57.   
58. // get data table  
59. //"stu"  
60.   
61.             }  
62. catch (Exception e)  
63.             { MessageBox.Show(e.ToString()); }  
64. finally  
65.             {   
66.                 conn.Close();  
67.             }  
68.         }  
69.   
70. private void button1_Click(object sender, EventArgs e)  
71.         {  
72. //数据源绑定  
73.         }  
74.   
75. private void button2_Click(object sender, EventArgs e)  
76.         {  
77.              
78. new SqlCommandBuilder(da);  
79. //更新数据库  
80.             da.Update(ds);  
81.         }  
82.   
83. private void button3_Click(object sender, EventArgs e)  
84.         {  
85. // 移除当前行  
86.         }  
87.   
88. private void button4_Click(object sender, EventArgs e)  
89.         {  
90.             dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[0].Value= textBox1.Text;  
91. //添加行  
92.             dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells[2].Value = textBox3.Text;  
93.         }  
94.     }  
95. }<pre class="csharp" name="code">实验结果:可以对DataGridView的数据进行删除,添加,并保存到数据库</pre>