【问题标题】:Using DataGridViewComboBoxColumn for distinct options将 DataGridViewComboBoxColumn 用于不同的选项
【发布时间】:2011-09-02 13:24:11
【问题描述】:

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

【问题讨论】:

    标签: c# winforms datagridviewcombobox


    【解决方案1】:

    尝试在事件主体中使用此事件DataGridView.CellValidating,只需检查是否存在具有相同值的另一行以及是否将e.Cancel 设置为true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      相关资源
      最近更新 更多