在DataGridView中添加列 时使用扩展的类型 DataGridViewComboEditBoxColumn 。
这样Combox列就可以编辑了。
public class DataGridViewComboEditBoxCell : DataGridViewComboBoxCell
{
public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
ComboBox comboBox = base.DataGridView.EditingControl as ComboBox;
if (comboBox != null)
{
comboBox.DropDownStyle = ComboBoxStyle.DropDown;
comboBox.Validating += new CancelEventHandler(comboBox_Validating);
}
}
protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
{
if (value != null)
{
if (value.ToString().Trim() != string.Empty)
{
if (Items.IndexOf(value) == -1)
{
Items.Add(value);
DataGridViewComboBoxColumn col = OwningColumn as DataGridViewComboBoxColumn;
col.Items.Add(value);
}
}
}
return base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context);
}
void comboBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
DataGridViewComboBoxEditingControl cbo = sender as DataGridViewComboBoxEditingControl;
if (cbo.Text.Trim() == string.Empty) return;
DataGridView grid = cbo.EditingControlDataGridView;
object value = cbo.Text;
// Add value to list if not there
if (cbo.Items.IndexOf(value) == -1)
{
DataGridViewComboBoxColumn cboCol = grid.Columns[grid.CurrentCell.ColumnIndex] as DataGridViewComboBoxColumn;
// Must add to both the current combobox as well as the template, to avoid duplicate entries
cbo.Items.Add(value);
cboCol.Items.Add(value);
grid.CurrentCell.Value = value;
}
}
}
public class DataGridViewComboEditBoxColumn : DataGridViewComboBoxColumn
{
public DataGridViewComboEditBoxColumn()
{
DataGridViewComboEditBoxCell obj = new DataGridViewComboEditBoxCell();
this.CellTemplate = obj;
}
}
C#取计算机硬件信息 | C#静态构造函数及静态变量学习 |
DataGridViewComboEditBoxColumn类,可编辑的ComboBox列[收集] | |
[ 发布日期:19年前 (2006-07-15) ] [ 来自:rick@博客园 ] | [分类:C# .Net编程] |
[ 分类:C# .Net编程
| 查看:7598 ]
上一篇: C#取计算机硬件信息
下一篇: C#静态构造函数及静态变量学习
暂时没有评论,快来发表一个评论吧。
发表评论 |