How can I access the value of the selected item in a dropdown?

I've got this code which works to populate a second dropdownlist based on what's in the first one (in the page's Page_Init event):

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    . . .
    'Populate the Units dropdown
    Dim unitsDT As DataTable
    sql = "Select distinct unit from masterunits where abs(active) = 1"
    retDS = sqlDAL.runSQLDataSet(sql)
    unitsDT = retDS.Tables(0)
    DropDownListUnits.DataSource = unitsDT
    DropDownListUnits.DataTextField = "unit"
    DropDownListUnits.DataValueField = "unit"
    DropDownListUnits.DataBind()

    'Populate the Members dropdown based on Unit selected
    'Dim selectedUnit As String = DropDownListUnits.Text
    Dim selectedUnit As String = DropDownListUnits.SelectedItem.Text
    Dim membersDT As DataTable
    sql = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit  + "' order by shortname"
    retDS = sqlDAL.runSQLDataSet(sql)
    membersDT = retDS.Tables(0)
    DropDownListMembers.DataSource = membersDT
    DropDownListMembers.DataTextField = "shortname"
    DropDownListMembers.DataValueField = "memberno"
    DropDownListMembers.DataBind()
    . . .
End Sub

...I need to also update the second dropdown any time the first one changes, so have this code:

Protected Sub DropDownListUnits_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListUnits.SelectedIndexChanged

DropDownListMembers.Items.Clear
    DropDownListCustomers.Items.Clear

    Dim selectedUnit As String = DropDownListUnits.SelectedItem.Text

    Dim sqlDAL As New SQLServer(ConfigurationSettings.AppSettings("ConnectionString"))
    Dim membersDT As DataTable
    Dim retDS As DataSet
    Dim sql As String = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit  + "' order by shortname"
    retDS = sqlDAL.runSQLDataSet(sql)
    membersDT = retDS.Tables(0)

    DropDownListMembers.DataSource = membersDT
    DropDownListMembers.DataTextField = "shortname"
    DropDownListMembers.DataValueField = "memberno"
    DropDownListMembers.DataBind()
End Sub

...but it doesn't work - selecting a different unit from DropDownListUnits does not change what is in DropDownListMembers.

Apparently this:

Dim selectedUnit As String = DropDownListUnits.SelectedItem.Text

...is not retrieving the new value selected from DropDownListUnits to selectedUnit.

I even added this, for debugging purposes:

Label2.Text = selectedUnit

...but Label2 never changes.

What am I doing wrong here?

UPDATE

Based on this, I also tried this:

Dim selectedUnit As String = DropDownListUnits.SelectedItem.ToString()

...but it makes no difference.

UPDATE 2

The event is apparently not even firing. This code:

Protected Sub DropDownListUnits_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListUnits.SelectedIndexChanged
        Label2.Text = "it fired"
        . . .

...shows no change to Label2's text...

UPDATE 3

When I tried this as the first line in the Page_Init event:

If Not IsPostBack Then Exit Sub

...it doesn't even run once.

I already had a similar thing in there:

Dim PageAlreadyInitted As Boolean = False

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If PageAlreadyInitted = True Then Exit Sub
    PageAlreadyInitted = True
    . . .

UPDATE 4

Based on the last comment, I tried this in the Page_Init:

If Page.IsPostBack = True Then Exit Sub

...and it makes no difference - I still get no result from the DropDownListUnits_SelectedIndexChanged event; it apparently is not fired as Label2 does not change to "it fired", as it should:

Protected Sub DropDownListUnits_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListUnits.SelectedIndexChanged
    Label2.Text = "it fired"

UPDATE 5

This is more messed up than Keith Richards' hair after he fell out of the coconut palm on his noggin: I try to access the value displaying in a dropdownlist, and it gives me the wrong value.

Here's the code to populate the dropdownlists:

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If PageAlreadyInitted = True Then Exit Sub
    If Page.IsPostBack = True Then Exit Sub
    PageAlreadyInitted = True

    Dim sqlDAL As New SQLServer(ConfigurationSettings.AppSettings("ConnectionString"))
    'Populate the Units dropdown
    Dim unitsDT As DataTable
    Dim sql As String = "Select distinct mu.unit from masterunits mu left join MasterUnitsProjSales mps on mps.Unit = mu.Unit where abs(active) = 1 and mps.NewBiz != 0 order by mu.unit"
    Dim retDS As DataSet = sqlDAL.runSQLDataSet(sql)
    unitsDT = retDS.Tables(0)
    DropDownListUnits.DataSource = unitsDT
    DropDownListUnits.DataTextField = "unit"
    DropDownListUnits.DataValueField = "unit"
    DropDownListUnits.DataBind()

    'Populate the Members dropdown - TODO: Call this when Unit changes, too
    Dim selectedUnit As String = DropDownListUnits.SelectedItem.Text
    Dim membersDT As DataTable
    sql = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit + "' order by shortname"
    retDS = sqlDAL.runSQLDataSet(sql)
    membersDT = retDS.Tables(0)
    DropDownListMembers.DataSource = membersDT
    DropDownListMembers.DataTextField = "shortname"
    DropDownListMembers.DataValueField = "memberno"
    DropDownListMembers.DataBind()

    'Populate the Customers dropdown - TODO: Call this when Member changes, too
    Dim selectedMember As String = DropDownListMembers.SelectedItem.Value
    Dim customersDT As DataTable
    sql = "select distinct companyname from customers C left join members M on M.MemberNo = C.MemberNo where M.MemberNo = '" + selectedMember + "' order by companyname"
    retDS = sqlDAL.runSQLDataSet(sql)
    customersDT = retDS.Tables(0)
    DropDownListCustomers.DataSource = customersDT
    DropDownListCustomers.DataTextField = "companyname"
    DropDownListCustomers.DataValueField = "companyname"
    DropDownListCustomers.DataBind()

    sqlDAL.Dispose()
End Sub

Here's what I see:

enter image description here

Note that "Applebees" is the unit displaying (I didn't select it - it is the first item in the collection, and displays by default).

Yet when I mash the button, the value stored in the database for Unit is "Abuelos" rather than "Applebees." Not only is this frustrating, it is also bizarre in the extreme, as "Abuelos" does not even exist in the collection of items:

enter image description here

Here's the code that's trying to get the value, for updating and inserting records in the database:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim connStr As String = "SERVER=PROSQL05;DATABASE=cpsdata;UID=sa;PWD=sqlsql"
    Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Existing', EndDate = @DateTimeYesterday, ChangedOn = @CurrentDateTime WHERE Unit = @Unit And MemberNo = @MemberNo AND Custno = @CustNo"
    Dim insertDML As String = "INSERT INTO CustomerCategoryLog (MemberNo, Unit, Custno, Category, Subcategory, BeginDate, ChangedBy, ChangedOn) VALUES (@MemberNo_Insert, @Unit_Insert, @CustNo_Insert, @Category, @Subcategory, @BeginDate, @ChangedBy, @ChangedOn)"

    Dim coName As String
    Dim argVals(2) As String
    Dim _Unit As String
    Dim _MemberNo As String
    Dim _CustNo As String

    coName = DropDownListCustomers.SelectedItem.ToString()
    argVals = GetArgValsForCompanyName(coName)
    _Unit = argVals(0)
    _MemberNo = argVals(1)
    _CustNo = argVals(2)
    Using conn As New SqlConnection(connStr), _
            cmd As New SqlCommand(upd8DML, conn)
        cmd.Parameters.Add("@Unit", SqlDbType.VarChar, 50).Value = _Unit
        cmd.Parameters.Add("@MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
        cmd.Parameters.Add("@CustNo", SqlDbType.VarChar, 50).Value = _CustNo
        cmd.Parameters.Add("@DateTimeYesterday", SqlDbType.DateTime).Value = DateTime.Today.AddDays(-1)
        cmd.Parameters.Add("@CurrentDateTime", SqlDbType.DateTime).Value = Date.Now
        conn.Open()
        cmd.ExecuteScalar()
    End Using
    ' Now insert a new record with "Existing" categories and Now as the BeginDate
    Using conn As New SqlConnection(connStr), _
            cmd As New SqlCommand(insertDML, conn)
        cmd.Parameters.Add("@MemberNo_Insert", SqlDbType.VarChar, 50).Value = _MemberNo
        cmd.Parameters.Add("@Unit_Insert", SqlDbType.VarChar, 50).Value = _Unit
        cmd.Parameters.Add("@CustNo_Insert", SqlDbType.VarChar, 50).Value = _CustNo
        cmd.Parameters.Add("@Category", SqlDbType.VarChar, 50).Value = "Existing"
        cmd.Parameters.Add("@Subcategory", SqlDbType.VarChar, 50).Value = "Existing"
        cmd.Parameters.Add("@BeginDate", SqlDbType.DateTime).Value = DateTime.Today
        cmd.Parameters.Add("@ChangedBy", SqlDbType.VarChar, 50).Value = Environment.UserName
        cmd.Parameters.Add("@ChangedOn", SqlDbType.DateTime).Value = Date.Now
        conn.Open()
        cmd.ExecuteScalar()
    End Using
End Sub

Here's what's inserted and updated in the database:

enter image description here

So as you can see, "Abuelos" is the Unit value, although it should be "Applebees" - what the Hec Ramsey !?!

Upvotes: 3

Views: 845

Answers (2)

This actually does work, apparently:

_Unit = DropDownListUnits.SelectedItem.ToString() 
_MemberNo = DropDownListMembers.SelectedValue.ToString()
_CustNo = DropDownListCustomers.SelectedValue.ToString()

The records are being updated/inserted with those values. In more context:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim connStr As String = "SERVER=PROSQL05;DATABASE=cpsdata;UID=sa;PWD=sqlsql"
    Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Existing', EndDate = @DateTimeYesterday, 

ChangedOn = @CurrentDateTime WHERE Unit = @Unit And MemberNo = @MemberNo AND Custno = @CustNo" Dim insertDML As String = "INSERT INTO CustomerCategoryLog (MemberNo, Unit, Custno, Category, Subcategory, BeginDate, ChangedBy, ChangedOn) VALUES (@MemberNo_Insert, @Unit_Insert, @CustNo_Insert, @Category, @Subcategory, @BeginDate, @ChangedBy, @ChangedOn)"

    Dim _Unit As String
    Dim _MemberNo As String
    Dim _CustNo As String

    _Unit = DropDownListUnits.SelectedItem.ToString() 
    _MemberNo = DropDownListMembers.SelectedValue.ToString()
    _CustNo = DropDownListCustomers.SelectedValue.ToString()
    Using conn As New SqlConnection(connStr), _
            cmd As New SqlCommand(upd8DML, conn)
        cmd.Parameters.Add("@Unit", SqlDbType.VarChar, 50).Value = _Unit
        cmd.Parameters.Add("@MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
        cmd.Parameters.Add("@CustNo", SqlDbType.VarChar, 50).Value = _CustNo
        cmd.Parameters.Add("@DateTimeYesterday", SqlDbType.DateTime).Value = DateTime.Today.AddDays(-1)
        cmd.Parameters.Add("@CurrentDateTime", SqlDbType.DateTime).Value = Date.Now
        conn.Open()
        cmd.ExecuteScalar()
    End Using
    ' Now insert a new record with "Existing" categories and Now as the BeginDate
    Using conn As New SqlConnection(connStr), _
            cmd As New SqlCommand(insertDML, conn)
        cmd.Parameters.Add("@MemberNo_Insert", SqlDbType.VarChar, 50).Value = _MemberNo
        cmd.Parameters.Add("@Unit_Insert", SqlDbType.VarChar, 50).Value = _Unit
        cmd.Parameters.Add("@CustNo_Insert", SqlDbType.VarChar, 50).Value = _CustNo
        cmd.Parameters.Add("@Category", SqlDbType.VarChar, 50).Value = "Existing"
        cmd.Parameters.Add("@Subcategory", SqlDbType.VarChar, 50).Value = "Existing"
        cmd.Parameters.Add("@BeginDate", SqlDbType.DateTime).Value = DateTime.Today
        cmd.Parameters.Add("@ChangedBy", SqlDbType.VarChar, 50).Value = Environment.UserName
        cmd.Parameters.Add("@ChangedOn", SqlDbType.DateTime).Value = Date.Now
        conn.Open()
        cmd.ExecuteScalar()
    End Using
End Sub

so, getting the displayed value like so:

_Unit = DropDownListUnits.SelectedItem.ToString() 

...and the data values like so:

_MemberNo = DropDownListMembers.SelectedValue.ToString()
_CustNo = DropDownListCustomers.SelectedValue.ToString()

...does work.

I still (different question) cannot get the second and third dropdownlists to repopulate based on the value of the first one when it changes, though...

Upvotes: 3

Win
Win

Reputation: 62290

You need to fill DropDownListUnits only at initial page load by using If Not IsPostBack. Otherwise, DropDownListUnits is populated with new data on postback, and losts the selected value.

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   If Not IsPostBack
    . . .
    'Populate the Units dropdown
    Dim unitsDT As DataTable
    sql = "Select distinct unit from masterunits where abs(active) = 1"
    retDS = sqlDAL.runSQLDataSet(sql)
    unitsDT = retDS.Tables(0)
    DropDownListUnits.DataSource = unitsDT
    DropDownListUnits.DataTextField = "unit"
    DropDownListUnits.DataValueField = "unit"
    DropDownListUnits.DataBind()
        . . .

   End If
End Sub

Protected Sub DropDownListUnits_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListUnits.SelectedIndexChanged

    DropDownListMembers.Items.Clear
    DropDownListCustomers.Items.Clear

    Dim selectedUnit As String = DropDownListUnits.SelectedValue
                                                         ^^^^^^

    Dim sqlDAL As New SQLServer(ConfigurationSettings.AppSettings("ConnectionString"))
    Dim membersDT As DataTable
    Dim retDS As DataSet
    Dim sql As String = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit  + "' order by shortname"
    retDS = sqlDAL.runSQLDataSet(sql)
    membersDT = retDS.Tables(0)

    DropDownListMembers.DataSource = membersDT
    DropDownListMembers.DataTextField = "shortname"
    DropDownListMembers.DataValueField = "memberno"
    DropDownListMembers.DataBind()
End Sub

Upvotes: 2

Related Questions