Solved

How do I get the value from a listbox at runtime?

Posted on 2002-07-17
38
250 Views
Last Modified: 2010-04-14
I have setup a listbox with various values. How do I get the value back from that box. I have tried the following:

Me.DropDownList1.SelectedItem.Text

What am I doing wrong?
0
Comment
Question by:kenmck
  • 13
  • 12
  • 8
  • +2
38 Comments
 
LVL 23

Expert Comment

by:naveenkohli
ID: 7159145
There is a Value property for ListControl. If you are trying to get the value corresponding to elected item, then use that.

Me.DropDownList1.SelectedItem.Value

Text property will give you the text associated with that item.

Naveen
0
 

Author Comment

by:kenmck
ID: 7159179
I have just tried that and there was a value of test and the Me.DropDownList1.SelectedItem.Value returned " ".

Help!
0
 
LVL 5

Expert Comment

by:thenrich
ID: 7159296
Let's see code including the event that has this code in it.
0
 
LVL 23

Expert Comment

by:naveenkohli
ID: 7159333
How are you populting the list? As thenrich mentioned, please post your code.
0
 
LVL 4

Expert Comment

by:RichW
ID: 7159378
Where are you trying to get the value of the ListBox or DropDown, or what it is?

It's not probable but possible you may be trying to get the SelectedItem value before it's been set.

0
 

Author Comment

by:kenmck
ID: 7159393
   Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim strConn As String = ("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:\Helpdesk\helpdeskdata97.mdb;")
        Dim Conn As New OleDb.OleDbConnection(strConn)

        Dim strSQL As String = "SELECT distinct Faults_Logged.Call_Number FROM Faults_Logged"
        Dim Cmd As New OleDb.OleDbCommand(strSQL, Conn)
        Conn.Open()
        DropDownList1.DataSource = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
        DropDownList1.DataMember = "Call_Number"
        DropDownList1.DataTextField = "Call_Number"
        DropDownList1.DataValueField = "Call_Number"
        DropDownList1.DataBind()
        Conn.Close()
End Sub

To try and call the dropdown list I use the following:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim str1 As String = Me.DropDownList1.SelectedItem.Value
        Dim str2 As String = Me.DropDownList1.SelectedItem.Text
        Server.Transfer("Webform4.aspx")
    End Sub

Neither str1 nor str2 have any values?

Thanks,
0
 
LVL 23

Expert Comment

by:naveenkohli
ID: 7159427
Do you have any item selected in the list. Do a simple test..
check whats the value of Me.DropDownList.SelectedIndex

Make sure that this value is valid. If not that means there is no item selected in the list.
0
 
LVL 5

Expert Comment

by:thenrich
ID: 7159448
try this:

       Dim str1 As String = Me.DropDownList1.SelectedItem
       Dim str2 As String = Me.DropDownList1.SelectedItem
0
 

Author Comment

by:kenmck
ID: 7159455
The Me.DropDownList.SelectedIndex = "0"

I selected a value of 7802 from the dropdownlist.

Thanks,
0
 

Author Comment

by:kenmck
ID: 7159468
When I change the value selected the Me.DropDownList.SelectedIndex stays as "0"
0
 
LVL 4

Expert Comment

by:RichW
ID: 7159565
SelectedItem.Text is the 0 item of the index.  SelectedItem.Value is the text of the selected item.

Also create a DataReader and set that to the DataSource of the DropDownList control instead of the CommandObject.

Comment out the DropDownList1.DataValueField = "Call_Number" before the DataBind() and see what happens.

RichW



0
 

Author Comment

by:kenmck
ID: 7159753
Hi RichW,

This is my new code

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim strConn As String = ("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:\Helpdesk\helpdeskdata97.mdb;")
        Dim Conn As New OleDb.OleDbConnection(strConn)

        Dim strSQL As String = "SELECT distinct Faults_Logged.Call_Number FROM Faults_Logged"
        Dim Cmd As New OleDb.OleDbCommand(strSQL, Conn) 'New OleDb.OleDbCommand(strSQL, Conn)
        Conn.Open()
        Dim reader1 As OleDb.OleDbDataReader
        reader1 = Cmd.ExecuteReader()
        DropDownList1.DataSource = reader1
        DropDownList1.DataTextField = "Call_Number"
        DropDownList1.DataBind()
        reader1.Close()
        Conn.Close()
End Sub

       Dim str1 As String = Me.DropDownList1.SelectedItem.Value
       Dim str2 As String = Me.DropDownList1.SelectedItem.Text

