首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

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

2012-01-10 
帮忙解决连接数据库问题一个表单只有button与dataGridView两个控件,现要点击button,在dataGridView中显示

帮忙解决连接数据库问题
一个表单只有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());
}

}

热点排行