Google Answers Logo
View Question
 
Q: DropDown Lists in a Visual Studio Web Application ( Answered 5 out of 5 stars,   0 Comments )
Question  
Subject: DropDown Lists in a Visual Studio Web Application
Category: Computers > Programming
Asked by: homebuilder-ga
List Price: $20.00
Posted: 26 Feb 2003 18:41 PST
Expires: 28 Mar 2003 18:41 PST
Question ID: 167637
I am coding in VB using Visual Studio .NET and can fill a dropdown
list from as SQL Server2000 Database with the following code:
'fill listbox with all communities  
            Me.SqlConnection1.Open()
            ddlCommunity.DataSource =
cmdCommunities.ExecuteReader(CommandBehavior.CloseConnection)
            ddlCommunity.DataTextField = "CommunityName"
            ddlCommunity.DataValueField = "CommunityID"
            ddlCommunity.DataBind()
            Me.SqlConnection1.Close()
The selection is then saved to a seperate table using:
With cmdUpdateCommunity
                .Parameters("@CustomerID").Value = intCustomerID
                .Parameters("@CommunityID").Value =
ddlCommunity.SelectedItem.Value
            End With
            Me.SqlConnection1.Open()
            Me.cmdUpdateCommunity.ExecuteNonQuery()
            Me.SqlConnection1.Close()

The problem that I'm having is on returning to this form after a
selection has been made the dropdown list fills and shows the first
item in the table, however what I'm wanting is the previously selected
item to be shown in the box.

I think this is acomplished by identifying the selectedindex but am
lost how to code this in VB .NET

Can anyone help?
Thanks
Peter
Answer  
Subject: Re: DropDown Lists in a Visual Studio Web Application
Answered By: cerebrate-ga on 26 Feb 2003 23:00 PST
Rated:5 out of 5 stars
 
Dear homebuilder-ga,

Yes, what you want is indeed the SelectedIndex - essentially, you need
to capture it when a selection is made from the drop-down list, and
store it for use when the browser comes back to the page; and when the
page loads, check to see if you have a stored selection, and set the
list box to that. The easiest place to store the current selection is
in the session state for your web application.

Here's how it's done:

First, set the "AutoPostBack" property of your drop-down list to
"true". This ensures that the user's selection will be sent back to
the web server so that you'll be able to capture it.

Then, add the following code to the SelectedIndexChanged event of your
drop-down list:

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object,
ByVal e As System.EventArgs) Handles
DropDownList1.SelectedIndexChanged
    Session.Add("listValue", DropDownList1.SelectedIndex)
End Sub

(Change DropDownList1 to the name of your specific drop-down list, and
listValue to something unique in your application, of course.)

And add the following code to the Page_Load event of your web form,
after
the code which populates the drop-down list:

Dim Index As Int32

' Only do this if the page is being loaded from another page, not
' from itself. Important, otherwise we wouldn't be able to change
' the value at all.
If Not Me.IsPostBack Then
    Index = Session.Item("listValue")
    ' To avoid throwing an exception, check that the number of items
in
    ' the list hasn't shrunk since we were last on this page. Don't
set
    ' the index if it would now fall off the end.
    If (Index < DropDownList1.Items.Count) Then
        DropDownList1.SelectedIndex = Index
    End If
End If

(Making the same changes as above.)

And that should now work!

The drawback with this method is that it only stores the index of the
selected item - thus, if you delete an item from the drop-down - in
your case, from your database - or the order they're returned in
changes, the indices of every item in the drop-down list changes, and
you'll end up with the wrong one being shown when you come back to the
page.

There's a way to get around this by using the SelectedValue property,
which stores the value by name. To use this method, follow the above
method, but substitute the following code:

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object,
ByVal e As System.EventArgs) Handles
DropDownList1.SelectedIndexChanged
        Session.Add("listValue", DropDownList1.SelectedValue)
End Sub

and:

Dim Value As String

' Only do this if the page is being loaded from another page, not
' from itself. Important, otherwise we wouldn't be able to change
' the value at all.
If Not Me.IsPostBack Then
    Value = Session.Item("listValue")
    ' ArgumentOutOfRangeException will be thrown if the value no
longer
    ' exists.
    Try
        DropDownList1.SelectedValue = Value
    Catch ex As ArgumentOutOfRangeException
        ' Ignore this exception - it just means value no longer
exists.
        ' Go with default value.
    End Try
End If

And that should again work for you.

If this answer isn't quite what you're looking for, please feel free
to request a clarification,

cerebrate-ga

Request for Answer Clarification by homebuilder-ga on 27 Feb 2003 07:21 PST
The second method looked good to me as the value is being stored in a
database so instead of using your suggestion to use the session state
to store the selected value I can just recapture the value from the
database, however I tried the line: DropDownList1.SelectedValue =
Value (after storing the previously selected value to the variable)
and I get an error due to the fact that SelectedValue is not an
option. I only have the choice of SelectedIndex or SelectedItem. I
tried SelectedItem but this does not work and SelectedIndex is
expecting an interger not a string (Value being a string).

