1. DataGridView中增加一列为COMBOX并绑定数据源
DataGridViewComboBoxColumn newColumn = new DataGridViewComboBoxColumn();
newColumn.DataSource = stateList;
newColumn.DisplayMember = "State";
newColumn.ValueMember = "State_id";
dataGridViewRectangle.Columns.Insert(1, newColumn);
newColumn.HeaderText = "State";
newColumn.Name = "dgv_State";
dataGridViewRectangle.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridViewRectangle_EditingControlShowing);
2. DataGridView中的COMBOX绑定值
foreach (DataGridViewRow dgvRow in dataGridViewRectangle.Rows)
{
LongLatInfoModel model = dgvRow.DataBoundItem as LongLatInfoModel;
dgvRow.Cells[1].Value = model.lli_taskStateid;
}
void dataGridViewRectangle_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridView dataGridView = (DataGridView)sender;
if ((dataGridView.CurrentCell.GetType().Name == "DataGridViewComboBoxCell") && !isLoadChange )
{
ComboBox comboBox = (ComboBox)e.Control;
comboBox.SelectionChangeCommitted += new EventHandler(comboBox_SelectedIndexChanged);
}
if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
{
DataGridViewComboBoxEditingControl cbo = e.Control as DataGridViewComboBoxEditingControl;
cbo.DropDownStyle = ComboBoxStyle.DropDownList;
}
isLoadChange = true;
}
3.当dataGridView中只有一行时,最后删除,有时会提示有索引-1没有值的异常,此时通过隐藏行代替删除时的解决办法,由于行中有comboBox,必须先清除comboBox中的选项,才能在列表中不显示该行,否则行还是显示,只是数据没有加载。
if (dataGridViewRectangle.Rows.Count == 1 && dgvRow.Index == 0)
{
cm.SuspendBinding();
dgvRow.Visible = false;
cm.ResumeBinding();
comboBox.DataSource = null;
comboBox.Items.Clear();
}
else
{
dataGridViewRectangle.Rows.Remove(dgvRow);
dataGridViewRectangle.Refresh();
}
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。