javascriptasp.net.netwebusercontrol

How to use WebUserControl multiple times on same web page


Work on Asp.net web page application.I have one user WebUserControl,it’s contain two textboxes and couple of javascript syntax,my control copy one text box information in another text box.Problem arise when I used my user control several times on same page . After used several times my user control not working properly,How to solve this issue

My user control syntax:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="transferControl.ascx.cs" Inherits="testControl.transferControl" %>


    <script type="text/javascript">
        function IsAccNumberValid(txtAccountNumber) {
            debugger;
            document.getElementById("<%= txtTo.ClientID %>").value = txtAccountNumber.value;
        }
</script>


<asp:TextBox runat="server" ID="txtFrom" onblur="Javascript:IsAccNumberValid(this);" />

<asp:TextBox ID="txtTo" runat="server"></asp:TextBox>

My used page syntax:

<%@ Register src="transferControl.ascx" tagname="transferControl" tagprefix="uc1" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">


    <uc1:transferControl ID="transferControl1" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Button" />
    <uc1:transferControl ID="transferControl2" runat="server" />


</asp:Content>

Solution

  • Change your User control code like this. Following code is replacing IsAccNumberValid() function with a direct Javascript statements. So there won't be any duplicate function definition.

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="transferControl.ascx.cs" Inherits="testControl.transferControl" %>
    
    <asp:TextBox runat="server" ID="txtFrom"  />
    <asp:TextBox ID="txtTo" runat="server"  ></asp:TextBox>
    <script type="text/javascript">
            var txtFrom = document.getElementById("<%= txtFrom.ClientID %>");
            var txtTo = document.getElementById("<%= txtTo.ClientID %>");
    
            txtFrom.onblur = function () {
                txtTo.value = txtFrom.value;
            }
    </script>