as

Saturday 18 January 2014

How to use datagridview in C#.Net

Datagridview is very popular control to display data from any database like Microsoft access, Oracle, Sql Server etc.
In this article I am going to tell you how we can use Datagridview control in C#.Net.

If you have visual studio open you can go to data controls in toolbox and then drag and drop that control on the form where you want to see your data.


After you have got the Datagridview control on your form you can use it in your code to display data.
Below example will show execute one query against access database and then result set will be shown in the datagridview.


            System.Data.Odbc.OdbcConnection con1 = new OdbcConnection();
            con1.ConnectionString = "Dsn=accessdb;";
            con1.Open();

            DataSet ds = new DataSet();
            OdbcDataAdapter daEmp = new OdbcDataAdapter();
            OdbcCommand slctEmp = new OdbcCommand("SELECT * FROM employee", con1);
            daEmp.SelectCommand = slctEmp;
            daEmp.Fill(ds, "tblEmp");
            dataGridView1.DataSource = ds.Tables["tblEmp"];
       
            con1.Close();

Above code will show the data retrieved by the sql query "select * from employee" and show it in the datagridview. Note that we need below classes for working with datagridview in .Net
  1. Dataset - an in-memory cache of data retrieved from a data source
  2. OdbcDataAdapter - set of data commands and a connection to a data source used to fill the DataSet
  3. OdbcCommand       - Sql command to execute 

Please note that the column headers for the datagridview will be same as returned by the query.
This is just a simple example on datagridview but you can do lot more complex operations on datagridview.





What do you think on this topic? Please express your opinion through comment below

Sponsored Links

Popular Posts

Comments

ShareThis