欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF C#将DataGrid绑定到数据库中读取的数据,并把变化更新到数据库

程序员文章站 2022-06-07 18:10:51
...

在网上看了好多帖子,关于绑定有说用context属性的,也有用DataSource属性的,还有用bindingsource,都未果。最后拼凑出这个办法。代码如下:

static string connString = @"Server=localhost\SQLEXPRESS;Database=StaffAdmin;Trusted_Connection=True;";
SqlConnection connection = new SqlConnection(connString);  //设置连接到数据库的SqlConnection
string sql = @"Select * from Staff";
 DataSet ds = new DataSet();
 SqlDataAdapter da = new SqlDataAdapter(sql, connection);  //创建SqlDataAdapter实例da,并指定SQL查询string和SqlConnection
           
 da.Fill(ds,"Staff");  //从数据库中读取数据,并填充ds
 DataView dv = new DataView(ds.Tables["Staff"]);  创建DataView实例dv,并指定其DataTable
 StaffAdminView.ItemsSource = dv;  //设置DataGrid的ItemsSource属性

 

到这里,就完成了数据库中数据的读取和绑定到DataGrid,如果要把在DataGrid中做的更改保存到数据库中,还要添加以下代码。

SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sql, connection);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
dt = ((DataView)StaffAdminView.ItemsSource).Table;
da.Update(ds.Tables["Staff"]);  //DataGrid和ds的table绑定之后,DataGrid的更改会自动更新到Dataset