如何在c#中将数据表绑定到datagridview

ani*_*kun 18 .net c# data-binding datagridview winforms

我需要将我的DataTable绑定到我的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;
Run Code Online (Sandbox Code Playgroud)

但我得到的只是DataTable ADDS NEW列到我的DataGridView.我不需要这个,我只需要在现有列下编写. 伙计们,帮助我吧!

Kin*_*ing 20

试试这个:

    ServersTable.Columns.Clear();
    ServersTable.DataSource = SBind;
Run Code Online (Sandbox Code Playgroud)

如果您不想清除所有现有列,则必须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;
}
Run Code Online (Sandbox Code Playgroud)


小智 10

更好的是:

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();
Run Code Online (Sandbox Code Playgroud)

你告诉可绑定的源它绑定到DataTable,你需要告诉你的DataGridView不要自动生成列,所以它只会为你手动输入到控件中的列提取数据. ..最后刷新控件以更新数据绑定.

  • 您必须表达 SBind.DataMember,通常是行的 ID。您需要为每一列设置 DataPropertyName,例如:http://stackoverflow.com/questions/9154130/fill-specific-columns-in-datagridview-from-mysql-data-vb-net (2认同)