.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> DataGrid >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Bind DataTable To GridView

Posted By:shiv chandra       Posted Date: June 30, 2011    Points: 40    Category: DataGrid    URL: http://www.dotnetspark.com  

This sample code show how to Bind DataTable To GridView
 

This article is basically for beginners. How to execute query from C#.

1. Set database.
string Database = "Name Of Database";
2. Set connection.
SqlConnection Con = new SqlConnection("Data Source=MyPC\\sqlexpress;Initial Catalog=" + Database + ";Integrated Security=True");
3. Set SQL Command.
SqlCommand Cmd = new SqlCommand("SELECT * FROM TableName", Con);
4. Create object of datatable.
DataTable Table = new DataTable();
5. Create object of Data Adapter.
SqlDataAdapter Adapter = new SqlDataAdapter(Cmd);
6. Fill adapter.
Adapter.Fill(Table);
7. Set datasource of grid.
Grid.DataSource = Table;
8. Bind data source with Grid.
Grid.DataBind();

Finally code looks like following.
protected void Page_Load(object sender, EventArgs e)
{
    string Database = "Name Of Database";
    SqlConnection Con = new SqlConnection("Data Source=MyPC\\sqlexpress;Initial Catalog=" + Database + ";Integrated Security=True");
    SqlCommand Cmd = new SqlCommand("SELECT * FROM TableName", Con);

    DataTable Table = new DataTable();
    SqlDataAdapter Adapter = new SqlDataAdapter(Cmd);
    Adapter.Fill(Table);

    Grid.DataSource = Table;
    Grid.DataBind();
}}
Before using above code, please change database and TabeName procedure.

Regards,
Shiva


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend