1

I have populated a DropDownList with values from an SQL statement and it works.

   Try
        cmdStr = "SELECT [idt],[col1] FROM [test];"
        Using conn As New SqlConnection(connStr)
            Using cmd As New SqlCommand(cmdStr, conn)
                conn.Open()
                cmd.ExecuteNonQuery()
                Using da As New SqlDataAdapter(cmd)
                    da.Fill(ds)
                    DropDownList1.DataSource = ds.Tables(0)
                    DropDownList1.DataTextField = "idt"
                    DropDownList1.DataValueField = "col1"
                    DropDownList1.DataBind()
                End Using
                cmd.Dispose()
                conn.Close()
                conn.Dispose()
            End Using
        End Using
    Catch ex As Exception
        TextBox1.Text = ex.Message
    End Try

The problem is the SQL list starts with idt=68 and it shows in the DropDownList as such but DropDownList1.DataTextField="" instead of 68 below.

     Try
        cmdStr = "SELECT [datetime],[col1],[col2],[col3] FROM [test] WHERE [idt]=@idt;"
        Using conn As New SqlConnection(connStr)
            Using cmd As New SqlCommand(cmdStr, conn)
                conn.Open()
                cmd.Parameters.AddWithValue("@idt", DropDownList1.DataTextField)
                cmd.ExecuteNonQuery()
      ...

3 Answers 3

1

update it to use DropDownList1.SelectedItem.Text

Try
        cmdStr = "SELECT [datetime],[col1],[col2],[col3] FROM [test] WHERE [idt]=@idt;"
        Using conn As New SqlConnection(connStr)
            Using cmd As New SqlCommand(cmdStr, conn)
                conn.Open()
                cmd.Parameters.AddWithValue("@idt", DropDownList1.SelectedItem.Text)
                cmd.ExecuteNonQuery()
0
 DropDownList1.DataSource = ds.Tables(0)
 DropDownList1.DataTextField = "idt"
 DropDownList1.DataValueField = "idt"
 DropDownList1.DataBind();

You don't need to select "col1" column . Because You don't use it.

Then

Use SelectedValue property

 cmd.Parameters.AddWithValue("@idt", DropDownList1.SelectedValue);
0

check your DataValueField,DataTextField

DataValueField=will be id for that field/id whenever your search or do any operation
DataTextField= text for that field/id to show on UI. 

i guess this would work

      DropDownList1.DataTextField = "col1"
      DropDownList1.DataValueField = "idt"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.