Reputation: 1272
I want to get the text of the button whenever I click on it.
The algorithm that I made is where i have a function that is a loop that creates a number of buttons and assigns numbers:
void ListAllPage()
{
if (pageMax < 50)
{
//if page max less than 50
for (int i = 0; i < pageMax; i++)
{
Button newBtn = new Button();
newBtn.Text = i.ToString();
newBtn.Width = 50;
newBtn.Click += page_Clicked;
pageCell.Controls.Add(newBtn);
}
}
}
Now buttons will appear on the screen, their events will be triggered and the function page_Click; will be executed:
public void page_Clicked(object sender, EventArgs e)
{
//inside this function I want to obtain the button number that was clicked by the user. How do I do that?
}
Take note, I must all the functions that I described here,...
My thinking is to feed all the buttons that i created inside the loop to a dictionary.. Dictionary.. it will take variables like this btndic.Add(Button b=new Button,b.text);
But the issue is how to retrieve the buttons,,,
if there is a better way, i would like to hear about it...
Upvotes: 2
Views: 119
Reputation: 17274
in your ListAllPage
method assign Tag
to each button:
newBtn.Tag = i;
In your handler you can obtain button instance from sender
:
var clickedButton = (Button)sender;
int pageIndex = (int)clickedButton.Tag;
Upvotes: 1
Reputation: 1674
instead of using the Click Event -> Use the Command Event: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.oncommand.aspx then you can distinguish which button has been clicked
Upvotes: 2
Reputation: 13086
Try this way
public void page_Clicked(object sender, EventArgs e)
{
Button btn=(Button)sender;
}
Upvotes: 2
Reputation: 51224
You just need to cast the sender
object to a Button
, or more generally, a Control
:
public void page_Clicked(object sender, EventArgs e)
{
Control c = sender as Control;
MessageBox.Show("Clicked on " + c.Text);
}
Also, it might be more appropriate to use the Tag
property to store your custom information (number). In that case, Text
property can be anything you like.
Upvotes: 2