简体   繁体   中英

How can I add a text box dynamically under an other by pressing a button in c#? (winforms)

在此处输入图片说明 ^^^Fixed Layout ^^^

在此处输入图片说明 The image is a reconstruction in Excel (I don't have the code at hand right now)

Question 1: How can I add a text box under an other dynamically (the yellow text boxes for reference) by pressing the 'Add Ingredient' button?

Question 2: Can I use a simpler method instead of adding text boxes? (a type of cell/row code)

Why don´t you use a table or a listview to display the ingredients? Its more flexible to display...

For example:

  1. Add "ListView"-Control to your form
  2. Change the view of your listview to "Details" to display the list as a table
  3. Add 4 Columns to your ListView (id, name, quantity, price)
  4. Create a struct to hold your data (id, name, ...)
  5. Add a generic List of your struct (like "List list = new List()") (class instance variable)
  6. Add Items to the List ("list.AddItem([...])")
  7. Bind the List as datasource.

在此处输入图片说明

So I managed to get it done using the dataGridView.

   public void AddItemToTable()
    {
        int idOfItem;
        string[] details = ItemCombo.Text.Split(','); //ItemCombo = combo box
        idOfItem = int.Parse(details[0]);

        int n = dataGrid.Rows.Add();
        dataGrid.Rows[n].Cells[0].Value = Vars.itemName[idOfItem];
        dataGrid.Rows[n].Cells[1].Value = InputValueBox.Text + " " + Vars.itemScale[idOfItem];
        dataGrid.Rows[n].Cells[2].Value = "€" + ((Vars.itemPrice[idOfItem] / Vars.itemBundle[idOfItem]) * double.Parse(InputValueBox.Text)).ToString("F4");
    }

You can use ListView and then do an Insert or Add. How to get columns? Add a listView, then when in "Main_Load", add the following code:

void Main_Load(object sender, EventArgs e)
{
     listView.View = View.Details;
     listView.Columns.Add("Ingredients", 100, HorizontalAlignment.Center);
     listView.Columns.Add("Amount", 100, HorizontalAlignment.Center);
     listView.Columns.Add("Cost", 100, HorizontalAlignment.Center);
}

void _btnAddIngredients(object sender, MouseEventArgs e)
{
     listView.Items.Add("Add Text Here");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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