Reputation: 840
There are answers all over the internet, but its not working and I'm wondering what I'm doing wrong.
I have a DataGridView
with 1 column, Column1
. That is the name of the column, not the text, or anything else.
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1});
this.dataGridView1.Name = "dataGridView1";
//
// Column1
//
this.Column1.HeaderText = "Column1";
this.Column1.Name = "Column1";
.....
}
public Form1()
{
InitializeComponent();
// Works
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = "AAAAA";
dataGridView1.Rows.Add(row);
// Fails
row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells["Column1"].Value = "AAAAA"; // Argument Exception: "Column named Column1 cannot be found"
dataGridView1.Rows.Add(row);
}
Please explain? Thank you so much!
Upvotes: 1
Views: 6219
Reputation: 12739
The row is not part of a Datagridview so it cannot find the column. Either add it back to the datagridview FIRST and then assign the value to it using the column name OR address the cells by the index of the column:
row.Cells[dataGridView1.Columns["Column1"].Index].Value = "AAAAA";
Upvotes: 2