Solved

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

Posted on 2002-07-17
38
257 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
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
 
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

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…

751 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