Jevon Jevon - 1 month ago 5
C# Question

increment excel cells according to data being written each time

Currently I have to specify the cells the values have to be added to. How do I like increment in some fashion as to say no matter how many times the user hits the add to file button it should just increment the previous pattern.
eg. I have :

xlWorkSheet.Cells[1, 1] = comboBox2.Text;
xlWorkSheet.Cells[1, 2] = textBox5.Text;
xlWorkSheet.Cells[1, 3] = textBox2.Text;
xlWorkSheet.Cells[1, 4] = comboBox3.Text;
xlWorkSheet.Cells[1, 5] = textBox3.Text;
xlWorkSheet.Cells[1, 6] = comboBox1.Text;


Upon clicking the "add to xls file" button, how would I make it now follow this pattern and save to file without having to write this into the code:

xlWorkSheet.Cells[2, 1] = comboBox2.Text;
xlWorkSheet.Cells[2, 2] = textBox5.Text;
xlWorkSheet.Cells[2, 3] = textBox2.Text;
xlWorkSheet.Cells[2, 4] = comboBox3.Text;
xlWorkSheet.Cells[2, 5] = textBox3.Text;
xlWorkSheet.Cells[2, 6] = comboBox1.Text;


It's not like I can copy and paste every single time, that would be way too tedious. All answers and comments are welcome. Thanks in advance

Answer

You can use property.

public int IndexProp {get; set;}

public void AddToExcelBtn_Click(object sender, EventArgs e) 
{
    //... some other code

    Index +=1;
    xlWorkSheet.Cells[IndexProp , 1] = comboBox2.Text;
    xlWorkSheet.Cells[IndexProp , 2] = textBox5.Text;
    xlWorkSheet.Cells[IndexProp , 3] = textBox2.Text;
    xlWorkSheet.Cells[IndexProp , 4] = comboBox3.Text;
    xlWorkSheet.Cells[IndexProp , 5] = textBox3.Text;
    xlWorkSheet.Cells[IndexProp , 6] = comboBox1.Text;
}