简体   繁体   中英

Change Value of a Dynamically Created Text Box when button is clicked C#

I have dynamically created a button using a function I made which is meant to increase the value of another button created using a similar function. I'm able to retrieve the name of the dynamically created textbox, but since it is dynamically created, I can't reference it.

I've tried to pass the textbox through as a parameter, but it doesn't appear that I'm able to pass extra parameters:

Button ButtonDecreaseValue= addButton(ItemName, "-"); 

TextBox TextBoxItemAmount = addTextBox(ItemName, "0");

So, how would I change the value of textbox one when ButtonRemoveItem is clicked?

I've created an event handler for the button, like so:

ButtonIncreaseValue.Click += new EventHandler(ItemDecreased);

But, inside the event handler, I'm unsure how I would change the textbox name.

private void ItemDecreased(object sender, EventArgs e)
{
    Button currentItem = (Button)sender;
    int ItemNo = Convert.ToInt32(currentItem.Tag);
    DataRow ItemInfo = getItemDetails(ItemNo);

    ItemInfo[0].ToString();
}

When clicking the button, the corresponding textbox should decrease in value.

Assuming this is Windows Forms

You said you have the name of the TextBox ? You should be able to find it with that.

private void ItemDecreased(object sender, EventArgs e)
{
   string textBoxName = HoweverYouGetTheDynamicTextBoxName();

   // Assumptions:
   //   1. ItemDecreased is a method on a Form or a UserControl.
   //   2. There is only one TextBox with the given name in the Form or UserControl.
   //   3. The TextBox is added to the Form or UserControl's Controls property.
   TextBox tb = Controls.Find(textBoxName, true).OfType<TextBox>().SingleOrDefault();
   if (tb is null)
   {
       // Couldn't find the text box for some reason.
   }
   // tb references the dynamically created text box.
}

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