我正在修改.NET 3.5中的Winforms应用程序。
我有一个DataGridViewComboBoxColumn,其中填充了一些硬编码选项,如下所示。
//
// dgvCol_PropName
//
this.dgvCol_PropName.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.ComboBox;
this.dgvCol_PropName.HeaderText = "Property Name";
this.dgvCol_PropName.Items.AddRange(new object[] {
"Option1",
"Option2",
"Option3"});
this.dgvCol_PropName.Name = "dgvCol_PropName";
this.dgvCol_PropName.Width = 150;
我想选择这些选项是不同的,这样一旦网格中存在一个选项,就不能再次选择它(用户应编辑当前行或删除并重新输入)。
有快速的方法吗?
我想我会分享我的最终解决方案,以防它帮助其他人。我的CellValidating事件处理程序如下:
/// <summary>
/// Handle the validation event on the cell so that only properties that have not already been specified can be selected
/// </summary>
private void dg_FTPS_ExProps_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
var dataGrid = sender as DataGridView;
if (dataGrid != null)
{
// Only validate if that event is generated for the Property Name column
string headerText = dataGrid.Columns[e.ColumnIndex].HeaderText;
// Abort validation if cell is not in the PropertyName column.
// Rejected using the column index in case the column order changes but
// equally, there will be problems if the column header changes. (Pay your money and take a chance)
if (headerText.Equals("Property Name"))
// if (e.ColumnIndex == 0)
{
// Count the number of times the property exists in the table
int propertyCount = 0;
foreach (DataGridViewRow row in dg_FTPS_ExProps.Rows)
{
if( row.Cells[ e.ColumnIndex ].EditedFormattedValue.ToString().Equals( e.FormattedValue) == true )
{
propertyCount++;
}
}
// Check if multiple entreies have tried to be applied
if (propertyCount > 1)
{
e.Cancel = true;
}
}
}
}
我喜欢使用LINQ来计算实例的数量,但我仍然在学习,所以我坚持我所知道的。
答案 0 :(得分:0)
尝试在事件正文中使用此事件DataGridView.CellValidating,只需检查是否有另一行具有相同的值,并且是否只有e.Cancel
设置为true
。