DropDownlist selectedITem in asp.net

H,

I am working with dropdownlists and am trying to pass the selected item to a textbox field or checkif selected Item is a certain value:

Here is what I have done:

If objDropDownListID.SelectedItem.Value = "MMM" Then ......

It just doesn't work...I even tried text instead of value.....

Thanks in advance

shmzAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Harisha M GEngineerCommented:
Hi shmz,
   Try..
    If objDropDownListID.SelectedItem.Text = "MMM" Then

Bye
---
Harish
Harisha M GEngineerCommented:
shmz,
    Sorry.. try

If objDropDownListID.Text = "MMM" Then
shmzAuthor Commented:

Thanks mg_mgharish, but 'Text' is not a member of DropDownList  web control.
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Harisha M GEngineerCommented:
Try.. objDropDownListID.Value
Diablo84Commented:
Should you not be using the comparison operator as opposed to the assignment operator in the if statement,
ie == rather then =

Diablo84
Harisha M GEngineerCommented:
shmz are you using java or vb to do this ?
Harisha M GEngineerCommented:
Diablo84, == is used in javascript not in vb/asp etc.
shmzAuthor Commented:

 I am using VB.Net.

I have used this  objDropDownListID.SelectedItem.Text in the past to pass values to db parameter and
it has been working fine but I don't understand why it is not not working for comparason.

 objDropDownListID.Text or  objDropDownListID.Value are not working in .NET

== doesn't work either. I also think it is used in javascript.

Thanks

shmzAuthor Commented:
I'll check comments in abuout 2 hours. thanks anyway.
ecc204Commented:
if (objDropDownListID.SelectedValue = "xxxxxxxxxxx") then
DevastatedCommented:
so far ive got the if statement working...

trying to get the rest done for you if i got time...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>WebForm1</title>
            <script runat="server">
                  Sub submit(sender As Object, e As EventArgs)
                        mess.Text="You selected " & drop1.SelectedItem.Text
                  End Sub
            </script>
      </HEAD>
      <body>
            <form runat="server" ID="Form1">
                  <asp:DropDownList id="drop1" runat="server">
                        <asp:ListItem>Item 1</asp:ListItem>
                        <asp:ListItem Value="MMM">This will print its working</asp:ListItem>
                        <asp:ListItem Value="mmm">This will NOT print its working</asp:ListItem>
                        <asp:ListItem>Item 5</asp:ListItem>
                  </asp:DropDownList>
                  <asp:TextBox id="txt1" runat="server" />
                  <asp:Button Text="Submit" OnClick="submit" runat="server" ID="Button1" NAME="Button1" />
                  <p><asp:label id="mess" runat="server" /></p>
                  <% If drop1.SelectedItem.Value = "MMM" Then %>
                        its working
                  <% End if %>
            </form>
      </body>
</HTML>
DevastatedCommented:
ignore the previous code...

here is an improved working version that illustrates how to get the if statement working as you want and also how to copy the text or value of the selected item to a textbox...

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>WebForm1</title>
            <script runat="server">
                  Sub submit(sender As Object, e As EventArgs)
                        mess.Text="You selected " & drop1.SelectedItem.Text
                        If drop1.SelectedItem.Value = "MMM" Then
                              txt1.Text = drop1.SelectedItem.Value.ToString
                              txt2.Text = drop1.SelectedItem.Text.ToString
                        End if
                  End Sub
            </script>
            <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
            <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
            <meta name="vs_defaultClientScript" content="JavaScript">
            <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body>
            <form runat="server" ID="Form1">
                  <asp:DropDownList id="drop1" runat="server">
                        <asp:ListItem>Item 1</asp:ListItem>
                        <asp:ListItem Selected>Item 2</asp:ListItem>
                        <asp:ListItem Value="MMM">This will work</asp:ListItem>
                        <asp:ListItem Value="mmm">This will NOT work</asp:ListItem>
                        <asp:ListItem>Item 5</asp:ListItem>
                  </asp:DropDownList>
                  Value:<asp:TextBox id="txt1" runat="server" />
                  &nbsp;Text:<asp:TextBox id="txt2" runat="server" />
                  <asp:Button Text="Submit" OnClick="submit" runat="server" ID="Button1" NAME="Button1" />
                  <p><asp:label id="mess" runat="server" /></p>
                  <asp:Label id="Label1" runat="server" />
            </form>
      </body>
</HTML>

hope this helps.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DevastatedCommented:
Oops remove this line from the above snippet (forgot to remove it - bloomin vs.net and its codey bits it likes to add)

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%>

as you dont have or need this codebehind file/reference
shmzAuthor Commented:
Thanks eveyone,

The if condition must work with this: " drop1.SelectedItem.Text"
My code was wrong some where else.

Thanks , specially Devastated, this line was very imformative:
drop1.SelectedItem.Text.ToString

didn't know it.

Regards
Harisha M GEngineerCommented:
>> The if condition must work with this: " drop1.SelectedItem.Text"

Wasn't that provided by me ?
Harisha M GEngineerCommented:
DevastatedCommented:
Your welcome...

yes it does seem that your if statement was correct - maybe the logic or another error was causing the problem...

.ToString is a very nice habit to get into - i.e. make sure variables types are compatible, dont rely on VB to 'cast' them properly.
EdFernan1016Commented:
I'm using your code to get value from a drpdown list where the value is email address but your code is not working on my page.

Please help
Imports System.Web
Imports System.Web.Mail
Imports System.Web.Configuration
Imports System.Web.UI.HtmlControls.HtmlTextArea
Imports System.IO
Imports System.Text.RegularExpressions
Public Class personalizeRecCard
    Inherits System.Web.UI.UserControl
 
#Region " Web Form Designer Generated Code "
 
    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
 
    End Sub
    Protected WithEvents hyperlink1 As System.Web.UI.WebControls.HyperLink
    Protected WithEvents Label5 As System.Web.UI.WebControls.Label
	Protected WithEvents fileNamelbl As System.Web.UI.WebControls.Label
    Protected WithEvents HyperLink2 As System.Web.UI.WebControls.HyperLink
    Protected WithEvents Label6 As System.Web.UI.WebControls.Label
    Protected WithEvents personalizelbl As System.Web.UI.WebControls.Label
    Protected WithEvents ValidationSummary2 As System.Web.UI.WebControls.ValidationSummary
    Protected WithEvents Label10 As System.Web.UI.WebControls.Label
	Protected WithEvents emailLbl As System.Web.UI.WebControls.Label
	Protected WithEvents Label10 As System.Web.UI.WebControls.Label
	Protected WithEvents HospitalDownList As System.Web.UI.WebControls.DropDownList
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    Protected WithEvents senderNametxt As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator4 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents Label8 As System.Web.UI.WebControls.Label
    Protected WithEvents EmailFromTxt As System.Web.UI.WebControls.TextBox
	Protected WithEvents emailToTxt As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator1 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents Label2 As System.Web.UI.WebControls.Label
    Protected WithEvents RegularExpressionValidator1 As System.Web.UI.WebControls.RegularExpressionValidator
    Protected WithEvents Label3 As System.Web.UI.WebControls.Label
    Protected WithEvents RecipientNametxt As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator5 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents Label9 As System.Web.UI.WebControls.Label
    Protected WithEvents HospitalDownList As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator2 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents Label7 As System.Web.UI.WebControls.Label
    Protected WithEvents RegularExpressionValidator2 As System.Web.UI.WebControls.RegularExpressionValidator
    Protected WithEvents Label4 As System.Web.UI.WebControls.Label
    Protected WithEvents RequiredFieldValidator3 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents selectedCardlbl As System.Web.UI.WebControls.Label
    Protected WithEvents Image1 As System.Web.UI.WebControls.Image
    Protected WithEvents descriptionlbl As System.Web.UI.WebControls.Label
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    Protected WithEvents cell2 As System.Web.UI.HtmlControls.HtmlTableCell
    Protected WithEvents messagetxt As System.Web.UI.HtmlControls.HtmlTextArea
		Protected WithEvents Mess As System.Web.UI.WebControls.Label
 
    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object
 
    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub
 
#End Region
 
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Page.IsPostBack Then
            BindList()
        End If
    End Sub
    Private Sub BindList()
        Dim CardId As String
        CardId = Request.Params("CardId")
 
        Dim card As New RecdCardsUtility
        Dim selectedCard As carddetails
        Dim selectedCardcategory As categorydetails
 
        selectedCard = card.getCardDetails(CardId)
        selectedCardcategory = card.GetCategoryDetails(selectedCard.CardCategoryId)
 
        Image1.ImageUrl = "../card_thumbnails/" & selectedCard.FileName
        descriptionlbl.Text = selectedCard.FileName
		descriptionlbl.Text = selectedCard.CardDescription
		 fileNamelbl.Text = selectedCard.FileName
		 'emailToTxt.Text = HospitalDownList.SelectedItem.Value.ToString 
		     'mess.Text="You selected " & HospitalDownList.SelectedItem.Value.ToString 
        HyperLink2.Text = "&nbsp;&nbsp;Card Selection&nbsp;&nbsp;-&nbsp;&nbsp;" & selectedCardcategory.DisplayName
        HyperLink2.NavigateUrl = "../categoryItems.aspx?categoryId=" & selectedCard.CardCategoryId
    End Sub
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
         
		If Page.IsValid Then
            Dim CardId As String
            CardId = Request.Params("CardId")
            Dim card As New RecdCardsUtility
 
            Dim strInput As String
            Dim strOutput As String
            strInput = messagetxt.Value
            strOutput = Regex.Replace(strInput, "<[^>]*>", " ")
            'output.Text = strOutput
            'output_raw.Text = Server.HtmlEncode(Text1.Text)
            
 
                        If HospitalDownList.SelectedItem.Text = HospitalDownList.SelectedItem.Text Then
                             emailToTxt.Text = drop1.SelectedItem.Value.ToString
                              mess.Text="You selected " & HospitalDownList.SelectedItem.Text.ToString            
 
             
            Dim i As Integer
            Try
                i = card.insertCardSentInformation(CardId, senderNametxt.Text, EmailFromTxt.Text, RecipientNametxt.Text, emailToTxt.Text, Server.HtmlEncode(messagetxt.Value))
 
            Catch ex As Exception
                Response.Redirect("error.aspx")
            Finally
 
 
 
            End Try
 
        End If
    End Sub
 
    Private Sub messagetxt_ServerChange(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles messagetxt.ServerChange
 
    End Sub
End Class

Open in new window

PersonalizedCard.txt
PersonalizedCardVBcode.txt
EdFernan1016Commented:
I am working with dropdownlist and I am trying to pass the selected item value (email address) to a textbox field but using a code found in this website is not working.

thanks.


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
         
		If Page.IsValid Then
            Dim CardId As String
            CardId = Request.Params("CardId")
            Dim card As New RecdCardsUtility
 
            Dim strInput As String
            Dim strOutput As String
            strInput = messagetxt.Value
            strOutput = Regex.Replace(strInput, "<[^>]*>", " ")
            'output.Text = strOutput
            'output_raw.Text = Server.HtmlEncode(Text1.Text)
            
 
                        If HospitalDownList.SelectedItem.Text = HospitalDownList.SelectedItem.Text Then
                             emailToTxt.Text = drop1.SelectedItem.Value.ToString
                              mess.Text="You selected " & HospitalDownList.SelectedItem.Text.ToString            
 
             
            Dim i As Integer
            Try
                i = card.insertCardSentInformation(CardId, senderNametxt.Text, EmailFromTxt.Text, RecipientNametxt.Text, emailToTxt.Text, Server.HtmlEncode(messagetxt.Value))
 
            Catch ex As Exception
                Response.Redirect("error.aspx")
            Finally
 
 
 
            End Try
 
        End If
    End Sub

Open in new window

PersonalizedCard.txt
PersonalizedCardVBcode.txt
DevastatedCommented:
What is the error you are getting exactly?

P.S. String comparisons i.e. HospitalDownList.SelectedItem.Text = HospitalDownList.SelectedItem.Text are not 'best practice'
EdFernan1016Commented:
This line of code is not working:
A .If HospitalDownList.SelectedItem.Text = HospitalDownList.SelectedItem.Text Then
                             emailToTxt.Text = drop1.SelectedItem.Value.ToString
                              mess.Text="You selected " & HospitalDownList.SelectedItem.Text.ToString  
    and used this line too still not working:
B. If HospitalDownList.SelectedItem.Text = " " Then
                             emailToTxt.Text = drop1.SelectedItem.Value.ToString
                              mess.Text="You selected " & HospitalDownList.SelectedItem.Text.ToString        
 
c. If HospitalDownList.SelectedItem.Text = " " Then
d.If HospitalDownList.SelectedItem.Text > -1 Then
Thanks for your help...
DevastatedCommented:
Surely d. should be If HospitalDownList.SelectedIndex > -1

Your code seems fine, have you tried debugging it and stepping through line by line and checking their values?

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Development

From novice to tech pro — start learning today.