2017-04-04 42 views
1

我有一個帶有表的數據庫。我想要做的是以編程方式將表的列中的值加載到DataGridView的列中。使用數據庫中的值加載DataGridView中的指定列

我有一個表「行動」,與「總計」字段,其中有一些數據:10,20,35,50等 我想把這個字段放入第二列的DataGridView。

所以DataGridView應該看起來像這樣(其他列已經設置)。

| Name  | Total  | Something | 
|:-----------|------------:|:------------:| 
| adsad  |  10 |  This  | 
| sddssdf |  20 | column | 
| name1  |  35 |  will  | 
| name  |  50 |  be  | 
| nmas  |  1 | center | 
| gjghjhh |  67 | aligned | 

回答

1

您需要創建在GridView中特定的列,並嘗試下面的代碼:

DataGridView dataGridView2 = new DataGridView(); 
BindingSource bindingSource2 = new BindingSource(); 

dataGridView2.ColumnCount = 2; 

dataGridView2.Columns[0].Name = "FieldOne"; 
dataGridView2.Columns[0].DataPropertyName = "FieldOne"; 
dataGridView2.Columns[1].Name = "FieldTwo"; 
dataGridView2.Columns[1].DataPropertyName = "FieldTwo"; 

bindingSource1.DataSource = GetDataTable(); 
dataGridView1.DataSource = bindingSource1; 
0

您可以添加一個新列到你的DataTable,然後將其綁定到你的DataGridView

//call SQL helper class to get initial data 
DataTable dt = sql.ExecuteDataTable("sp_MyProc"); 

dt.Columns.Add("NewColumn", typeof(System.Int32)); 

foreach(DataRow row in dt.Rows) 
{ 
    //need to set value to NewColumn column 
    row["NewColumn"] = 0; // or set it to some other value 
} 

// possibly save your Dataset here, after setting all the new values 
dataGridView1.DataSource = dt; 
+0

我要設置列VALES等於每個記錄的字段的值。所以,如果我有一個表的記錄具有值:10,20,35等字段「總」,我必須將該字段複製到dataGridView中的列。 – Liviu