c#中如何将datatable绑定到datagridview

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19114635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:08:22  来源:igfitidea点击:

how to bind datatable to datagridview in c#

c#.netwinformsdata-bindingdatagridview

提问by animekun

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

我需要将我的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;

But all i got is DataTableADDS NEWcolumns to my DataGridView. I don't need this, i just need to write under existing columns. please, help me, guys!

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

采纳答案by King King

Try this:

尝试这个:

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

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

如果您不想清除所有现有列,则必须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;
}

回答by King King

Even better:

更好的是:

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();

You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.

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

回答by Marc K

On the DataGridView, set the DataPropertyName of the columns to your column names of your DataTable.

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

回答by Jegadeesh Sakthivel

foreach (DictionaryEntry entry in Hashtable)
{
    datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}

回答by Cwinds

// I built my datatable first, and populated it, columns, rows and all. //Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.

// 我首先构建了我的数据表,并填充了它的列、行和所有内容。//然后,一旦数据表起作用,请执行以下操作将其绑定到 DGV。注意:对于此示例,DGV 的 AutoGenerateColumns 属性必须为“true”,否则将无法将列名从数据表“分配”到 dgv。我之前也将我的数据表“添加”到数据集,但我认为没有必要。

 BindingSource SBind = new BindingSource();
 SBind.DataSource = dtSourceData;

 ADGView1.AutoGenerateColumns = true;  //must be "true" here
 ADGView1.Columns.Clear();
 ADGView1.DataSource = SBind;

 //set DGV's column names and headings from the Datatable properties
 for (int i = 0; i < ADGView1.Columns.Count; i++)
 {
       ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
       ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
 }
 ADGView1.Enabled = true;
 ADGView1.Refresh();

回答by Parag555

private void Form1_Load(object sender, EventArgs e)
    {
        DataTable StudentDataTable = new DataTable("Student");

        //perform this on the Load Event of the form
        private void AddColumns() 
        {
            StudentDataTable.Columns.Add("First_Int_Column", typeof(int));
            StudentDataTable.Columns.Add("Second_String_Column", typeof(String));

            this.dataGridViewDisplay.DataSource = StudentDataTable;
        }
    }

    //Save_Button_Event to save the form field to the table which is then bind to the TableGridView
    private void SaveForm()
        {
            StudentDataTable.Rows.Add(new object[] { textBoxFirst.Text, textBoxSecond.Text});

            dataGridViewDisplay.DataSource = StudentDataTable;
        }

回答by abdelilah dehaoui

for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps : step 1 - get all Users by :

例如,我们希望通过以下 2 个步骤将 DataTable 'Users' 设置为 DataGridView:第 1 步 - 通过以下方式获取所有用户:

public DataTable  getAllUsers()
    {
        OracleConnection Connection = new OracleConnection(stringConnection);
        Connection.ConnectionString = stringConnection;
        Connection.Open();

        DataSet dataSet = new DataSet();

        OracleCommand cmd = new OracleCommand("semect * from Users");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = Connection;

        using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
        {
            dataAdapter.SelectCommand = cmd;
            dataAdapter.Fill(dataSet);
        }

        return dataSet.Tables[0];
    }

step 2- set the return result to DataGridView :

步骤 2- 将返回结果设置为 DataGridView :

public void setTableToDgv(DataGridView DGV, DataTable table)
    {
        DGV.DataSource = table;
    }

using example:

使用示例:

    setTableToDgv(dgv_client,getAllUsers());