【问题标题】:Pulling a Business Object off a DataGridView in C#在 C# 中从 DataGridView 中拉出业务对象
【发布时间】:2017-08-06 11:09:42
【问题描述】:

我有一个列表。我已将其转换为 BindingList 并放入 BindingSource 并绑定到 DataGridView,这样我就可以让用户选择他们想要打印的 JobItem。 DataGridView 有一个 ButtonColumn,用户选择 JobItem,点击 ButtonColumn JobItem 打印到热敏打印机。

我的问题是我无法正确使用语法将所选业务对象从 DataGridView 中拉出,因此我可以将其发送到打印函数。

这是我目前正在尝试的:

BusinessObjects.JobItem row = dgJobItems.SelectedRows[e.RowIndex].DataBoundItem;

这是我的其余代码:

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;  
        }


    }

工作项目:

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()
    {

    }
}

对不起...我收到以下我不明白的错误:

ArgumentOutOfRangeException 未处理 mscorlib.dll 中出现“System.ArgumentOutOfRangeException”类型的未处理异常

附加信息:索引超出范围。必须为非负数且小于集合的大小。

【问题讨论】:

  • 没有错误?看来您有选定的行...缺少什么?
  • 我已经为这个问题stackoverflow.com/questions/3577297/… 加注了星标,因为我很少做前端的事情并且一直忘记。这不是您问题的答案。但通常我的问题是绑定到错误的事件。在任何情况下,我要做的是从该按钮单击获取对象 ID 并发送相应的对象,而不是信任来自前端的数据进行打印。
  • @JohnG 抱歉...是的,我遇到了一个错误。我添加了它。名为 mscorlib 的 dll 中的 ArgumentOutOfRangeException。 dll。

标签: c# datagridview bindingsource


【解决方案1】:

我猜是SelectedRows 没有返回您所期望的。由于它是连续的一个按钮,请使用dgJobItems.Rowse.rowIndex,如下所示。看看这是否有帮助。

if (dgJobItems.Columns[e.ColumnIndex].Name == "bPrint") {
  JobItem jobItem = (JobItem)dgJobItems.Rows[e.RowIndex].DataBoundItem;
  MessageBox.Show("Job Item" + jobItem.ToString());
}

【讨论】:

  • 非常感谢!它现在正在运行。
【解决方案2】:

我有一个扩展方法用于获取当前选定行的相关业务对象。

public static T GetSelectedPOCO<T>(this DataGridView grid) where T : class
{
    return (grid.SelectedRows.Count == 1)
        ? grid.SelectedRows[0].DataBoundItem as T
        : null;
}

可以这样调用:

Customer selectedCustomer = dgvCustomers.GetSelectedPOCO<Customer>();

顺便说一句,这个扩展假定不能选择多行。如果您不是这种情况,可能需要更改它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2011-04-18
    • 2011-01-07
    • 2010-11-21
    相关资源
    最近更新 更多