Search code examples
c#c#-4.0datagridviewc#-2.0c#-datatable

c#- Every time a buttton is clicked related item (Button name as Bread) count should be incremented in Data Table row of data grid view


int bread = 0;
     DataTable dt = new DataTable();
     DataRow dr ;`
    
    private void Form1_Load(object sender, EventArgs e)
    {
    dt.Columns.Add("Food");
    dt.Columns.Add("Amount");
    dt.Columns.Add("Table");
    }
    
   private void btnBread_Click(object sender, EventArgs e)
   {
    dr = dt.NewRow();
    bread ++;
            dr["Food"] = btnBread.Text;
            dr["Amount"] = bread;
            dr["Table"] = 1;
            dt.Rows.Add(dr);`
    
    }
    

I tried incrementing var(bread) but every time it is creating new row when i click a buttton(bread), incremented counter is added on next line. how to increment only counter and other data should be same.


Solution

  • The code does exactly what you ask it to do. Each time the button is clicked you create a new row with the name dr, then increment the variable named bread and after that you configure the new row and add it to the table.

    I think you should rethink your approach to the problem at hand.

    EDIT:

    I think the following code will do the trick, just assembled something on my break from work so test it to make sure

    private void Form1_Load(object sender, EventArgs e)
    {
        data_table.Columns.Add("Food");
        data_table.Columns.Add("Amount");
        data_table.Columns.Add("Table");
    
        data_table.Rows.Add(data_table.NewRow());
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        this.amount++;
    
        this.data_table.Rows[0][1] = amount;
    }
    
    private DataTable data_table = new();
    private int amount = 0;