Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to read data from database using a data reader.
I have a text box and a click button.
When i enter data in the textbox and click search then it should display the data .
How to do it with Datareader and display the in a gridview?

Please help me out..
Posted
Comments
[no name] 14-Jun-13 5:26am    
What have you tried and where are you stuck?

Its better to use DataAdapter to fill a datagridview from database .
Data reader used mostly where we have to fetch and process data row one by one.
i.e.
VB
Dim ConnStr As String= "your connection string"
Dim SConn As System.Data.SqlClient.SqlConnection
Dim SqlStat As String="select * from tableName"
SConn = New System.Data.SqlClient.SqlConnection(ConnStr)
SConn.Open()  'open connection

Using DataAdapter is so simple.
VB
Dim ds As DataSet = New DataSet()
Dim da As System.Data.SqlClient.SqlDataAdapter
da = New System.Data.SqlClient.SqlDataAdapter(SqlStat, SConn)
da.Fill(ds, "myTable")
DatagridView1.DataSource=ds.tables("myTable") 'We candirectly bind dataset to DataGridView.


If you must have to use datareader then
using datareader :

VB
Dim SComm As System.Data.SqlClient.SqlCommand
SComm = New System.Data.SqlClient.SqlCommand(SqlStat, SConn)
Dim reader As SqlDataReader= SComm.ExecuteReader
      'We cannot directly bind DataReader to DataGridView.
Dim table As New DataTable()
table.Load(reader)
DatagridView1.DataSource=table

At Last close connection
VB
SConn.Close()'close connection
 
Share this answer
 
v3
C#
sqlconnection con=new seqlconnection("Write Connection String")
sqlCommand cmd=new SqlCommand("Select * from table where columnname like '%"+texbox.text+"'",con)
cmd.con.open();
sqldatareader dr=cmd.ExecuteReader();
dr.read();
datatable dt=new datatable();
dt.Load(dr);
cmd.con.close();
GridView.DataSource=dt;
Gridview.DataBind();
 
Share this answer
 
v4
Comments
VICK 14-Jun-13 5:47am    
Is it the solution to your answer or you have posted the problematic code???
yourfriendaks 14-Jun-13 6:05am    
No, tell me What U Want That I Write Line By Line Code For U?
yourfriendaks 14-Jun-13 6:06am    
u Written That How to read Data Using SqlDatareader that's It

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900