0

On select TreeView Node event, a new row in the DataGridView should be added containing some information from the node. But I cannot add a new row to the DataGridView without it replacing the already existing DataGridView row.

The DatagridView columns are named after custom node properties and all row cells must be placed in a column based on the name of the node object property.

This is what I've done so far

public static void AddToGrid(TreeNode node, DataGridView gridview)
{
    int rowIndex;
    if (gridview.RowCount > 0)
        rowIndex = gridview.RowCount +1;
    else rowIndex = gridview.Rows.Add();

    var row = gridview.Rows[rowIndex];
    row.Cells["property name"].Value = node.Text;
}

When I use this function a new Row is created in the DataGridView. Is there already a row in the DataGridView the existing row get replaced. I want it to add a new Row and also keep existing ones.

UPDATE

After hours of search I changed the code trying to figure this out but still same result. The new row replaces the old. The new attempt:

public static void AddToGrid(TreeNode node, DataGridView gridview)
{
    DataGridViewRow row = new DataGridViewRow();
    row.CreateCells(gridview);
    //row.Cells["property name"].Value = node.Text <- stopped working. Error: Cannot find column named "property name". (the column name do exist)
    row.Cells[0].Value = node.Text; // <- Instead I'm using this as for now
    gridview.Rows.Add(row);
}
4
  • if (gridview.RowCount > 0) rowIndex = gridview.RowCount +1;... Why that check? You only create one row. If you always want a new one always add one!
    – TaW
    Jun 8, 2016 at 13:24
  • @TaW This function is run every time I select a TreeNode, and it is supposed to add the selected node.Text as a new row in the DataGridView without removing the existing ones. But it replaces existing rows when adding. I figured it could be because the old and new row had the same index. Jun 8, 2016 at 13:55
  • The code in the update does not replace anything. It just adds a new row. It you see something else the reason is in some other part of your code..
    – TaW
    Jun 8, 2016 at 13:57
  • @TaW I found the solution to be elsewhere just as you suggested! Big thanks! Post as answer and I will mark it as solution. Jun 8, 2016 at 14:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.