如何在c#中将datatable绑定到datagridview

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

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

试试这个:

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

更好的是:

 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不要自动生成列,所以它只会为你手动输入到控件中的列提取数据。 ..最后刷新控件以更新数据绑定。

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

//我首先构建了我的数据表,并填充了它,列,行和所有。 //然后,一旦数据表正常运行,请执行以下操作将其绑定到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(); 
 foreach (DictionaryEntry entry in Hashtable) { datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString()); } 
 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; }