简体   繁体   中英

SQL Query to SQL DataSource

I have created this query but I dont know how to bind it to a sqldatasource so I can create a datalist, can someone please help me?

    Dim cn As SqlConnection = New SqlConnection()
    Dim cmd As SqlCommand = New SqlCommand()
    Dim dr As SqlDataReader

    If Session("Email") <> "" Then
        cn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
        cmd.Connection = cn
        cmd.CommandText = "Select Name From [Games] Where Platform = @Platform AND Genre = @Genre AND Age >= @Age"

        Dim Platform As New SqlParameter("@Platform", SqlDbType.VarChar, 20)
        Platform.Value = ddlPlatform.SelectedItem.ToString()
        cmd.Parameters.Add(Platform)

        Dim Genre As New SqlParameter("@Platform", SqlDbType.VarChar, 20)
        Genre.Value = ddlgenre.SelectedItem.ToString()
        cmd.Parameters.Add(Genre)

        Dim Age As New SqlParameter("@Age", SqlDbType.Int)
        Age.Value = txtAge.Text.ToString()
        cmd.Parameters.Add(Age)

        'Open the connection to the database
        cn.Open()
        ' Execute the sql.
        dr = cmd.ExecuteReader()`

Thanks to Vignesh I have been able to answer this question.

     Dim cn As SqlConnection = New SqlConnection()
    Dim cmd As SqlCommand = New SqlCommand()
    cn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
    cmd.Connection = cn
    cmd.CommandText = "Select Name, Platform, Genre, Age_Range From [Games] Where (Platform = @Platform) and (Genre = @Genre) and (Age_Range <= @Age)"

    Dim Platform As New SqlParameter("@Platform", SqlDbType.VarChar, 20)
    Platform.Value = ddlPlatform.SelectedItem.ToString()
    cmd.Parameters.Add(Platform)

    Dim Genre As New SqlParameter("@Genre", SqlDbType.VarChar, 20)
    Genre.Value = ddlgenre.SelectedItem.ToString()
    cmd.Parameters.Add(Genre)

    Dim Age As New SqlParameter("@Age", SqlDbType.VarChar, 20)
    Age.Value = txtAge.Text
    cmd.Parameters.Add(Age)

    cn.Open()
    Dim ds As SqlDataReader
    ds = cmd.ExecuteReader()
    MyDatalist.DataSource = ds
    MyDatalist.DataBind()
    cn.Close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM