p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   ASP.NET 1.0 and 1.1 Professional (http://p2p.wrox.com/forumdisplay.php?f=57)
-   -   Selecting an Item from a databound listbox (http://p2p.wrox.com/showthread.php?t=13409)

nyclimber May 25th, 2004 01:38 PM

Selecting an Item from a databound listbox
I have created a web page (using web matrix) that contains a listbox (of city names) that is bound to a datatable. I then want to be able to pre-select a city name as the default (see code below).

It appears that the databind() function does not fully let go of the listbox control on page_load(). Even when I place my selection code in page_prerender(), I am unable to default to the city name.

As a test, I manually loaded the listbox and the code worked fine and I was able to default to the city name.

Any ideas?

Thank you in advance.

<%@ Page Language="VB" smartnavigation="True" autoeventwireup="False" Inherits="System.Web.UI.Page" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Web.UI" %>
<%@ import Namespace="System.Web.UI.Page" %>
<%@ import Namespace="System.Web.UI.WebControls" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server">

         Dim adoDtCity As New DataTable

         Public Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            '// Load listbox with static values
                'lstCity.Items.Add(New ListItem("Amlin", 1))
                'lstCity.Items.Add(New ListItem("Bexley", 2))
                'lstCity.Items.Add(New ListItem("Blacklick", 3))
                'lstCity.Items.Add(New ListItem("Canal Winchester", 4))
                'lstCity.Items.Add(New ListItem("Columbus", 5))
                'lstCity.Items.Add(New ListItem("Dublin", 6))
                'lstCity.Items.Add(New ListItem("Gahanna", 7))
                'lstCity.Items.Add(New ListItem("Galloway", 8))

            '// Load listbox from database
                adoDtCity = GetCityTbl()
                lstCity.DataSource = adoDtCity
                lstCity.DataTextField = "name"
         End Sub

         Public Sub Page_PreRender(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
                lstCity.SelectedIndex = lstCity.Items.IndexOf(lstCity.Items.FindByText("Co lumbus"))
         End Sub

         Public Function GetCityTbl() As DataTable
             Dim adoCn As SqlConnection
             Dim adoCd As SqlCommand
             Dim adoDr As SqlDataReader
             Dim adoDt As New DataTable()
             Dim adoParm As SqlParameter
             Dim adoRow As DataRow

                 adoDt.Columns.Add("city_id", System.Type.GetType("System.String"))
                 adoDt.Columns.Add("name", System.Type.GetType("System.String"))

                 adoCn = New SqlConnection(ConfigurationSettings.AppSettings("S QL_LOGIN"))
                 adoCd = New SqlCommand(ConfigurationSettings.AppSettings("spAl lCity"), adoCn)
                 adoCd.CommandType = CommandType.StoredProcedure
                 adoParm = adoCd.Parameters.Add(New SqlParameter("@PgmID", SqlDbType.VarChar, 4))
                 adoParm.Direction = ParameterDirection.Input
                 adoParm.Value = ConfigurationSettings.AppSettings("PGM")
                 adoDr = adoCd.ExecuteReader(CommandBehavior.CloseConnectio n)

                 While adoDr.Read
                     adoRow = adoDt.NewRow()
                     adoRow(0) = adoDr("city_id")
                     adoRow(1) = adoDr("name")
                 End While
                 'Error handling goes here
             End Try

             Return adoDt
         End Function

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR" />
    <meta content="Visual Basic 7.0" name="CODE_LANGUAGE" />
    <meta content="JavaScript" name="vs_defaultClientScript" />
    <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema" />
    <link href="Includes/cnas.css" rel="stylesheet" />
    <script language="javascript" src="Includes/inc_cmn_pg.js"></script>
    <form id="Intake" method="post" runat="server">
        <div id="contentstart" style="HEIGHT: 100px">
            <table cellspacing="0" cellpadding="0" width="760" border="0">
                            <asp:ListBox id="lstCity" runat="server" rows="1" Font-Size="Smaller" Font-Names="Arial"></asp:ListBox>
        <asp:Label id="lblMsg" runat="server"></asp:Label>

bmains May 25th, 2004 01:52 PM


lstCity.SelectedItem = lstCity.Items.FindByText("Columbus")

I tested out on a web form and I can access a property of a control in the prerender event, that is the only thing I can think of, but I'm sure I'm missing something...


nyclimber May 25th, 2004 02:26 PM

Thanks for the suggestion, but I think 'SelectedItem' is a read-only property and therefore could not be set.

A recent note, even if I change the one line of code in the Page_PreRender() function to:

     lstCity.SelectedIndex = 4

(this will explicitly tell the listbox to display the fourth element in the listbox)

It still will not work correctly for a listbox loaded with a databind(), but will for the listbox loaded programmatically with Items.Add().

Question: Do I need to explicitly set sequential values for:

     lstCity.DataTextValue = <Index (ie. 1,2,3...>

Could it be that I am unable to set the listbox to display a specified default city is because there is no value associated with the DataTextField assigned in the bind?

I'll look into that next. Any suggestions would be helpful?

Thanks again.

nyclimber May 25th, 2004 02:59 PM

I need to correct my previous statement:

Where I said, "...I change the one line of code in the Page_PreRender() function to:

     lstCity.SelectedIndex = 4

(this will explicitly tell the listbox to display the fourth element in the listbox)

It still will not work correctly for a listbox loaded with a databind(), but will for the listbox loaded programmatically with Items.Add()."

This is incorrect. It DOES work, and works correctly for both the listbox loaded through the databind() and programmatically with Items.Add().

The original code for the Page_PreRender() function still does not work for the the listbox loaded using the databind().

The listbox seems to automatically assign an index value for each of the items within the listbox. This would explain why "lstCity.SelectedIndex = 4" works.

Am I missing a namespace? It seems like this should be pretty straight-forward.

Thanks for listening to my ramblings.

bmains May 25th, 2004 03:24 PM


Sorry about the SelectedItem, I forgot about that. Anyways, another thing you can try is setting the DataValueField to either the city_id or the name property, and reference lstCity.SelectedValue = "value". Like you had said, that may be the problem.

It does assign an index value, starting at zero. So when you did lstCity.SelectedIndex = 4, it referenced the 5th item. You don't set the sequential values for DataTextField and DataValueField (although it may work; I don't know).

It seems straightforward to me... In addition, maybe you want to try to move the statement from the PreRender event to the Load event? Don't know if that will help.


All times are GMT -4. The time now is 01:02 AM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.