MT.*_*MT. 8 c# datagridview winforms
是否可以在DataGridView中执行以下操作:
在同一列中,我想更改DataGridViewTextBoxColumn和DataGridViewComboBoxColumn之间每行的控件类型?
(这是因为有时我想显示一个下拉列表,有时我只想让用户输入一个写意值).
谢谢,
PS我正在使用C#
我最近有一个类似的用例,最后写了类似下面的代码:
编写一个自定义的Cell和Column类,并覆盖单元格上的EditType和InitializeEditingControl方法,以适当地返回不同的控件(这里我只是将数据绑定到一个自定义类的列表,其中.useCombo字段指示要使用的控件):
// Define a column that will create an appropriate type of edit control as needed.
public class OptionalDropdownColumn : DataGridViewColumn
{
public OptionalDropdownColumn()
: base(new PropertyCell())
{
}
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
// Ensure that the cell used for the template is a PropertyCell.
if (value != null &&
!value.GetType().IsAssignableFrom(typeof(PropertyCell)))
{
throw new InvalidCastException("Must be a PropertyCell");
}
base.CellTemplate = value;
}
}
}
// And the corresponding Cell type
public class OptionalDropdownCell : DataGridViewTextBoxCell
{
public OptionalDropdownCell()
: base()
{
}
public override void InitializeEditingControl(int rowIndex, object
initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
// Set the value of the editing control to the current cell value.
base.InitializeEditingControl(rowIndex, initialFormattedValue,
dataGridViewCellStyle);
DataItem dataItem = (DataItem) this.OwningRow.DataBoundItem;
if (dataItem.useCombo)
{
DataGridViewComboBoxEditingControl ctl = (DataGridViewComboBoxEditingControl)DataGridView.EditingControl;
ctl.DataSource = dataItem.allowedItems;
ctl.DropDownStyle = ComboBoxStyle.DropDownList;
}
else
{
DataGridViewTextBoxEditingControl ctl = (DataGridViewTextBoxEditingControl)DataGridView.EditingControl;
ctl.Text = this.Value.ToString();
}
}
public override Type EditType
{
get
{
DataItem dataItem = (DataItem)this.OwningRow.DataBoundItem;
if (dataItem.useCombo)
{
return typeof(DataGridViewComboBoxEditingControl);
}
else
{
return typeof(DataGridViewTextBoxEditingControl);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后只需向此类型的DataGridView添加一列,并应使用正确的编辑控件.
您可以创建自己的从 DataGridViewCell 继承的类,并覆盖足够的虚拟成员(InitializeEditingControls、EditType,也许还有其他一些)。然后,您可以使用此类的实例创建一个 DataGridViewColumn 作为单元格模板