Hi Adam,
Thank you for your kind words. Good to hear you like the book so much...
You *can* hook up the same handler to multiple buttons. Simply assign the OnClick to the same handler (C#) or specify multiple controls in the Handles section of the handler in
VB.
So, for example in C# you can do this:
Code:
<asp:Button ID="Button1" runat="server" Text="1" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="2" onclick="Button1_Click" />
Then in Code Behind, you can cast the Sender to a Button and get its Text which holds the number:
Code:
protected void Button1_Click(object sender, EventArgs e)
{
Button myButton = sender as Button;
if (myButton != null)
{
int value = Convert.ToInt32(myButton.Text);
}
}
However, this is not the best solutionn. The application breaks if you use text numbers (one, two and so on) or add other markup to the button. So, it's better to use a CommandName and CommandArgument:
Code:
<asp:Button ID="Button1" runat="server" Text="1" onclick="Button1_Click" CommandName="InputNumber" CommandArgument="1" />
<asp:Button ID="Button2" runat="server" Text="2" onclick="Button1_Click" CommandName="InputNumber" CommandArgument="2" />
<asp:Button ID="Button3" runat="server" Text="+" onclick="Button1_Click" CommandName="Operate" CommandArgument="+" />
Notice how the numeric buttons have an CommandName of InputNumber (arbitrarily chosen) and a CommandArgument with the number they represent. The Plus button has a CommandName of Operate. Now, in code behind you can do stuff like this:
Code:
protected void Button1_Click(object sender, EventArgs e)
{
Button myButton = sender as Button;
if (myButton != null)
{
switch (myButton.CommandName)
{
case "InputNumber":
int value = Convert.ToInt32(myButton.CommandArgument);
// Do what you need to do with the number here
break;
case "Operate":
string theOperator = myButton.CommandArgument ;
// Do what you need to do with the operator here
break;
}
}
}
This way, inside the Click handler you can look at the CommandName (a number is clicked, or an operator is clicked) and the CommandArgument (to find out which number or operator was clicked).
Hope this helps,
Imar