Question

I'm modifying a Winforms application in .NET 3.5.

I have a DataGridViewComboBoxColumn populated with some hard coded options as shown below.

// 
// 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;

I would like to make the selection of these options distinct so that once an option exists in the grid then it can't be selected again (The user should edit the current row or delete and re-enter it).

Is there a quick way to do this?

I thought I'd share my final solution in case it helps anyone else. My CellValidating event handler is below:

/// <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;
            }
        }
    }
}

I'd have liked to use LINQ to count the number of instances but I'm still learning that so I stuck to what I know.

Was it helpful?

Solution

Try using this event DataGridView.CellValidating in the body of the event just check if there is another row with same value and if there is just set e.Cancel to true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top