How do I get the text value of a button

Hi,

How can I get the text value of a clicked button control in asp.net?

I am using a group of buttons as a number pad like on an ATM machine or a calculator and want to display the values in a textbox. Please see example code below.
Thanks.

(on asp.net page)
<asp:Button ID=“btn1” runat=“server” Text=“1” OnClick=“Add_It” />

(in code behind)
protected void Add_It(Object s, EventArgs e)
{
string strVal = [the text value from the clicked button];
txtLogin.Text += strVal;
}

Did you try btn1.Text ? You’ll have to have a click handler for each button though.

Thanks for your response.

All the buttons are calling the same function so I need to identify which button clicked before I can get the value. That’s the issue. How to identify the button. The easy solution is to have a separate function for each button but I would like to try it with only one function that is called.

Button.CommandName

Button.CommandName Property (System.Web.UI.WebControls)

^^^CommandName is the way to go, not Text. Will have to be separately specified though.

Yes,
Commandname worked.

Thanks.

I learned something new here. :slight_smile:

CommandName is not really intended for this, although it will work. But you don’t need it:

    &lt;asp:Button ID="btn1" runat="server" Text="1" onclick="Add_It" /&gt;
    &lt;asp:Button ID="btn2" runat="server" Text="2" onclick="Add_It" /&gt;
    &lt;asp:Button ID="btn3" runat="server" Text="3" onclick="Add_It" /&gt;
    &lt;asp:Button ID="btn4" runat="server" Text="4" onclick="Add_It" /&gt;
    &lt;asp:Button ID="btn5" runat="server" Text="5" onclick="Add_It" /&gt;
    &lt;asp:Button ID="btn6" runat="server" Text="6" onclick="Add_It" /&gt;
    &lt;asp:Button ID="btn7" runat="server" Text="7" onclick="Add_It" /&gt;
    &lt;asp:Button ID="btn8" runat="server" Text="8" onclick="Add_It" /&gt;
    &lt;asp:Button ID="btn9" runat="server" Text="9" onclick="Add_It" /&gt;
    &lt;asp:Button ID="btn0" runat="server" Text="0" onclick="Add_It" /&gt;

protected void Add_It(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    txtLogin.Text += btn.Text;
}

Care to explain why it isn’t intended? I think you have a bigger issue relying upon the UI text to run back-end logic, it is a nasty reverse dependency waiting to happen.

That’s what I was trying to remember. Since switching to MVC I haven’t touched this stuff. :wink: