简体   繁体   English

每次触发事件时,在DataGridView中添加具有递增值的新行

[英]Add a new Row in DataGridView with incremented value every time the event is fired

I have a table which has an ID, Name, and ActiveStatus which are set to default on a button click event. 我有一个表,该表的ID,名称和ActiveStatus在按钮单击事件中设置为默认值。 Whenever I click, it adds a new row to the datagridview but does nothing if i want to add a new row under it WITH AN INCREMENT VALUE OF PREVIOUS VALUE. 每当我单击时,它都会向datagridview添加一个新行,但是如果我想在其下添加一个具有以前值的增值的新行,则不会执行任何操作。 Like if there is already an id with number 1 is present, it should add a new row with id = 2. or if it is empty, it should add id = 1. 就像已经存在编号为1的id一样,它应该添加id = 2的新行;或者如果它为空,则应该添加id = 1。

   MyDatabase mydata = new MyDatabase();
   List<MyDatabase> listmydata = new List<MyDatabase>();

        mydata.id = "1";
        mydata.Name = "YO";
        mydata.ActiveStatus= true;
        listmydata.Add(mydata);
        dataGridView1.DataSource = listmydata.ToList<MyDatabase>();

//This adds only 1 new row, does nothing if we click the button again //这只会添加1个新行,如果再次单击该按钮则不执行任何操作

Try to announce a global class variable, wich will count your new elements, wich you can use as id field in MyDatabase list. 尝试声明一个全局类变量,该变量将计算您的新元素,您可以在MyDatabase列表中将其用作id字段。

public class Form...
{
   private int elemsCount = 0;
   public event(...)
   {
      MyDatabase mydata = new MyDatabase();
      List<MyDatabase> listmydata = new List<MyDatabase>();

      mydata.id = elemsCount.ToString();
      mydata.Name = "YO";
      mydata.ActiveStatus= true;
      listmydata.Add(mydata);
      dataGridView1.DataSource = listmydata.ToList<MyDatabase>();
      elemsCount++;
   }
}

Similar to Vladimir's answer, I would suggest you need a global variable to keep count of how many times this method has been executed. 与弗拉基米尔的答案类似,我建议您需要一个全局变量来计算此方法已执行了多少次。 However, you're probably going to want to make your List variable global as well. 但是,您可能还希望将List变量也设置为全局变量。

public class YourClass
{
   private int numExecutions = 0;
   private List<MyDatabase> listmydata = new List<MyDatabase>();
   public YourEvent(EventArgs e)
   {  
      MyDatabase mydata = new MyDatabase();
      mydata.id = numExecutions.toString();
      mydata.Name = "YO";
      mydata.ActiveStatus= true;
      listmydata.Add(mydata);
      dataGridView1.DataSource = listmydata.ToList<MyDatabase>();
      numExecutions++;
   }
}

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

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