简体   繁体   中英

Programmatically add a row to datagridview

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM