Send DropDownList selected value inside UserControl to another UserControl Label using JavaScript in ASP.Net

Last Reply 10 months ago By pandeyism

Posted 10 months ago

I'm pretty new ASP.Net and Javascript so I hope I'm explaining myself correctly.

Here is my scenario:

I have 2 UserControls. One UC contains a DropDownList control and the other UC contains a Label control. Both of these UC's are dropped onto an ASPX page. When the page is rendered, a user will select a value from the DDL and that value needs to be displayed in the Label control of the 2nd UC.

My question is this...

How can I access the selected value from the DDL and move that value into the Label using Javascript. I'm not sure what needs to be declared or where it needs to be declared. If I can do this without Javascript and without a PostBack...great. Otherwise, I figuired Javascript is the best way to handle this situation.

Thanks in advance!

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

Hi rsmldmv,

Please refer below sample.

HTML

WebUserControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
    Inherits="WebUserControl" %>
<asp:DropDownList ID="ddlFruits" runat="server" onchange="GetSelectedTextValue(this)">
    <asp:ListItem Text="Mango" Value="1"></asp:ListItem>
    <asp:ListItem Text="Grapes" Value="2"></asp:ListItem>
    <asp:ListItem Text="Banana" Value="3"></asp:ListItem>
    <asp:ListItem Text="Apples" Value="4"></asp:ListItem>
</asp:DropDownList>

WebUserControl2.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl2.ascx.cs"
    Inherits="WebUserControl2" %>
<asp:Label ID="lblMessage" runat="server"></asp:Label>

Default.aspx

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

<%@ Register Src="~/WebUserControl.ascx" TagPrefix="uc1" TagName="WebUserControl" %>
<%@ Register Src="~/WebUserControl2.ascx" TagPrefix="uc2" TagName="WebUserControl" %>
<!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>
    <script type="text/javascript">
        function GetSelectedTextValue(ddlFruits) {
            var selectedText = ddlFruits.options[ddlFruits.selectedIndex].value;
            document.getElementById('WebUserControl2_lblMessage').innerHTML = selectedText;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:WebUserControl runat="server" ID="WebUserControl1" />
        <uc2:WebUserControl runat="server" ID="WebUserControl2" />
    </div>
    </form>
</body>
</html>

Screenshot