C#读取SQL2008中的数据,在DataGridView中不能显示。

代码如下:
private void ChaXunbutton_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=gd-sc-gcb;Persist Security Info=True;Initial Catalog=工资管理系统;User ID=sa;Password=sql";
conn.Open();
string strsql = "select 姓名,部门,电话,职务 from 员工信息";
SqlCommand cmd = new SqlCommand(strsql,conn);
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd;
DataSet ds = new DataSet();
ada.Fill(ds);
try
{
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

我点了执行查询后,数据没出来。我之前是读取显示在textBox中的,能成功。今天早上无意看到DataGridView这个神器的,于是改用了DataGridView。我的DataGridView的属性只修改了ScrollBars,其他是全部默认的。请问是什么原因导致数据不能显示,程序应该没错误的吧?求大神帮忙。

private void ChaXunbutton_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection();
 
           conn.ConnectionString = "Data Source=gd-sc-gcb;Persist 
Security Info=True;Initial Catalog=工资管理系统;User ID=sa;Password=sql";
            conn.Open();
            string strsql = "select 姓名,部门,电话,职务 from 员工信息";
            SqlCommand cmd = new SqlCommand(strsql,conn);                      
            SqlDataAdapter ada = new SqlDataAdapter();
            ada.SelectCommand = cmd;
            DataSet ds = new DataSet();
            ada.Fill(ds);
            try
            {
                if (ds.Tables.Count > 0)
                {
                    MessageBox.Show("OK!");//先在这里做个测试看看Table里面有数据没有
                    dataGridView1.DataSource = ds.Tables[0];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
}

追问

有OK的。说明读取成功了嘛。会是什么原因?

追答

你把datagridview的表头去掉先

追问

嗯  。现在可以了。但是总感觉有点别扭得很。

这个是执行查询前的图:


没表头感觉怪怪的:

这是执行查询后的图:

必须去掉表头吗?

追答

那你就换一种赋值的方法了,流表头然后一行一行的给datagridview赋值

追问

那这个该怎弄呢,指点下。或者给点代码。我给你加分。

追答http://blog.csdn.net/whuarui2010/article/details/9141349

温馨提示:答案为网友推荐,仅供参考
相似回答