none
listBox.SelectedItem

    Question

  • I’m using C# 2008 Express. I’m using an SQL database to store tables. I have a Port table that stores a list of comm ports. I connect to the database and bind the table to a ListBox control. No problems there.

    The problem is when I try to read which port has been selected by the user.

    The code inside the Button Event is:

    string curPort = listBoxPort.SelectedItem.ToString();

    curPort actually gets loaded with the string “System.Data.DataViewRow” instead of “Com01” or”Com02”.

    Huh?

    Wednesday, August 20, 2008 9:30 PM

Answers

  • System.Data.DataViewRow is a type in the .NET framework.  The default implementation of .ToString() with types is to return the type name.  So what you'll need to do is cast your SelectedItem to a DataViewRow, and drill down through your data to find the string you're looking for. 

    You probably need to do the following, most likely, but you may need to stop your debugger on this line, and hunt for the data in another way.

    string curPort = ((DataViewRow)listBoxPort.SelectedItem)["SqlColumnNameGoesHere"].ToString();
    David Morton - http://blog.davemorton.net/
    • Marked as answer by NwTweety Wednesday, August 20, 2008 10:13 PM
    Wednesday, August 20, 2008 9:54 PM
    Moderator

All replies

  • System.Data.DataViewRow is a type in the .NET framework.  The default implementation of .ToString() with types is to return the type name.  So what you'll need to do is cast your SelectedItem to a DataViewRow, and drill down through your data to find the string you're looking for. 

    You probably need to do the following, most likely, but you may need to stop your debugger on this line, and hunt for the data in another way.

    string curPort = ((DataViewRow)listBoxPort.SelectedItem)["SqlColumnNameGoesHere"].ToString();
    David Morton - http://blog.davemorton.net/
    • Marked as answer by NwTweety Wednesday, August 20, 2008 10:13 PM
    Wednesday, August 20, 2008 9:54 PM
    Moderator
  • Dave,

    Thanks, that actually works. Especially after I corrected my question to show ‘DataRowView’ instead of ‘DataViewRow’. Now I almost understand the result I was getting.

    Your solution does the job.

    Thanks again,

    NWTweety

    Wednesday, August 20, 2008 10:13 PM