Since the last focus will be on the Add button, you need to "remember" the TextBox before the Button is clicked.
Try to use onfocus() event.
<!-- Add a HiddenField control to "remember" the id of a TextBox -->
<asp:HiddenField ID="HiddenField1" runat="server" />
<!-- Assign current focus to that hidden field -->
<asp:TextBox onfocus="document.getElementById('HiddenField1').value=this.id" ...>
<asp:TextBox onfocus="document.getElementById('HiddenField1').value=this.id" ...>
If that works, you will be able to get a value in code-behind as
string c = HiddenField1.Value;
if (!string.IsNullOrEmpty(c))
if (c == "TextBox1")
TextBox1.Text = "hi there";
Note: depends on your environment you might need to call ClientID (e.g. getElementById('<%=HiddenField1.ClientID%>')
UPDATE
As I told you above you might need to use HiddenField1.ClientID to find the HiddenField Control. When your source looks as
<input type="hidden" name="ctl00$MainContent$HiddenField1" id="MainContent_HiddenField1" />
<input name="ctl00$MainContent$TextBox1" type="text" id="MainContent_TextBox1"
onfocus="document.getElementById('HiddenField1').value=this.id" />
<input name="ctl00$MainContent$TextBox2" type="text" id="MainContent_TextBox2"
onfocus="document.getElementById('HiddenField1').value=this.id" />
<input type="submit" name="ctl00$MainContent$Button1" value="Button" id="MainContent_Button1" />
That means that you use MasterPage and asp.net changes id of your control to MainContent_HiddenField1
. So when you use document.getElementById('HiddenField1')
it will not find such control because its id is different. You either need to use
document.getElementById('MainContent_Button1').value=this.id
which will work but might require changes if you remove master page or will move the textbox to other container
or use
document.getElementById('<%=HiddenField1.ClientID%>').value=this.id
which will automatically inject correct id (recommended asp.net way)