When the datalistbox loads it displays the first record. When I change this it has no effect str1 and str2 are still always the first record and the DropDownList.SelectedIndex is always "0".

Help!
0
 
LVL 4

Expert Comment

by:RichW
ID: 7159826
This si the important part, where are you entering:
Dim str1 As String = Me.DropDownList1.SelectedItem.Value
      Dim str2 As String = Me.DropDownList1.SelectedItem.Text

0
 

Author Comment

by:kenmck
ID: 7159853
On pressing a button. See below:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim str3 As String = Me.DropDownList1.SelectedIndex
        Dim str1 As String = Me.DropDownList1.SelectedItem.Value
        Dim str2 As String = Me.DropDownList1.SelectedItem.Text
        Text2.Text = Me.DropDownList2.SelectedItem.Value
        Server.Transfer("Webform4.aspx")
    End Sub
0
 
LVL 4

Expert Comment

by:DarthPedro
ID: 7159857
The problem is that the dropdownlist box is being reset in your Page_Load event handler whenever there's a postback to the form (which includes the button click).  You need to change your code to not rebind on postbacks, which will maintain the DropDownList's current selection.

   Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
     If me.IsPostBack <> True Then
       'Put user code to initialize the page here
       Dim strConn As String = ("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:\Helpdesk\helpdeskdata97.mdb;")
       Dim Conn As New OleDb.OleDbConnection(strConn)

       Dim strSQL As String = "SELECT distinct Faults_Logged.Call_Number FROM Faults_Logged"
       Dim Cmd As New OleDb.OleDbCommand(strSQL, Conn) 'New OleDb.OleDbCommand(strSQL, Conn)
       Conn.Open()
       Dim reader1 As OleDb.OleDbDataReader
       reader1 = Cmd.ExecuteReader()
       DropDownList1.DataSource = reader1
       DropDownList1.DataTextField = "Call_Number"
       DropDownList1.DataBind()
       reader1.Close()
       Conn.Close()
     End If
End Sub

The button_click function should then work as written.
0
 
LVL 4

Accepted Solution

by:
DarthPedro earned 50 total points
ID: 7159864
Oh yeah, and you can go back to your original Page_Load code which included setting the value field:

       DropDownList1.DataSource = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
       DropDownList1.DataMember = "Call_Number"
       DropDownList1.DataTextField = "Call_Number"
       DropDownList1.DataValueField = "Call_Number"
       DropDownList1.DataBind()
0
 

Author Comment

by:kenmck
ID: 7161761
My new code is as follows:

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Me.IsPostBack <> True Then
            'Put user code to initialize the page here
            Dim strConn As String = ("PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:\Helpdesk\helpdeskdata97.mdb;")
            Dim Conn As New OleDb.OleDbConnection(strConn)

            Dim strSQL As String = "SELECT distinct Faults_Logged.Call_Number FROM Faults_Logged"
            Dim Cmd As New OleDb.OleDbCommand(strSQL, Conn) 'New OleDb.OleDbCommand(strSQL, Conn)
            Conn.Open()
            DropDownList1.DataSource = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
            DropDownList1.DataMember = "Call_Number"
            DropDownList1.DataTextField = "Call_Number"
            DropDownList1.DataValueField = "Call_Number"
            DropDownList1.DataBind()
            Conn.Close()
        End If
End Sub

My button Press is as follows:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' On Error Resume Next
        Dim str3 As String = Me.DropDownList1.SelectedIndex
        Dim str1 As String = Me.DropDownList1.SelectedItem.Value
        Server.Transfer("Webform4.aspx")
    End Sub

I then get the following error:

Object reference not set to an instance of an object.

What am I doing wrong?
0
 
LVL 4

Expert Comment

by:RichW
ID: 7161810
I just ran your code, switch the db info, and I had no problem.  

Check for NULL values in the page.

Where exactly does the error occur?
0
 

Author Comment

by:kenmck
ID: 7161814
The problem happens when I press the button1 at the following line:

Dim str1 As String = Me.DropDownList1.SelectedItem.Value
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 4

Expert Comment

by:RichW
ID: 7161878
Really dumb question, but did you select anything in the list before you clicked the button?

0
 

Author Comment

by:kenmck
ID: 7161960
Yes, I did!!
0
 
LVL 4

Expert Comment

by:RichW
ID: 7162000
Is the Call_Number field an Integer type field?  You're passing that value into a String.

