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

datagrilview 绑定数据源源代码
求 datagrilview 绑定sql数据源源代码

------解决方案--------------------
SqlConnection conn = GetCon();//自定义的一个获得一个数据库连接函数
SqlDataAdapter sda = new SqlDataAdapter("select RoomName,RoomJC,RoomBJF,RoomWZ,RoomType,RoomBZ,ID from tb_Room order by ID desc", conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];

从别人的项目里面摘出来的一段代码,看看有么有帮助
------解决方案--------------------
一般提问最好贴代码说明哪里出错才好指出。

------解决方案--------------------
你datagridview列绑定数据源字段了吗?
------解决方案--------------------
C# code
   private static SqlConnection conn;
        public static SqlConnection Conn
        {

            get
            {
                try
                {
                    
                    string connstr = "server=.;database=Driver;User ID=sa;Password=123456";
                    if (conn == null)
                        conn = new SqlConnection(connstr);
                    if (conn.State == ConnectionState.Closed)
                        conn.Open();
                    if (conn.State == ConnectionState.Broken)
                    {
                        conn.Close();
                        conn.Open();
                    }
                    return conn;

                }
                catch (Exception ex)
                {

                    throw;
                }
            }
        }

  //查询:DataTable
        public static DataTable GetTable(string SqlStr)
        {
            try
            {      
            SqlDataAdapter dap = new SqlDataAdapter(SqlStr, Conn);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            conn.Close();
            return ds.Tables[0];
            }
            catch (Exception ex)
            {

                throw;
            }
        }


dataGridView1要添加显示列的,,DataPropertyName要和数据库字段对应
   DataTable dt =GetTable("Select * from  users order by create_date");
            this.dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = dt;

------解决方案--------------------
protected void Page_Load(object sender, EventArgs e)
{
DataBind();

public void DataBind()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test(你的数据库名);Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from test1";
cmd.Connection = con;
DataTable dt = new DataTable();
con.Open();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}


------解决方案--------------------
C# code
SqlConnection conn = new SqlConnection("连接字符串");
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("查询语句", conn);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
sda.Dispose();
conn.Dispose();

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtbl;