c#
  • datagridview
  • 2016-03-02 68 views 0 likes 
    0

    我試圖初始化一個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; 
    

    那麼,有沒有其他的代碼,我要補充或我必須設置看對電網的數據顯示屬性?謝謝您的幫助。

    +2

    u能看到的列標題?你確定查詢返回一些數據嗎?因爲你的代碼似乎沒問題.. – Olivarsham

    +0

    我甚至沒有看到列標題。 –

    +0

    您需要設置['dataGridView1.AutoGenerateColumns = true;'](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autogeneratecolumns%28v=vs.110%29。 aspx)或在代碼中添加你想要的列。 – TaW

    回答

    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; 
        } 
        } 
    } 
    
    相關問題