c#中如何将datatable绑定到datagridview [英] how to bind datatable to datagridview in c#

查看:192
本文介绍了c#中如何将datatable绑定到datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将我的 DataTable 绑定到我的 DataGridView.我这样做:

I need to bind my DataTable to my DataGridView. i do this:

        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 添加新 列.我不需要这个,我只需要在现有列下写.

But all i got is DataTable ADDS NEW columns to my DataGridView. I don't need this, i just need to write under existing columns.

推荐答案

试试这个:

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

如果您不想清除所有现有列,则必须为每个现有列设置 DataPropertyName,如下所示:

If you don't want to clear all the existing columns, you have to set DataPropertyName for each existing column like this:

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;
}

这篇关于c#中如何将datatable绑定到datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