can you help me assign sql query to gridview..i am trying like this but it doesnt work.

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim con As New SqlConnection("Data Source=SPERANZA\SQLEXPRESS;initial catalog=master;integrated security=true")
        Dim cmd As New SqlCommand
        Dim dr As SqlDataReader
        cmd.Connection = con
        con.Open()
        cmd.CommandText = "SELECT name,dob,sex FROM users WHERE name LIKE ('%' + @name + '%')"
        cmd.Parameters.AddWithValue("@name", txtname.Text)
        dr = cmd.ExecuteReader()
        GridView1.DataSource = dr
        con.Close()
    End Sub

and code in aspx file

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="176px"  Width="598px">
                <Columns>
                <asp:TemplateField>
                <ItemTemplate>
                <%#Eval("name")%><br />
                <%#Eval("dob")%><br />
                <%#Eval("sex") %><br />
                </ItemTemplate>
                </asp:TemplateField>
                </Columns>
</asp:GridView>

The only thing you are missing is that you should bind the gridview to its data source. after the set of the data source and before closing the connection write this.

GridView1.Databind()

and don't forget to close the data reader ;)

Try
Dim ObjSqlDataAdapter As SqlDataAdapter
Dim ObjDataSet As New DataSet
ObjSqlConnection = New SqlConnection(ConnectionString)

If ObjSqlConnection.State <> ConnectionState.Open Then
ObjSqlConnection.Open()
End If

ObjSqlDataAdapter = New SqlDataAdapter(CommandText, ObjSqlConnection)
ObjDataSet = New DataSet()
ObjSqlDataAdapter.Fill(ObjDataSet)
Gridview1.DataSource = ObjDataSet.Tables(0)

Catch ex As Exception
Throw New Exception(ex.Message)
Finally
ObjSqlConnection.Close()
ObjSqlConnection.Dispose()
End Try

if solved pls mark as solved

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