Try converting the value to an Integer type, or try adding .ToString after .Value.

Other than that I don't have a good answer.  I have no problem with the code on my end.
0
 
LVL 4

Expert Comment

by:DarthPedro
ID: 7163368
What is the return value for SelectedIndex:
       Dim str3 As String = Me.DropDownList1.SelectedIndex
0
 

Author Comment

by:kenmck
ID: 7164062
-1
0
 
LVL 4

Expert Comment

by:RichW
ID: 7164488
-1 means there was no selection.  Did you include the If Not IsPostBack Then statement????




0
 
LVL 4

Expert Comment

by:DarthPedro
ID: 7170838
For some reason the listbox doesn't think anything is selected.  You should check the Page_Load event again, as RichW suggested - maybe post it again.  I assume that you are getting items in the listbox when the page first loads, right?

0
 

Author Comment

by:kenmck
ID: 7171097
Yes all the items load up they just do not seam to realise that they have just been selected!!
0
 
LVL 4

Expert Comment

by:RichW
ID: 7171686
I hate to be redundant, to repeat myself, to say the same thing over and over, LOL, but did you use the If Not IsPostBack Then statement before you test the the Me.DropDownList1.SelectedIndex?

If you really selected a item in the DropDownList, and you're getting a -1 result, it really means that you're not testing for PostBack, otherwise I can't think of anything else, in this situation, that would cause this.

RichW
 
0
 
LVL 4

Expert Comment

by:DarthPedro
ID: 7172211
One quick question that just occurred to me.  
What is the   Server.Transfer("Webform4.aspx") call for?
0
 
LVL 4

Expert Comment

by:RichW
ID: 7172434
He's using that instead of Page.Response.Redirect

0
 
LVL 4

Expert Comment

by:DarthPedro
ID: 7172499
I understand that, but why?  Where is he going to?  What's Webfor4.aspx?
0
 
LVL 4

Expert Comment

by:RichW
ID: 7172704
Probably just the name of his .aspx form.

0
 
LVL 4

Expert Comment

by:RichW
ID: 7172709
Server.Transfer acts as an efficient replacement for Response.Redirect. Response.Redirect tells the browser to request a different page. Since a redirect forces a new page request, the browser has to make two round trips to the Web server, and the Web server has to handle an extra request. IIS 5.0 introduced a new function, Server.Transfer, which transfers execution to a different ASP page on the server. This avoids the extra round trip, resulting in better overall system performance, as well as a better user experience.

0
 
LVL 4

Expert Comment

by:RichW
ID: 7172758
>>"Yes all the items load up they just do not seam to realise that they have just been selected!! "

Darthpedro, do you think he's talking about the SelectedIndexChanged event not recognizing that an item has been selected?

I mean, I know we're talking about code in a Button, but with the way this thread has been going I'm grabbing at straws.

I know if you have the DropDownList's AutoPostBack property set to False (the default), you may experience problems getting the values of selected items in the SelectedIndexChanged event until the server makes another trip.  Changing it to True resolves this problem.

Again, just grabbing at straws.

RichW
0
 
LVL 4

Expert Comment

by:DarthPedro
ID: 7172799
I was thinking that he's using Server.Transfer incorrectly. Is it being used to go back to the current page.  If that's the case he is forcing a the Page_Load event to run again, but this time the IsPostBack would be false because ASP.NET context would be different, so the DropDownList would be databound again, which would clear the selection.  That seems to be the effect that he's experiencing.

So, that's why I was asking what the Server.Transfer was actually doing.  What happens on the page without the Server.Transfer call?

But, I'm grasping too...
0
 
LVL 4

Expert Comment

by:RichW
ID: 7173080
lol

I think that's the page he's going to after the update of the string variables.

I tested the SelectedIndexChanged event for a DropDownList control, and when you set the control's AutoPostBack property to True it will fire, but the Index is still 0.  Maybe that's what he's talking about?





0
 
LVL 4

Expert Comment

by:DarthPedro
ID: 7175286
It would be nice to get a comment from kenmck...
0
 

Author Comment

by:kenmck
ID: 7176657
I have recreated this form from scratch and used the code above and it is working!!!

On my old form it still does not and that is using the same code.

Go figure?  

Thanks for all your help.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Normally the drop down box control found in the .Net framework tools is able to select just one data and value at a time, which is displayed on the text area.   But what if you want to have multiple values to be selected in the drop down box? As …
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now