【问题标题】:Best way to auto-increment ID column in a DataGridView?在 DataGridView 中自动增加 ID 列的最佳方法?
【发布时间】:2018-02-20 10:41:05
【问题描述】:

我有一个 dataGridView,我可以在其中插入、删除和更新值,但有些事情困扰着我。 用户只能修改显示的 2 列(大小和数量),隐藏其他 2 列(ID 和 selectedComponent)。 ID是我表中的PK。

这是我为新行设置 ID 和 selectedComponent 所做的:

private void dataGridViewStock_DefaultValueNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e) 
    {
        e.Row.Cells["id"].Value = "1";
        e.Row.Cells["codeArticleComponent"].Value = labelComponentChosen.Text;
    }

无论我为 ID 设置什么值,第一个可用的数字都会被插入到数据库中。它可以工作,但我担心它以后可能会导致错误。

有没有更好的方法来实现这一点?或者我可以保持原样吗?

【问题讨论】:

  • 使用Identity 列。
  • @RezaAghaei 我已经将 ID 列声明为 Identity 并自动递增 1。
  • 制作代理客户端ID。保存到数据库后用实际 id 替换它们。

标签: c# sql-server winforms


【解决方案1】:

您可能需要一个单独的列(仅在 GirdView 中)来识别当前行是新添加的还是现有的。并根据新列用负值增加 id 列。

在保存数据的同时可以识别新创建的行,在此基础上可以通过插入不带id的列或者更新已有数据来保存数据。

希望这可以澄清你。

【讨论】:

    【解决方案2】:

    这是我的数据网格视图中自动递增主键的代码

    private void Row_Added(object sender, 
    DataGridViewRowsAddedEventArgs e){
      foreach(DataGridViewRow dtr in dataGridView1.Row){
      dataGridView1.Rows[e.RowIndex-1].Cells[0].Value = 
    e.RowIndex;
    }
    }
    

    我用过这个...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 2013-07-22
      • 2012-04-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多