Get Button ID inside ASP.Net UserControl on ASPX page using C# and VB.Net

Last Reply 4 months ago By pandeyism

Posted 4 months ago

i want to call user control button from page server side and get its id and name and set to text box please help me thanks

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Button ID="Button1" runat="server" Text="Button" />

i have above user control having button

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Src="~/WebUserControl.ascx" TagPrefix="uc1" TagName="WebUserControl" %>


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:WebUserControl runat="server" id="WebUserControl" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>

 

You are viewing reply posted by: pandeyism 4 months ago.
Posted 4 months ago

Hi arehman,

Refer below sample.

HTML

CS.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>

<%@ Register TagPrefix="uc" Src="~/WebUserControl.ascx" TagName="Submit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc:Submit ID="ucButton" runat="server" />
    </div>
    </form>
</body>
</html>

WebUserControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
    Inherits="WebUserControl" %>
<asp:Button Text="Submit" runat="server" ID="btnSubmit" />

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    Button btn = this.FindControl("ucButton").FindControl("btnSubmit") as Button;
    btn.Click += new EventHandler(Save);
}

protected void Save(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('ID is : " + (sender as Button).ID + "');", true);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim btn As Button = TryCast(Me.FindControl("ucButton").FindControl("btnSubmit"), Button)
    AddHandler btn.Click, AddressOf Save
End Sub

Protected Sub Save(ByVal sender As Object, ByVal e As EventArgs)
    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "Message", "alert('ID is : " & (TryCast(sender, Button)).ID & "');", True)
End Sub

Screenshot