DataGridView throwing “InvalidOperationException: Operation is not valid…” when adding a row

前端 未结 5 1617
失恋的感觉
失恋的感觉 2021-02-07 05:00

I want an OpenFileDialog to come up when a user clicks on a cell, then display the result in the cell.

It all works, except that the DataGridView displays an extra row,

5条回答
  •  我在风中等你
    2021-02-07 06:04

    Try this:

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                int row = e.RowIndex;
                int clmn = e.ColumnIndex;
                if(e.RowIndex == dataGridView1.Rows.Count- 1)
                    dataGridView1.Rows.Add();
                dataGridView1.Rows[row].Cells[clmn].Value = openFileDialog1.FileName;
            }
    

    EDIT I didn't notice that you are binding your datagridview :( Ok, to solve it: use binding source, set its DataSource property to your list, then set the data source of the data grid view to this binding source. Now, the code should look like so:

    public partial class frmTestDataGridView : Form
        {
            BindingSource bindingSource1 = new BindingSource();
            List datasource = new List();
            public frmTestDataGridView()
            {
                InitializeComponent();
                datasource.Add("item1");
                datasource.Add("item2");
                datasource.Add("item3");
    
                bindingSource1.DataSource = datasource;
                dataGridView1.DataSource = bindingSource1;
            }
    
            private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    int row = e.RowIndex;
                    int clmn = e.ColumnIndex;
    
                    if (e.RowIndex == dataGridView1.Rows.Count - 1)
                    {
                        bindingSource1.Add("");
                    }
                    dataGridView1.Rows[row].Cells[clmn].Value = openFileDialog1.FileName;
                }
            }
    
        }
    

提交回复
热议问题