-2

I have a custom DGV (dgvPaths) with 2 buttons as first 2 columns:

        DataGridViewButtonColumn btnColRemove = new DataGridViewButtonColumn();
        btnColRemove.Name = "Remove";
        btnColRemove.HeaderText = "Remove";
        dgvPaths.Columns.Add(btnColRemove);
        dgvPaths.Columns["Remove"].DisplayIndex = 0;

        DataGridViewButtonColumn btnColBrowse = new DataGridViewButtonColumn();
        btnColBrowse.Name = "Browse";
        btnColBrowse.HeaderText = "Browse";
        dgvPaths.Columns.Add(btnColBrowse);
        dgvPaths.Columns["Browse"].DisplayIndex = 1;

        DataGridViewTextBoxColumn txtColPath = new DataGridViewTextBoxColumn();
        txtColPath.Name = "Path";
        txtColPath.HeaderText = "Path";
        dgvPaths.Columns.Add(txtColPath);
        dgvPaths.Columns["Path"].DisplayIndex = 2;

Now I want to add a new row by using the columnNames and tried this:

        DataGridViewRow row = (DataGridViewRow)dgvPaths.Rows[0].Clone();
        row.Cells["Path"].Value = "Path xy";
        dgvPaths.Rows.Add(row);

This leads to the error "Column Path not found".

How can I accomplish this?

tar
  • 156
  • 2
  • 13
  • Use the debugger to check the column names that are actually there! – TaW Jun 29 '21 at 15:08
  • what's purpose of `row.Cells["Path"].Value = "Path xy";`? – Lei Yang Jun 29 '21 at 15:10
  • Columns have names because only one column will have that name. Cells are not columns. There will be many cells in the `Path` column, so `row.Cells["Path"]` is ambiguous – Ňɏssa Pøngjǣrdenlarp Jun 29 '21 at 15:23
  • [This question](https://stackoverflow.com/questions/9094124/how-to-add-a-row-to-a-unbound-datagridview) is not an exact duplicate of yours, but it shows a different way to achieve the creation of unbound rows – Steve Jun 29 '21 at 15:27
  • 1
    I cannot see any column names in the debugger. The pupose of the values is to use them later, ofc and ofc, column should have names and row.Cells["Path"] should get the column Path of that exactly row. The linked question does not help me, at all. – tar Jun 29 '21 at 15:30
  • 1
    Or get the index of the column from the Columns property and use it to index the cells array – Steve Jun 29 '21 at 15:36
  • Probably is a limitation of the Clone method or the whole DataGridView control. I use a different control from another vendor and this problem doesn't exist. – Steve Jun 29 '21 at 15:37

1 Answers1

0

Got it solved using:

row.Cells[dgvPaths.Columns["Path"].Index].Value = "Path xy";
tar
  • 156
  • 2
  • 13