DataGridView Winform 自动插入序数列(技巧)

发布于 2024-08-26 05:29:21 字数 372 浏览 6 评论 0原文

我想找到一些解决这个问题的技巧。

我有像这样的产品表

(uuid,名称)

和一个 datagridview 来显示此信息( dataGridView.DataSouce = 在运行时分配的产品)

  • 我的问题是我想在 dataGridView 上有“否”列,它将如下所示

    没有|名称

    1 |产品A

    2 |产品B

    3 | ProductC

我现在所做的是在我的产品模型上创建一个“否”字段,然后循环遍历所有行并为其赋值。

我认为这不是一个好的解决方案。

希望任何人都可以提出更好的解决方案。

谢谢,

I want to get some trick for this problem.

I have my table like this

Product (uuid, Name)

and one datagridview to display this information ( dataGridView.DataSouce = Products which is assign on runtime)

  • My problem is that I want to have "No" column on dataGridView which will show like below

    No | Name

    1 | ProdctA

    2 | ProductB

    3 | ProductC

What I do right now is create a "No" field on my product Model, and loop through all the row and assign value to it.

I think this is not a good solution.

Hope anyone can suggest better solution.

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荭秂 2024-09-02 05:29:21

我一直没找到窍门,但我研究过好几次了。以下是有关此问题的一些评论。

  1. 由于您要添加列,因此基本上是在添加数据。因此,您必须指定该列的行数据。
  2. 更新特定列相对较快。与使用表达式添加数据列的性能大致相同。我已经完成了性能测试,并且在使用列的索引时更新整数值的速度大约与您执行此更新的速度一样快。

    Dim oData As DataTable = GatherDataTable()

    Dim oAutoIdColumn As New DataColumn("uuid", GetType(Integer))
    oData.Columns.Add(oAutoIdColumn)

    Dim iColumnIndex As Integer = oAutoIdColumn.Ordinal
    Dim oRows As DataRowCollection = oData.Rows
    Dim iRowCount As Integer = oRows.Count

    For i As Integer = 1 To iRowCount
        oRows.Item(i - 1).Item(iColumnIndex) = i
        '-or-
        oRows(i - 1)(iColumnIndex) = i
    Next

    Me.DataGridView1.DataSource = oData

I have never found a trick, but I have researched several times. Following are some comments regarding this issue.

  1. Since you are adding a column, you are basically adding data. Therefore, you must specify what the row's data will be for that column.
  2. Updating a specific column is relatively fast. Approximately the same performance as adding a data column with an expression. I have done performance testing and updating an integer value while using the column's index is about as fast as you can do this update.

    Dim oData As DataTable = GatherDataTable()

    Dim oAutoIdColumn As New DataColumn("uuid", GetType(Integer))
    oData.Columns.Add(oAutoIdColumn)

    Dim iColumnIndex As Integer = oAutoIdColumn.Ordinal
    Dim oRows As DataRowCollection = oData.Rows
    Dim iRowCount As Integer = oRows.Count

    For i As Integer = 1 To iRowCount
        oRows.Item(i - 1).Item(iColumnIndex) = i
        '-or-
        oRows(i - 1)(iColumnIndex) = i
    Next

    Me.DataGridView1.DataSource = oData
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文