Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.

I want to store row for row which a datareader reads from my sql database into a gridview.

basically :

While reader.Read()

//Here i want to get the entire row that it reads eg. theName,Description,number
//and store that as is so that it can be used to populate my gridview.

end while

The gridview must look exactly like a SQL table would when you run a query like :
SELECT * FROM tblClients

any help?
Posted

Why?

A simple binding can't be an option???

C#
public static DataTable GetData()
{
    DataTable table = new DataTable();
    string query = @"SELECT * FROM tblClients";

    using (SqlConnection cn = new SqlConnection(Configuration.DefaultConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand(query, cn))
        {
            cn.Open();

            using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                table.Load(reader);
            }
        }
    }

    return table;
}

MyGrid.DataSource = GetData();
MyGrid.DataBind();


VB.NET

Public Shared Function GetData() As DataTable
	Dim table As New DataTable()

	Using cn As New SqlConnection("your connection string")
		Using cmd As New SqlCommand("SELECT * FROM tblClients", cn)
			cn.Open()

			Using reader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
				table.Load(reader)
			End Using
		End Using
	End Using

	Return table
End Function

Cheers
 
Share this answer
 
v2
Comments
Member 9374423 23-Aug-12 5:12am    
Hi I do appreciate the help. but could you please rewrite this in VB.net code? it seems to have trouble descripting in VB.
Mario Majčica 23-Aug-12 5:16am    
I just updated the solution. Converting code is easy http://converter.telerik.com/ or http://www.developerfusion.com/tools/convert/csharp-to-vb/ .

Cheers
Member 9374423 23-Aug-12 5:20am    
It works Perfectly Thank you very much :}
The FieldCount property of the DataReader tells you the number of columns.
The GetFieldType(columnIndex) function gives infromation on the type of the data.
And then do the nested loops thru your data, and fill the gridview.
 
Share this answer
 
Comments
Member 9374423 23-Aug-12 5:14am    
could you please supply an example?

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