我尝试使用以下代码建立与本地SQL服务器的连接:
dataGridView1.Visible = true;
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=.;Initial Catalog=Form;Integrated Security=True";
SqlCommand com = new SqlCommand("select * from Form", con);
SqlDataAdapter sda = new SqlDataAdapter(com);
dataGridView1.DataSource = sda;
但是当我按下表格中的按钮时,它并没有显示数据!我做错了什么?
答案 0 :(得分:1)
您需要使用con.Open();
打开连接。
con.ConnectionString = @"Data Source=.;Initial Catalog=Form;Integrated Security=True";
SqlCommand com = new SqlCommand("select * from Form", con);
con.Open();
此外,您还遇到了许多其他问题,例如您没有丢弃可能导致内存泄漏且无法关闭连接的资源,而且您还没有填充适配器。这是实现它的最佳方式。
using(SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=Form;Integrated Security=True";))
{
con.Open();
SqlCommand com = new SqlCommand("select * from Form", con);
using(SqlDataAdapter sda = new SqlDataAdapter(com));
{
DataTable resultTbl = new DataTable();
sda.Fill(resultTbl);
dataGridView1.DataSource = resultTbl;
dataGridView1.DataBind();
}
}
答案 1 :(得分:1)
你需要这样的东西
dataGridView1.Visible = true;
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=.;Initial Catalog=Form;Integrated Security=True";
con.Open()
SqlCommand com = new SqlCommand("select * from Form", con);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataTable dt=new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;//set it to datatable
dataGridView1.DataBind();