DropDownList显示SQL值

时间:2014-04-02 00:29:04

标签: asp.net sql

我已经使用SQL语句中的值填充了DropDownList,但它可以正常工作。

   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

问题是SQL列表以idt = 68开头,它在DropDownList中显示,但DropDownList1.DataTextField =“”而不是68以下。

     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 个答案:

答案 0 :(得分:1)

更新它以使用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()

答案 1 :(得分:0)

 DropDownList1.DataSource = ds.Tables(0)
 DropDownList1.DataTextField = "idt"
 DropDownList1.DataValueField = "idt"
 DropDownList1.DataBind();

您不需要选择" col1"专栏。因为你不能使用它。

然后

使用SelectedValue属性

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

答案 2 :(得分:0)

检查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. 

我想这会起作用

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