Ok, basically, I have a datagrid with a button column, and the goal is, to be able to load specific things into a second datagrid depending on which rows button was clicked. But I seem to be completely unable to figure out how to get the row index.

The program is loading all of its data from an XML file, so I am going to have it compare the row index to a row index value in the xml file to know what to display in the second datagridview.

Thanks in advance for any help.

Dani AI

Generated

Good catch by — detecting the clicked cell is the right approach. For a button column it’s usually cleaner to handle the grid’s CellContentClick (or CellClick) so you get e.RowIndex/e.ColumnIndex directly and can ignore header clicks.

A minimal pattern to use (check RowIndex and the column first, then read an ID from the row rather than relying on the visual index):

private void grid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0) return;               // clicked header
    if (e.ColumnIndex != myButtonColIndex) return;

    var row = grid.Rows[e.RowIndex];
    string xmlId = row.Tag as string ?? row.Cells["XmlId"]?.Value?.ToString();
    // use xmlId to select the XML node and populate the second grid
}

Don’t map the UI row index straight to your XML. Sorting, filtering, or binding changes row ordering. Instead attach a stable key when you populate the grid (or bind to objects and use DataBoundItem). Example when filling rows:

var r = grid.Rows[i];
r.Cells["Title"].Value = element.Element("Title")?.Value;
r.Tag = element.Attribute("id")?.Value;   // keep a stable lookup key

If the grid is data-bound, read the key via row.DataBoundItem and cast to the underlying type (e.g., DataRowView), then use that ID to pull the correct XML node. If you prefer mouse handlers, use DataGridView.HitTest(x,y) to convert coordinates to a row/column. See the Microsoft docs for the CellContentClick event and DataGridViewRow.Tag/DataBoundItem for details: DataGridView.CellContentClick and .

Recommended Answers

All 2 Replies

Have you looked at:

DataGridView dgvMyName = new DataGridView();

You need to recognize a click or other event inside of the DGV such as when you release the mouse button:

dgvMyName_MouseUp (object sender, MouseEventArgs e)
{
     // get the current row
     int iSelectedRow;

     iSelectedRow = dgvMyName.CurrentRow.Index;

     // now do something with the selected row.
}

Thank you VERY much. That is exactly what I was stuck on, and now it seems so simple.

Thanks again.

-Adam

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.