读书人

帮忙解决连接数据库有关问题

发布时间: 2012-01-10 21:26:51 作者: rapoo

帮忙解决连接数据库问题
一个表单只有button 与dataGridView 两个控件,现要点击button ,在dataGridView中显示查询的数据,但下面的语句怎么不行帮忙看看,

private void button1_Click(object sender, EventArgs e)
{
string strcon = " Integrated Security=SSPI;Initial Catalog=pubs ";
SqlConnection conn = new SqlConnection(strcon);
conn.Open();
string strsql = "select * from jobs ";
SqlCommand command = new SqlCommand(strsql, conn);
try
{
command.ExecuteNonQuery();
MessageBox.Show( "提交成功 ");

}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}

SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
this.dataGridView1.DataSource = ds.Tables;
try
{
if (this.dataGridView1.DataSource == null)
MessageBox.Show( "显示错误 ");
else
MessageBox.Show( "显示成功 ");
}


catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}
conn.Close();
}

[解决办法]
this.dataGridView1.DataSource = ds.Tables[0];
[解决办法]
this.dataGridView1.DataSource = ds.Tables[0];
[解决办法]
你这里做查询还 command.ExecuteNonQuery();?
[解决办法]
private void button1_Click(object sender, EventArgs e)
{
string strcon = " Integrated Security=SSPI;Initial Catalog=pubs ";
SqlConnection conn = new SqlConnection(strcon);

string strsql = "select * from jobs ";
SqlCommand command = new SqlCommand(strsql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();

conn.Open();
adapter.Fill(ds);
conn.Close();

this.dataGridView1.DataSource = ds.Tables[0];
try
{
if (this.dataGridView1.DataSource == null)
MessageBox.Show( "显示错误 ");
else
MessageBox.Show( "显示成功 ");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}

}

读书人网 >C#

热点推荐