简体   繁体   English

如何增加自动生成的 ID

[英]How to increment the Auto Generated Id

I'm pretty new to C#.我对 C# 很陌生。 I want to increment an int variable id by 1 and insert it into a datagridview.我想将int变量id增加 1 并将其插入到 datagridview 中。 The problem is, it doesn't increment, it stays at 1.问题是,它不会增加,而是保持在 1。

Here's my code for adding the data to datagridview这是我将数据添加到 datagridview 的代码

class QuantityCtrl : Quantity
{
   private ManageSale _manageSale;

   public QuantityCtrl(ManageSale manageSale)
   {
        _manageSale = manageSale;
   }

   private void BtnOk_Click(object sender, EventArgs e)
   {
        _manageSale.dgvItemList.Rows.Add
        (
            GenerateId(),
            _manageSale.lblName.Text,
            _manageSale.lblPrice.Text,
            _manageQuantity.txtDiscount.Text,
            _manageQuantity.txtQuantity.Text,
            Total
        );
   }
}

Here's my code for incrementing这是我的递增代码

class Quantity
{
    public int OrderId = 1;

    public int GenerateId()
    {
        return OrderId++;
    }
}

I solved it thanks to Brendan.感谢 Brendan,我解决了这个问题。 I hope it could be a referrence for some developers :) and If someone has a better way of incrementing you can answer it Thank you.我希望它可以成为一些开发人员的参考:) 如果有人有更好的递增方式,您可以回答它,谢谢。

public static int OrderId = 1;

Another way of doing it would be creating a new class in a folder inside your solution which contains the list and the proprieties :另一种方法是在解决方案内的文件夹中创建一个新类,其中包含列表和属性:

class IDS
{

    #region Proprieties
    public int Id { get; set; }
    #endregion

    #region Lists
    public List<IDS> _ids = new List<IDS>();
    #endregion
}

Now, you'll need to link the class to the main, for that, go in your main code and put at the top :现在,您需要将类链接到主类,为此,进入您的主代码并放在顶部:

using SolutionName.Folder;

Next go to your button event and simply put this:接下来转到您的按钮事件并简单地输入:

private void btnAutoGen_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
   int iId = 0;

   try
   {
       var req = (from value in _id
                  select value.Id).Max() + 1;
       iId = req;
   }
   catch (InvalidOperationException)
   {
       iId = 1;
   }

You now have a button that auto increment.您现在有一个自动递增的按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM