为什么我的DataGridView中没有显示任何内容?

时间:2016-03-02 05:04:19

标签: c# datagridview

我正在尝试初始化DataGridView对象。我所做的只是将对象添加到我的屏幕而不更改任何属性。我有代码,当用户选择它所在的面板时运行。代码看起来像这样......

DataTable tbl = new DataTable();
string query = "SELECT viewfolder, status FROM Folders WHERE username = '" + Globals.usrName + "' ORDER BY viewfolder";

SqlConnection connect = new SqlConnection(@"Data Source=(LocalDB)\v11.0;" +
    @"AttachDbFilename=C:\Development\C-Sharp\LockItUp\Lockitup.mdf;Integrated Security=True");

SqlCommand cmd = new SqlCommand(query, connect);

connect.Open();
try
{
    SqlDataAdapter dAdapt = new SqlDataAdapter(cmd);
    dAdapt.Fill(tbl);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
    return;
}
connect.Close();

dataGridView1.DataSource = tbl;

那么我还需要添加其他代码或属性我必须设置以查看数据是否出现在网格上?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此代码:

void FillData()
{

    using (SqlConnection c = new SqlConnection(
    @"Data Source=(LocalDB)\v11.0;" +
@"AttachDbFilename=C:\Development\C-Sharp\LockItUp\Lockitup.mdf;Integrated Security=True"))
    {
    c.Open();

           string query = "SELECT viewfolder, status FROM Folders WHERE username = '" + Globals.usrName + "' ORDER BY viewfolder";
    using (SqlDataAdapter a = new SqlDataAdapter(
        query , c))
    {
        DataTable tbl = new DataTable();
        a.Fill(tbl);
        dataGridView1.DataSource = tbl; 
    }
    }
}