help sorting an asp.net listbox with up and down buttons using vb.net

Hi Experts,

I need some help with something that has been causing me a problem for a few days now.

I am populating an asp.net listbox from a database table using "objRdr = objCmd.ExecuteReader()". This bit works fine.

Now I need to allow a visitor to the web page to sort the listbox using up and down arrows and send the sorted data to another table.

I have found several chunks of code to achieve this but all of them have failed (depite them apparently working for other people). I'm quite new to asp.net so it is possible I'm not applying the code correctly.

The most recent error message:  
.......................................................................................................
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30311: Value of type 'System.Web.UI.WebControls.ListItem' cannot be converted to 'String'.

Source Error:

 

Line 139:
Line 140:        If league.SelectedIndex > 0 Then
Line 141:            TextToMove = league.SelectedItem
Line 142:            CurrentIndex = league.SelectedIndex
Line 143:

..........................................................................................................

The sub:

..........................................................................................................

Public Sub MoveUp()
        Dim TextToMove As String
        Dim CurrentIndex As Integer

        If league.SelectedIndex > 0 Then
            TextToMove = league.SelectedItem
            CurrentIndex = league.SelectedIndex

            league.Items.RemoveAt(CurrentIndex)
            league.Items.Insert(CurrentIndex - 1, TextToMove)

            league.SelectedIndex = CurrentIndex - 1
        End If
    End Sub

    Public Sub MoveDown()
        Dim TextToMove As String
        Dim CurrentIndex As Integer

        If league.SelectedIndex < league.Items.Count - 1 Then
            TextToMove = league.SelectedItem
            CurrentIndex = league.SelectedIndex

            league.Items.RemoveAt(CurrentIndex)
            league.Items.Insert(CurrentIndex + 1, TextToMove)

            league.SelectedIndex = CurrentIndex + 1
        End If
    End Sub
............................................................................................................................

The listbox:
............................................................................................................................

<asp:ListBox id="league" runat="server" BackColor="White" Rows="20" DataTextFormatString="" DataTextField="30" DataMember="30" width="150"></asp:ListBox><br>
     <asp:button Text="UP" Tooltip="To remove an item, select and then click this button" OnClick="MoveUp" runat="server" />
     <asp:button Text="DOWN" Tooltip="To remove an item, select and then click this button" OnClick="MoveDown" runat="server" />

...........................................................................................................................

Hopefully someone out there can help.

Thanks.



ajd07Asked:
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.

martie_11Commented:
Line 141:            TextToMove = league.SelectedItem

'league.SelectedItem' is of type 'Object'.  I'm assuming that 'TextToMove' is a string.  So, the following should do it:

TextToMove = league.SelectedItem.Text
martie_11Commented:
Sorry, league.SelectedItem if of type 'ListItem' and not 'Object'... nonetheless, the above should do it.
ajd07Author Commented:
Thanks Martie 11,

Your suggestion has got me half the way there as the page now renders in the browser.

However when I select a list item and click on the 'up' button the page refreshes but the item does not move up the list.

When I do the same but with the down button I get the following error message:

..........................................................................................

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 154:
Line 155:        If league.SelectedIndex < league.Items.Count - 1 Then
Line 156:            TextToMove = league.SelectedItem.Text
Line 157:            CurrentIndex = league.SelectedIndex

.............................................................................................

I wondered if it might be because the content of the listbox is dynamically generated from a sql database and so I recreated the page but this time just hard coded in 3 list items instead of requesting anything from the database. This time the code DID WORK.

So of course I am wondering what I can do to make this code work with the database generated listbox which is populated via the following code:

objCmd = New SqlCommand("getLeagueTeamsAlpha2", objConn)
 objCmd.CommandType = CommandType.StoredProcedure
 objRdr = objCmd.ExecuteReader()
 league.DataSource = objRdr
 league.DataValueField = "LETE_START_POSITION"
 league.DataTextField = "LETE_DESCRIPTION"
 league.DataBind()
 objRdr.Close()

In other words, can the code that you initially commented on physically work with a listbox who's list items are generated from a database as above?

Look forward to hearing your thoughts.

Thanks.

 
Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

martie_11Commented:
Where do you populate the list box?  Is it in the Page_Onload?  Can you paste the entire method where you load the drop down?
ajd07Author Commented:
Yes, here's the page load (see "getLeagueTeamsAlpha2" for populating the list box)
................................................................................................................
<script runat="server" language="VB">
 Sub Page_Load()
 Dim connectionString as String
 connectionString = ConfigurationSettings.AppSettings("ConnectionString")
 Dim objConn As New SqlConnection (connectionString)
 Dim objCmd As SqlCommand
 Dim objRdr As SqlDataReader
 

 objConn.Open()
 
 
 objCmd = New SqlCommand("getPlayerTitle", objConn)
 objCmd.CommandType = CommandType.StoredProcedure
 objRdr = objCmd.ExecuteReader()
 title_type.DataSource = objRdr
 title_type.DataValueField = "TITY_TITLE_TYPE"
 title_type.DataTextField = "TITY_DESCRIPTION"
 title_type.DataBind()
 objRdr.Close()
 
 objCmd = New SqlCommand("getPlayerSource", objConn)
 objCmd.CommandType = CommandType.StoredProcedure
 objRdr = objCmd.ExecuteReader()
 player_source.DataSource = objRdr
 player_source.DataValueField = "PLSO_PLAYER_SOURCE"
 player_source.DataTextField = "PLSO_DESCRIPTION"
 player_source.DataBind()
 objRdr.Close()
 
 objCmd = New SqlCommand("getLeagueTeamsAlpha2", objConn)
 objCmd.CommandType = CommandType.StoredProcedure
 objRdr = objCmd.ExecuteReader()
 league.DataSource = objRdr
 league.DataValueField = "LETE_START_POSITION"
 league.DataTextField = "LETE_DESCRIPTION"
 league.DataBind()
 objRdr.Close()
 
 objConn.Close()
End Sub
..............................................................................................

And here's the listbox in question:

.............................................................................................

<asp:ListBox id="league" runat="server" BackColor="White" Rows="20" DataTextFormatString="" DataTextField="30" DataMember="30" width="150"></asp:ListBox><br>
     <asp:button Text="UP" Tooltip="To remove an item, select and then click this button" OnClick="MoveUp" runat="server" />
     <asp:button Text="DOWN" Tooltip="To remove an item, select and then click this button" OnClick="MoveDown" runat="server" />

...............................................................................................

Perhaps it would be better to use a DataSet for this functionality, which is essentially to allow the user to sort 20 records into their preferred order and send the new order to a different table in one go (ie one insert action)? (have increased the points for this to 350 to reflect this additional question).

Look forward to hearing from you.

martie_11Commented:
W.r.t using a dataset, it would be easier.

In fact, you can sort using the .NET framework using a dataview.  Here is an example:

   ' Get the DefaultViewManager of a DataTable.
   Dim myDataView As DataView
   Dim myDataSet As DataSet

   myDataSet = ....
   'populate dataset

   myDataView = myDataSet.Tables(0).DefaultView
   ' By default, the first column sorted ascending.
   myDataView.Sort = "LETE_START_POSITION DESC"      'or "LETE_START_POSITION" for ascending
   league.DataSource = myDataView
 
...hope that helps
ajd07Author Commented:
That is interesting. The real thrust in terms of functionality is allowing the user to view 20 records from a database and sort them into their preferred order of priority (hence the need for up and down buttons). Then once the user has finished sorting the records they can hit the 'update' button  and the records are submitted to the database in the sorted order.

Any thoughts on how best to achieve this?

Thanks.
martie_11Commented:
To move items up / down:

private void btnUp_Click(object sender, System.EventArgs e)
{
     // get selected item of list
     ListItem li = lbItems.SelectedItem;
        if (li == null)
          return;
     int index = lbItems.SelectedIndex;
     // first item cannot be moved up
     if (index <= 0)
          return;
     else
     {
          // swap two items
          lbItems.Items.RemoveAt(index);
          lbItems.Items.Insert(index - 1, li);
     }
}

private void btnDown_Click(object sender, System.EventArgs e)
{
     // get selected item of list
     ListItem li = lbItems.SelectedItem;
        if (li == null)
          return;
     int index = lbItems.SelectedIndex;
     // last item cannot be moved down
     if (index >= lbItems.Items.Count - 1)
          return;
     else
     {
          // swap two items
          lbItems.Items.RemoveAt(index);
          lbItems.Items.Insert(index + 1, li);
     }
}

That's C# code above.  Now when a user is done, he/she would click 'update' or 'submit'.  On the 'update/submit' you would read back the items in the list box and then update your database.

...hope that helps.
ajd07Author Commented:
Thanks for that. I'd like to try that code out on my page. Is it technically possible to use C# code on a page which is currently utilising VB.NET and if so are there any special declarations or anything I need to add to the page for two ASP.NET languages to be utilised on the same page?

Thanks again for your valuable input.

martie_11Commented:
You can mix VB.NET code and C#...but this is not the right time / place.  If there was an external module that was in C# that your VB.NET code needed to tap into, then it's a worthwhile effort.  In this case however, you need to convert it to VB.NET.  There are some converters available online that convert C# code to VB.NET as they are very similar.  Perhaps you could try those.

I'm not a VB.NET coder myself; sorry.

You can always post that code on EE for a few points (50? 100?) to have it converted.

...wish I could be of more help.

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
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
ASP.NET

From novice to tech pro — start learning today.