I have a List . Which I've converted to a BindingList and put into a BindingSource and bound to a DataGridView so that I can have the user select which JobItem they want to print. The DataGridView has a ButtonColumn, the user picks the JobItem, clicks the ButtonColumn the JobItem prints to a thermal printer.
My problem is I can’t get the syntax right to pull the selected Business Object off the DataGridView so I can send it to print function.
This is what I’m currently trying:
BusinessObjects.JobItem row = dgJobItems.SelectedRows[e.RowIndex].DataBoundItem;
This is the rest of my code:
DataGridViewButtonColumn btnPrint = new DataGridViewButtonColumn();
btnPrint.Text = "Print";
btnPrint.Name = "bPrint";
btnPrint.UseColumnTextForButtonValue = true;
dgJobItems.Columns.Add(btnPrint);
private void dgJobItems_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dgJobItems.Columns[e.ColumnIndex].Name == "bPrint")
{
BusinessObjects.JobItem row = dgJobItems.SelectedRows[e.RowIndex].DataBoundItem;
}
}
JobItem:
public class JobItem
{
public int jobNumber { get; set; }
public string serialNumber { get; set; }
public string modelNumber { get; set; }
public int quantity { get; set; }
public string description { get; set; }
public JobItem()
{
}
}
Sorry... I get the following error which I don't understand:
ArgumentOutOfRangeException was unhandled An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
I am guessing it is the SelectedRows
that is not returning what you are expecting. Since it is a single button in a row, use dgJobItems.Rows
and the e.rowIndex
like below. See if this helps.
if (dgJobItems.Columns[e.ColumnIndex].Name == "bPrint") {
JobItem jobItem = (JobItem)dgJobItems.Rows[e.RowIndex].DataBoundItem;
MessageBox.Show("Job Item" + jobItem.ToString());
}