1

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!

1 Answer 1

2

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";
1
  • Thank you! Everywhere else I looked referred to the code I had. Didnt realize the row wasnt a part of the table, or that it didnt have a refernce to the columns, since it was a clone of a row. Either way, this is what I was looking for so THANK YOU!
    – Tizz
    Commented Dec 3, 2012 at 20:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.