Friday, April 2, 2010

Laoding Data from Database in the Data Grid

First of all we need to create connection of an application with the database add a app.config file in to your solution.

add the code in the main tag of the HTML code present in the app.config file


connectionString="Data Source= XYZ-PC6\SQLEXPRESS;;USER ID=uid;password=pwd;Initial Catalog = umais;"
providerName="System.Data.SqlClient" />


Provide Data Source, data server name, its user ID password and Catalog from the data base

after this need to add the connection string from the CS file

Create a method dataBaseConnection, in the method pass the connection string, create SQL connection and open the connection
string connectionString = (string)ConfigurationManager.ConnectionStrings["_4UnitTesting.Properties.Settings.DBConnectionString"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();

SQLDataAdapter is used to fire the SQL Query

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM DatagridTable", sqlConnection);

initialized the dataset and fill it in the SQL Adapter.
DataSet ds = new DataSet();


ad.Fill(ds);

in the end bind it with datagrid (gvData) datagrid name

gvData.DataSource = ds.Tables[0];

Now after doing this call dataBaseConnection the method from where it will load the data, on click event.....

By this you can load data from the data base, if you want to save the loaded data in CSV file use the previous post of Saving data in CSV file, Need to do same thing...

No comments:

Post a Comment