2013-10-01 31 views
16

我需要将我的DataTable绑定到我的DataGridView。 我这样做:如何将数据表绑定到c中的datagridview中#

 DTable = new DataTable(); 
     SBind = new BindingSource(); 
     //ServersTable - DataGridView 
     for (int i = 0; i < ServersTable.ColumnCount; ++i) 
     { 
      DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name)); 
     } 

     for (int i = 0; i < Apps.Count; ++i) 
     { 
      DataRow r = DTable.NewRow(); 
      r.BeginEdit(); 
      foreach (DataColumn c in DTable.Columns) 
      { 
       r[c.ColumnName] = //writing values 
      } 
      r.EndEdit(); 
      DTable.Rows.Add(r); 
     } 
     SBind.DataSource = DTable; 
     ServersTable.DataSource = SBind; 

但我的一切是的DataTable增加了新的列到我的的DataGridView。 我不需要这个,我只需要在现有的列下写。 拜托,帮帮我,伙计们!

+1

您没有任何'DataSet',只需要'BindingSource'和'DataTable'。你的'BindingSource'是空白的。 –

回答

16

试试这个:

ServersTable.Columns.Clear(); 
    ServersTable.DataSource = SBind; 

如果您不想清除所有现有列,你必须设置DataPropertyName像这样每个现有列:

for (int i = 0; i < ServersTable.ColumnCount; ++i) { 
    DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name)); 
    ServersTable.Columns[i].DataPropertyName = ServersTable.Columns[i].Name; 
} 
+0

我已经这么做了,只是忘了在帖子中加入。 –

+0

@ Greag.Deay查看我的更新回答 –

+0

是!非常感谢你!!! –

9

更妙的是:

DataTable DTable = new DataTable(); 
BindingSource SBind = new BindingSource(); 
SBind.DataSource = DTable; 
DataGridView ServersTable = new DataGridView(); 

ServersTable.AutoGenerateColumns = false; 
ServersTable.DataSource = DTable; 

ServersTable.DataSource = SBind; 
ServersTable.Refresh(); 

您正在告诉绑定源它绑定了到DataTable,反过来你需要告诉你的DataGridView不要自动生成列,所以它只会将你手动输入到列中的数据拉入控件中......最后刷新控件来更新数据绑定。

+0

看起来你是对的,但现在它只是增加了新的空行而没有填充任何单元格。看起来像datagridview不知道哪些列需要填写。 –

+1

您必须表达SBind.DataMember,通常是该行的ID。您需要为每个列设置DataPropertyName,例如:http://stackoverflow.com/questions/9154130/fill-specific-columns-in-datagridview-from-mysql-data-vb-net – 2013-10-01 12:01:47

+0

是,在DataGridView上你必须设置DataPropertyName。之后,这个解决方案就像一个魅力。非常感谢。 – FrenkyB

3

在DataGridView上,将列的DataPropertyName设置为DataTable的列名称。

0
foreach (DictionaryEntry entry in Hashtable) 
{ 
    datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString()); 
} 
相关问题