我正在修改 .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 来计算实例的数量,但我仍在学习这一点,所以我坚持我所知道的。