?
Solved

listbox1.selecteditem.tostring question

Posted on 2003-03-27
24
Medium Priority
?
479 Views
Last Modified: 2010-10-05
when using this code:

label3.text = listbox1.selecteditem.tostring

which i have found in a  few examples on the web, doesnt seem to work, the listbox1 is bound to a dataset, everything seem to work great, but i get an error when the form loads and the label doesnt get updated,  heres my full code:

    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Try
            Label3.Text = ListBox1.SelectedItem.ToString
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

the error is as follows:

system.nullrefernceexception:object refernce not set to an instance of an object.
at purchase_orders.jobsedit.listbox1_selectedindexchanged(object sender, eventargs e)

what i want to accomplish, is when a user clicks on an item in the listbox, the label displays the text from the listbox
0
Comment
Question by:dysasha
[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
  • 12
  • 8
  • 2
  • +2
24 Comments
 

Author Comment

by:dysasha
ID: 8219502
with the try method, after the errors (one for each item in the listbox) the label3 displays:

system.data.datarowview

instead of needed text
0
 
LVL 6

Expert Comment

by:CarlosMu
ID: 8219656
Can you show the code with wich you binded the listbox to the dataset.  Did you set the Displaymember and Value member properties of the listbox
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 8219734
Check if you fill the listbox in page_load event. It might reinitialize the listbox on and it does not have reference set.
0
Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

 

Author Comment

by:dysasha
ID: 8219837
heres the code thats sets the selectcommand and fills the dataset for the listbox (the listbox is bound to dsjoblist21)

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim selitem As String
        selitem = ComboBox1.Text
        SqlDataAdapter2.SelectCommand.CommandText = "SELECT JobNumber FROM JobNumbers WHERE (Project = N'" + selitem + "') ORDER BY JobNumber"
        DsJoblist21.Clear()
        SqlConnection1.Close()
        SqlConnection1.Open()
        SqlDataAdapter2.Fill(DsJoblist21)
        SqlConnection1.Close()
    End Sub


i did set the datasource and datamember, but i did it in the listbox properties instead of via code
0
 

Author Comment

by:dysasha
ID: 8219842
also, i treid adding this to the on load:

        ListBox1.DisplayMember = "Text"

0
 
LVL 4

Expert Comment

by:farzinm
ID: 8220031
Check whether any of the items in the listbox is selected before you assign the value of the selected item to the listbox
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
       Try
        if (Listbox1.selectedindex <> -1) then
          Label3.Text = ListBox1.SelectedItem.ToString
        End If
       Catch ex As Exception
           MessageBox.Show(ex.ToString)
       End Try
End Sub


0
 

Author Comment

by:dysasha
ID: 8220079
we, i'm not sure if its a step forward.. but it looks better,  the pop up error disappeared, even if i remove the try/catch statement,  but the label still says:

system.data.datarowview

reguardless of which item i select..

any more thoughts?
0
 
LVL 4

Expert Comment

by:farzinm
ID: 8220133
I dont know whether this is the solution to your problem or not but this is what I tried on a test page.
The OnSelectedIndexChanged event of the listbox did not fire for me until I changed the autopostback property to "true".
Dont know whether it will work in your existing code but you can give it a shot.
Good Luck!
0
 

Author Comment

by:dysasha
ID: 8220163
The OnSelectedIndexChanged event of the listbox did not fire for me until I changed the autopostback property to "true".

huh?  i cant locate this property
0
 
LVL 4

Expert Comment

by:farzinm
ID: 8220183
Its a behaviour of the listbox. You will find it in the properties dialog (window) of the listbox.
0
 

Author Comment

by:dysasha
ID: 8220234
sir, i've looked and looked, and i cant find it, are you by chance using vb.net?  perhaps you could narrow it down a bit, what group are you seeing it in? and what else is near it,  ive expanded all the groups, and i dont see it anywhere
0
 
LVL 4

Expert Comment

by:farzinm
ID: 8220260
lol :) Alright you can try this on the page_load
sub page_load(sender As Object, e As EventArgs)
  listbox1.autopostback=true
end sub

I am using webmatrix but I believe that VS.Net also has it in its properties window cant be sure though.
0
 

Author Comment

by:dysasha
ID: 8220277
autopostback is not a memeber of system.windows.forms.listbox?
0
 

Author Comment

by:dysasha
ID: 8220300
perhaps you are referencing something i am not?

Imports System.Windows.Forms
Imports System.Data  are the imports ive used...
0
 
LVL 4

Expert Comment

