I have an issue wherein I have a DataGridViewComboBoxColumn
in a DataGridView
and I want to add an item to the DataSource
.
I've initially set the DataSource property to a List<string>
which works fine. Later I'll add an item to this list, which works fine. But when I try to choose this item in a combobox, I get a data validation error,
System.ArgumentException: DataGridViewComboBoxCell value is not valid.
Further, I can't actually set the combobox to the newly added value.
Here is a fully working example.
public partial class Form1 : Form
{
List<string> Data { get; set; }
public Form1()
{
InitializeComponent();
// Populate our data source
this.Data = new List<string> { "Thing1", "Thing2" };
// Set up controls
var gvData = new System.Windows.Forms.DataGridView();
var col1 = new System.Windows.Forms.DataGridViewComboBoxColumn();
var button = new System.Windows.Forms.Button();
gvData.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { col1 });
// Set the column's DataSource
col1.DataSource = this.Data;
col1.HeaderText = "Test";
col1.Name = "col1";
// Set up a button which adds something to the source
button.Text = "Add";
button.Location = new System.Drawing.Point(0, 200);
button.Click += (e, s) => this.Data.Add("Thing3");
this.Controls.Add(gvData);
this.Controls.Add(button);
}
}
How can I add items to the DataSource
for my DataGridViewComboBoxColumn
?
Changing
button.Click += (e, s) => this.Data.Add("Thing3");
to
button.Click += (e, s) =>
{
col1.DataSource = null;
this.Data.Add("Thing3");
col1.DataSource = Data;
};
has worked for me.