Your first choice the SelectedIndex will not for me due to the list
changing as you mentioned.

I also tried adding this line after the list fills: 

ddlCommunity.SelectedIndex = 3

but when running the page the first Item in the database stil appears
in the dropdown list box????????

any Ideas?

Request for Answer Clarification by homebuilder-ga on 27 Feb 2003 07:28 PST
Correction!
 
ddlCommunity.SelectedIndex = 3 
 
does work but this is not what I need.

Clarification of Answer by cerebrate-ga on 27 Feb 2003 08:11 PST
Dear homebuilder-ga,

I've just double-checked, and I think I see the problem; the
SelectedValue property was added in release 1.1 of the .NET framework
- if you're using 1.0, it won't be present. Sorry about that.

However, there's a slightly longer way of expressing the same thing
which should hopefully work for you. Instead of saving the value, save
the list item itself in the SelectedIndexChanged event:

Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object,
ByVal e As System.EventArgs) Handles
DropDownList1.SelectedIndexChanged
    Session.Add("listItem", DropDownList1.SelectedItem)
End Sub

and in the Page_Load event, we look up the index of that particular
item, and then set SelectedIndex to that index, thus:

If Not Me.IsPostBack Then
    Item = Session.Item("listItem")

    Dim index As Int32
    ' Find the index of the list item we saved
    index = DropDownList1.Items.IndexOf(Item)
    If (index <> -1) Then
        ' If the item is still in the list, set it selected
        DropDownList1.SelectedIndex = index
    End If
End If

I've used the session state here, again, but you should be able to
swap your database code in here without any trouble.

And hopefully that should work!

cerebrate-ga

Request for Answer Clarification by homebuilder-ga on 27 Feb 2003 11:12 PST
I decided to upgrade to the .NET Framework ver 1.1 but after
downloading and installing I still do not have the SelectedValue
property.

I checked in Help About Visual Studio and it say I still have ver 1.0

is this just a bug or could it be that I installed it withought
installing the 1.1 redistribuatable pack first. I tried Re-installing
after installing th redistributable and it doesnt change anything? Do
you think I should un-install and then re-install 1.1 SDK or can you
think of something else I'm doing wrong.

Clarification of Answer by cerebrate-ga on 27 Feb 2003 11:42 PST
Dear homebuilder-ga,

Unfortunately, Visual Studio itself is tied to a particular version of
the .NET framework (per
http://msdn.microsoft.com/netframework/productinfo/versioncomparison/default.asp
) - the current "release" version of Visual Studio will always compile
against the 1.0 framework, needing the different code I mentioned.

I'm afraid I happened to come up initially with a solution for the 1.1
version of the framework because I happen to be in the beta programme
for the next Visual Studio.NET version, and so that's what I have
installed. To compile against the 1.1 framework you'd either need a
copy of that beta, or to use the command-line compiler in the SDK
rather than Visual Studio.

I must apologise for leading you on this wild-goose chase; I'm afraid
I didn't realise to begin with that SelectedValue wasn't present in
the 1.0 framework. I'm sorry to have wasted your time with it.

Regards,

cerebrate-ga

Request for Answer Clarification by homebuilder-ga on 27 Feb 2003 12:37 PST
No need to appologise I appreciate all the help.

The reason I liked your first answer so much was that I already have
the SelectedValue stored in the Database and it would have ben far
easier to find the item in the dropdown list using that value
(probably why Microsoft added that feature in  1.1), however I was
thinking (very dangerous)is there a way to loop through the values in
the dropdown inorder to find the match for the previously selected
item an then when the match is located store the SelectedIndex for
that item to a variable.

In your last solution I would have to store the SelectedItem (I'm not
sure what this relates to)I think thiis relates to the text displayed
in the dropdown box.

Clarification of Answer by cerebrate-ga on 27 Feb 2003 21:36 PST
Dear homebuilder-ga,

Yes, that should also be possible. In fact, you don't even need to
loop, as the ListItemsCollection supplies a FindByValue method to let
you do exactly this.

The code you would need in Page.Load is (where previousValue is a
variable containing the value from your database):

If Not Me.IsPostBack Then
    Dim item As ListItem

    ' Find the ListItem with the value from the database
    item = DropDownList1.Items.FindByValue (previousValue)

    If Not (item Is Nothing) Then
        ' If it exists, set SelectedIndex to its index
        DropDownList1.SelectedIndex =
DropDownList1.Items.IndexOf(item)
    End If
End If 

(To clarify the previous one, SelectedItem is the currently selected
ListItem, which is the object used internally by the DropDownList to
manage its items (it contains a few other properties apart from the
value itself) - when you call Add with a string, it creates one for
you with sensible defaults. It's probably the most useful thing to
store in 1.0 to avoid problems with the list changing, except when, as
here, you have the information stored elsewhere anyway...)

Regards,

cerebrate-ga
homebuilder-ga rated this answer:5 out of 5 stars
****Fantastic***** Thanks so much for the help. It works great.

Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy