2014-02-27 68 views
0

我想在窗體上有一個網格視圖,當我點擊一個按鈕時,它會將一些測試數據加載到DataGridView中。如何將DataTable設置爲DataGridView,以便DataTable中的數據將顯示DataGridView?

該名稱在屬性中稱爲網格。出於某種原因,我的DataTable沒有被加載到DataGridView中,因此不會顯示在我的表單上。

代碼:

private void button3_Click(object sender, EventArgs e) 
    { 
     DataTable table = new DataTable(); 
     table.Columns.Add("Dosage", typeof(int)); 
     table.Columns.Add("Drug", typeof(string)); 
     table.Columns.Add("Patient", typeof(string)); 
     table.Columns.Add("Date", typeof(DateTime)); 

     table.Rows.Add(25, "Indocin", "David", DateTime.Now); 
     table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); 
     table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); 
     table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); 
     table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); 

     DataGridView grid = new DataGridView(); 
     grid.DataSource = table; 
    } 

enter image description here

+0

您正在創建* new * DataGridView控件。你是否將它添加到表單中?否則,只需更新當前窗體上的網格。 – LarsTech

+1

在'grid.DataSource = table;'行之後添加'grid.DataBind();'。 – Iqbal

+0

@Iqbal它沒有被標記,但圖像顯然是一個WinForm。沒有BindDate()調用。 – LarsTech

回答

2

問題:您沒有添加表格上DataGridView控制這是在運行時創建

解決方案:您需要的DataGridView添加到窗體

添加這些2聲明:

grid1.Location = new Point(100,100);//x and y axis 
    this.Controls.Add(grid1); 

如果創建DataGridView在窗體設計器,你可以使用相同的DataGridView沒有在運行時創建新的數據綁定如下:

替換此:

grid.DataSource = table; 

這一點:

dataGridView1.DataSource = table; 

編輯:更改設計器列的寬度

enter image description here

+0

以下檢查我的答案謝謝。這行得通。有沒有辦法在C#DataGridView能夠拖動打開更多列,或者你必須以編程方式。 –

+0

您可以在設計時創建列併爲每列指定width屬性,或者可以從運行時更改它。看到我編輯的答案。 –

4

試試這個

我已經假定電網表單不會增加運行時間

table.Rows.Add(25, "Indocin", "David", DateTime.Now); 
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); 
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); 
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); 
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); 

dataGridView1.DataSource = table; 

,如果你對按鈕添加gridcontrol點擊事件然後

table.Rows.Add(25, "Indocin", "David", DateTime.Now); 
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); 
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); 
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); 
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); 

    DataGridView grid = new DataGridView(); 
    grid.Location = new Point(50, 50); 
    this.Controls.Add(grid); 
    grid.DataSource = table; 
相關問題