日期:2014-05-18 浏览次数:20878 次
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();
}
------解决方案--------------------
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;