by:farzinm
ID: 8220339
You are right! We are not referencing to the same thing. I get a
Namespace or type 'Forms' for the Imports 'System.Windows.Forms' cannot be found.
Let me get back to u if I find something.
0
 
LVL 4

Expert Comment

by:farzinm
ID: 8220381
I am referencing to System.Web.UI.WebControls.ListBox which I believe is always the default one with my webmatrix pages.
0
 

Author Comment

by:dysasha
ID: 8220395
i see :(   i was hoping i had found a solution

any other thoughts?
0
 
LVL 6

Expert Comment

by:CarlosMu
ID: 8220531
If you are writting a Web page you should not be using
Imports System.Windows.forms

those are the imports for a Visual basic to run on a windows enviroment.

try to include the imports that farzinm is using instead.
0
 

Author Comment

by:dysasha
ID: 8220549
hmm, scroll up a bit, i'm not writing a webpage
0
 
LVL 4

Expert Comment

by:farzinm
ID: 8220641
just a thought ...maybe you need to add event handlers?
0
 
LVL 4

Expert Comment

by:farzinm
ID: 8220696
ok ignore my previous comment I dont think you need to add handlers
0
 
LVL 12

Accepted Solution

by:
farsight earned 200 total points
ID: 8226355
>with the try method, after the errors (one for each item in the listbox) the label3 displays:
>system.data.datarowview

Because binding to the database results in the items in the listbox being DataRowView objects.  ToString on such an item returns "system.data.datarowview".

The question is: What part of the DataRowView do you wish to display?

Maybe this example will help.

Option Strict On        ' Don't program without this!
    ' Build a form with controls:
    '    Button1, ListBox1, Label1, Label2, and Label3, Label4.
    ' Then paste this code in.

    Private Const myDisplayMember As String = "LastName"
    Private Const myValueMember As String = "EmployeeID"

    Dim DataSet1 As New DataSet()

    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Try
            Dim theListBox As ListBox = DirectCast(sender, ListBox)

            ' Show text of selected item.
            Label1.Text = theListBox.GetItemText(theListBox.SelectedItem)
            ' Show value of selected item.
            Label2.Text = theListBox.SelectedValue.ToString

            ' The following is useful when a ListBox is bound to a DataTable.
            Dim drv As DataRowView = DirectCast(theListBox.SelectedItem, DataRowView)
            ' Show one column.
            Label3.Text = drv.Item(myDisplayMember).ToString
            ' Show multiple columns.
            Label4.Text = String.Format("{1} {0} is from {2}.", drv.Item("LastName"), drv.Item("FirstName"), drv.Item("City"))
        Catch ex As Exception
            Debug.Assert(ex Is Nothing)     ' Should never be reached now.
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

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

        ' Make an appropriate data adapter with connection in any way you want.
        ' Northwind database on MS SQL Server is used here. Change SQLDB as appropriate.
        Dim connect As String = "data source=ILINK2;initial catalog=Northwind;integrated security=SSPI"
        Dim SqlDataAdapter2 As New SqlClient.SqlDataAdapter("SELECT * FROM Employees", connect)

        ' Build the dataset in any way you want.
        DataSet1.Clear()
        SqlDataAdapter2.Fill(DataSet1)

        ' To avoid getting extraneous ListBox1_SelectedIndexChanged events,
        ' (1) Make sure the design-time values of DisplayMember,
        '     ValueMember, and DataSource are cleared for ListBox1, and
        ' (2) Set DisplayMember and ValueMember before setting DataSource.

        ' Bind the first table of the DataSet to the ListBox.
        ListBox1.DisplayMember = myDisplayMember
        ListBox1.ValueMember = myValueMember
        ListBox1.DataSource = DataSet1.Tables(0)
    End Sub

0
 

Author Comment

by:dysasha
ID: 8226537
       Dim theListBox As ListBox = DirectCast(sender, ListBox)
        Label3.Text = theListBox.GetItemText(theListBox.SelectedItem)



was exactly what i was looking for, i wasnt aware of directcast... reccomend any good books that dont prattle on about hello world and filling a dataset?  something more advanced, that doesnt assume you know vb6?
0
 

Author Comment

by:dysasha
ID: 8226541
thanks again!
0

Featured Post

How To Reduce Deployment Times With Pre-Baked AMIs

Even if we can't include all the files in the base image, we can sometimes include some of the larger files that we would otherwise have to download, and we can also sometimes remove the most time-consuming steps. This can help a lot with reducing deployment times.

Question has a verified solution.

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

Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

801 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