简体   繁体   中英

Get the Text of dynamically created button in C#?

I am dynamically creating buttons in C# with this logic

for (int i = 1; i <= vap; ++i)
{
    newButtons[i] = new Button();
    newButtons[i].BackColor = Color.Gray;
    newButtons[i].Name = "Button4" + i.ToString();
    newButtons[i].Click += new EventHandler(NewButtons_Click);

    newButtons[i].Location = new System.Drawing.Point(width,height);
    newButtons[i].Size = new System.Drawing.Size(76, 38);

    tabPage5.Controls.Add(newButtons[i]);
}

This is creating a button and the click event is also working but my problem is I don't know how to get the text of the newly created button. On form load I am putting the text of button from database and this also happening correctly, but I want to know how to get the text of dynamically created buttons.

You won't be able to get the text until after you populate it from the database (careful not to try and get the text too early).

But this should work:

string buttonText = FindControl("Button41").Text;

Update

Since you want the button text from within the click event, you can access the sender object:

Button button = sender as Button;
string buttonText = button.Text;

您只需在添加按钮时设置按钮的Text属性。

Using something along the lines of...

string BtnTxt = FindControl("ExampleButton1").Text;

should work fine.

This may cause problems later on however if you are trying to pull text content of buttons in a random order.

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