如何将选定的组合框项添加到数据表?

时间:2015-08-13 00:29:16

标签: c# datagridview combobox

我有一个使用DataTable作为其DataSource的DataGridView,然后我将DataGridViewComboBoxColumn添加到DataGridView。到目前为止,一切都很好。但是,当用户从组合框列中选择一个项目时,所选项目不包含在DataGridView的DataSource中。有没有办法可以将所选项目包含到DataSource中而不是循环访问DataGridView?

dgvNewChargesChild.DataSource = null;

//dt is some DataTable
dgvNewChargesChild.DataSource = dt;

//create a combobox column
DataTable cbDT = new DataTable();
cbDT.Columns.Add("ChargeType", typeof(string));
cbDT.Columns.Add("ChargeTypeID", typeof(string));
cbDT.Rows.Add(new object[] { "Storage", "1" });
cbDT.Rows.Add(new object[] { "BankService", "2" });

DataGridViewComboBoxColumn cbCol = new DataGridViewComboBoxColumn();
cbCol.ValueMember = "ChargeTypeID";
cbCol.DisplayMember = "ChargeType";
cbCol.DataSource = cbDT;

//add combobox column to the datagridview
dgvNewChargesChild.Columns.AddRange(cbCol);

//get the datasource of the datagridview after user makes a selection from the DataGridViewComboBoxColumn
DataTable newDT = (DataTable) dgvNewChargesChild.DataSource;

//this newDT does not include the selected item from the combobox.

0 个答案:

没有答案