Ok, so I am loading data from an XML file into a dataGridView. I have several entries in the XML file and would like each one to create a button next to it.

After some searches it looks like I either have to put it in a <code> or <c> tag, but I have no idea what I would put in there in to create a button in its row in the dataGridView.

Any ideas on how to do this?

Dani AI

Generated

Useful, compact pattern to get one button per XML row in a WinForms DataGridView (builds on ’s suggestion and the XML-to-grid scenario described by ).

Load the XML into a DataTable and bind:

var ds = new DataSet();
ds.ReadXml("data.xml");      // or use a stream
dataGridView.DataSource = ds.Tables[0];

Add a button column (same text for every row) or set per-row text afterwards:

var btn = new DataGridViewButtonColumn();
btn.Name = "Action";
btn.HeaderText = "Action";
btn.Text = "Open";
btn.UseColumnTextForButtonValue = true; // common label for all buttons
dataGridView.Columns.Add(btn);

If each button needs custom text, set UseColumnTextForButtonValue = false and populate the cell values after binding:

dataGridView.Rows[i].Cells["Action"].Value = "Edit";

Handle clicks and retrieve the underlying data row reliably (works with a bound DataTable):

private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0) return;
    if (dataGridView.Columns[e.ColumnIndex].Name != "Action") return;

    var drv = (DataRowView)dataGridView.Rows[e.RowIndex].DataBoundItem;
    var id = drv["Id"]?.ToString();   // use your key/column name
    // perform action using id or drv.Row
}

Quick troubleshooting/cautions:

  • Check e.RowIndex and column Name in the click handler to avoid header/new-row clicks.
  • For bound grids, prefer reading values from DataBoundItem (DataRowView) rather than cell text.
  • If you want the button column in a specific place, set DisplayIndex or Columns.Insert(...).
  • For large XML files, read into a DataTable/DataSet with schema or stream-read to avoid UI freezes.
  • Don’t try to place individual WinForms Button controls into every row — use the button column for performance and correct integration with data binding.

Recommended Answers

All 2 Replies

Thank you so much for your help.

Can't believe it was as simple as adding a row full of buttons.

Every time I use C# I am more impressed with it.

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.