日期:2014-05-18  浏览次数:20726 次

datagridview数据绑定
怎样将数据库表中的数据绑定到datagridview中的指定地方,谢谢

------解决方案--------------------
C# code

string strSql = "select xm as name from tablename";
DataSet ds = ExecuteSqlDataSet(strSql);
ds = ExecuteSqlDataSet(strSql);
this.datagridview1.DataSource = ds.Tables[0].DefaultView;
this.datagridview1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
this.datagridview1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);

//sconn为你的连接数据库字符串
private DataSet ExecuteSqlDataSet(string strSQL)
        {
            SqlConnection myCn = new SqlConnection(sconn);
            try
            {
                myCn.Open();
                SqlDataAdapter da = new SqlDataAdapter(strSQL, myCn);
                DataSet ds = new DataSet();
                da.Fill(ds, "ds");
                return ds;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                myCn.Close();
            }
        }

------解决方案--------------------
dgv_show.Rows[所需要的行].Cells["xm"].Value = "值";
------解决方案--------------------
select [Name] = xm from table....这样xm字段就对应Name列了