且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在DataGridView中创建Lookup字段?

更新时间:2023-02-18 17:25:39

我不知道您是否可以完全按照自己的意愿去做,哪个似乎是同时将DataGridView绑定到两个不同的 DataTable 实例。我不认为 DataGridView 类支持该功能-否则是否是我从未见过的忍者式动作。

I don't know if you can do exactly what you want, which seems to be binding the DataGridView to two different DataTable instances simulataneously. I don't think the DataGridView class supports that -- or if it does it's a ninja-style move I haven't seen.

根据MSDN ,您***的选择可能是使用DataGridView上的 CellFormatting 事件,并检查正在格式化的单元格何时在查找列中,然后可以用其他表中的值代替。使用一个未绑定的列作为WorkplaceName列,隐藏UserWorkplaceID列,然后实现CellFormatting事件句柄以在行中查找值,例如:

Per MSDN, your best bet is probably using the CellFormatting event on the DataGridView and check for when the cell being formatted is in the lookup column, then you could substitute your value from the other table. Use an unbound column for the WorkplaceName column, hide the UserWorkplaceID column and then implement the CellFormatting event handle to look up the value in the row, e.g.:

private void dgv_CellFormatting(object sender, 
    DataGridViewCellFormattingEventArgs e)
{
    if (dgv.Columns[e.ColumnIndex].Name.Equals("WorkplaceName")
    {
        // Use helper method to get the string from lookup table
        e.Value = GetWorkplaceNameLookupValue(
            dataGridViewScanDetails.Rows[e.RowIndex].Cells["UserWorkplaceID"].Value);
    }
}

如果有很多行可见,这可能会影响性能,但可能是使其正常工作的一种不错的方法。

If you've got a lot of rows visible, this might impact performance but is probably a decent way to get it working.

如果这对您没有吸引力,则可以使用 DataTable.Merge() 合并查询的方法能够进入您的主表。快速浏览一下我的一本ADO.NET书籍,尽管我没有尝试过,但它应该可以工作。但是我不确定这是否与您先前击落的建议过于接近。

If this doesn't appeal to you, maybe use the DataTable.Merge() method to merge your lookup table into your main table. A quick glance at one of my ADO.NET books suggests this should work, although I have not tried it. But I'm not sure if this is too close to the idea suggested previously which you shot down.

关于查找组合框的第二个问题,您应该将其真正发布在一个单独的问题中,以便引起适当的注意。