C#中将DataGrid绑定到SQL Server数据库,显示数据库中的数据

思路流程整理

sqlDataadapter的作用是实现 DataTable 和 DB 之间的桥梁

实现方法1(自用): 

string strConn="uid=账号;pwd=密码;database=数据库;server=服务器";//SQL Server链接字符串    
SqlConnection connSql=new SqlConnection (strConn); //Sql链接类的实例化    
connSql.Open ();//打开数据库    
//使用SqlDataAdapter时没有必要从Connection.open()打开,    
//SqlDataAdapter会自动打开关闭它。    
string strSql = "SELECT * FROM 表名"; //要执行的SQL语句    
SqlCommand cmd=new SqlCommand(strSql,connsql);  
SqlDataAdapter da=new SqlDataAdapter(cmd); //创建DataAdapter数据适配器实例    
DataTable dt=new DataTable("tablename");//创建DataSet实例    
da.Fill(dt);//使用DataAdapter的Fill方法(填充)  
datagrid.ItemsSource = dt.DefaultView;  
ConnSql.Close ();//关闭数据库  

实现方法二:

private void updataDataGrid()
        {
            connopen();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "select * from[应力测点] order by 测试日期 asc";
            cmd.CommandType = CommandType.Text;

            SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            datagrid.ItemsSource = dt.DefaultView;
            dr.Close();
        }

实现方法三: 

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修改更新到数据库中的方法    见: 

https://blog.csdn.net/weixin_40626630/article/details/82329097

猜你喜欢

转载自blog.csdn.net/weixin_40626630/article/details/82323182