I am trying to add a value to listbox. i use lstlistbox.items.add(new listitem(value)).

this adds it fine in click event of button, but i need to use the selectedvalue of the listbox again in same event.

as the listbox item doesnt show i cant use selectedvalue. is there a way to first populate the listbox with its selected value then somehow use the value.


I'm sorry but I don't understand your problem.
Lets assume you have the below stated example, it adds a few items to the listbox and after a selection is done, it responds the selected value to the page.....

Is thát what you achieved?

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

            For iCnt As Integer = 1 To 5
                Dim lItem As New ListItem
                lItem.Text = String.Format("New Item {0}", iCnt.ToString)
                lItem.Value = iCnt
                lItem = Nothing
            Next iCnt
        End If
    End Sub

    Protected Sub ListBox1_SelectedIndexChanged( _
            ByVal sender As Object, _
            ByVal e As System.EventArgs) _
            Handles ListBox1.SelectedIndexChanged
        HttpContext.Current.Response.Write( _
             String.Format("Selected Value = {0}", _
             CType(sender, ListBox).SelectedValue.ToString))
    End Sub
End Class


<%@ Page 
    Inherits="_Default" %>
    html PUBLIC 
    "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
            AutoPostBack="True" />


Add the code code in your .aspx

<asp:DropDownList id="ddl1"  runat="server" AutoPostBack="True" AppendDataBoundItems="True"   >   
        <asp:ListItem Selected="True" Value="-1">--Select Me--</asp:ListItem>
        <asp:ListItem Value="1">Value 1</asp:ListItem>
        <asp:ListItem Value="2">Value 2</asp:ListItem>

And you can bind additional values at run time from database and can use selected

Private Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddl1.SelectedIndexChanged
your code 
    End Sub

Mark as solved if it helps you!!!


This article has been dead for over six months. Start a new discussion instead.