C#C
C#14mo ago
Alec

[solved]

Now, when I'm loading new data into my datagridview, some of which may not exist, I wanted to check if it does exist first, if it doesn't I add it to the datasource of the combobox, if it does... I want to select it. I'm having trouble searching through the datasource and comparing objects then setting the comboboxcell value when I find a match:

my current code looks something like:

SetComboBoxCellValue(row, "ColumnName", MyClass.myclassobjectvariable, (dataGridView_product.Columns["ColumnName"] as DataGridViewComboBoxColumn)?.DataSource);


        private void SetComboBoxCellValue(DataGridViewRow row, string columnName, object value, object dataSource)
        {
            
            if (row.Cells[columnName] is DataGridViewComboBoxCell comboBoxCell && dataSource is IEnumerable<object> dataList)
            {
                // Check if the exact object exists in the DataSource
                var matchingItem = dataList.Cast<object>().FirstOrDefault(item => item.Equals(value));

                // Set the ComboBoxCell's value to the matching object if found; otherwise, use the first item as fallback
                comboBoxCell.Value = matchingItem ?? dataList.Cast<object>().First();
            }
        }


this doesnt work at all lol, I get no errors but also the dgvcomboboxcell is just empty, none of it's items selected. Is there a way to do this easier? am I dumb?
Was this page helpful?