繁体   English   中英

使用数据库中的值在DataGridView中加载指定的列

[英]Load a specified column in DataGridView with values from a database

我有一个带表的数据库。 我要做的是以编程方式将值从表的列加载到DataGridView的列。

我有一个表“ Actions”,其中的字段“ Total”包含一些数据: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    |

您需要在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;

您可以将新列添加到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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM