Home Search Contact us About us
Title Populating the DataGrid
Summary The DataGrid control in WinForms is a very powerful and complete item. These code samples describe how to populate the underlaying DataSet manually or from database table.
Contributor John McTainsh
Published 7-May-2001
Last updated 15-Jul-2001
Page rating   78% for 10 votes Useless Brilliant

Description.

These code snippets will demonstrate how to fill a DataGrid manually and with data from a database. This will involve filling a DataSet using a DataTable and an ADODataSetCommand. All these classes are very powerful and have many features that will not be covered here. We will only cover a few of the most simple forms of population.

Create the DataGrid.

The following steps will create the DataGrid object we will use for the remainder of the exercise.

  • Using Visual Studio.NET open a new C# Windows application project.
  • From the View menu select Toolbox.
  • Drag a DataGrid onto the form in design mode.
  • Right click on the DataGrid object on the form and select properties.
  • Change (Name) to m_dgTest.
  • See Simple ADO.NET on using namespace System.Data.OleDb (if using databases)

Displaying database table using OleDbDataAdapter .

This is probably the simplest method. All you need is the database connection string and SQL select statement to return the table rows. Note that with this method the columns information is read from the same location as the data. The "SomeName" parameter is used to label the table in the DataSet as it may contain several tables. This method also allows for the data to be edited my the user and changes pushed back into the database using the OleDbDataAdapter .Update() command.

DataSet ds = new DataSet();

// Read the Data into a Table.
OleDbDataAdapter workDSCMD = new OleDbDataAdapter(
    "SELECT * FROM EMPLOYEES", 
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\CS\\Northwind.mdb;" );
workDSCMD.Fill(ds, "EMPLOYEES" );

// Set the dataset to the Grid
m_dataGrid.DataSource = ds;

Fill the DataGrid using DataReader.

If you do not want to write back to the database and want a little more control over how the data is read or displayed, this section of code should solve your problem. It opens the DataReader and sets up the columns by reading the field names from the table. It then iterates through all the table rows adding them to the DataTable.

// Open connection
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\CS\\Northwind.mdb;";
conn.Open();

// Create DataReader
OleDbDataReader dr;
OleDbCommand cmd = new OleDbCommand( "SELECT * FROM EMPLOYEES", conn );
dr = cmd.ExecuteReader();  

DataTable dt = new DataTable("Employees");

// Setup the Column types
for( int nField = 0; nField < dr.FieldCount ; nField++ )
{
    dt.Columns.Add( dr.GetName( nField ) );
}

// Insert the data into the table
while( dr.Read() )
{
    DataRow datRow = dt.NewRow();   
    for( int nField = 0; nField < dr.FieldCount ; nField++ )
        datRow[nField] = dr.GetValue( nField );
    dt.Rows.Add( datRow );
}       

// Set the dataset to the Grid
DataSet ds = new DataSet();
ds.Tables.Add( dt );
m_dataGrid.DataSource = ds;

Fill the DataGrid from the NT Event Log.

If you became bored enough you may want to create your own event log viewer or even enable viewing the event log through a aspx page. Here we will fill a DataSet with the contents of the local machines "Application" event log. The points to note are;

  • A DataTable is created.
  • Columns are added to the table to create a schema.
  • dt.NewRow is called to create a row with the table's schema.
  • The new row is then populated and added to the Table.
    // Insert just after namespace
    using System.Diagnostics;

    ...

    // Create the Table
    DataTable dt = new DataTable( "MyApplicationLog" );

    //Setup the Column types
    dt.Columns.Add( "Time" );
    dt.Columns.Add( "Source" );
    dt.Columns.Add( "Message" );

    // Open the event log
    EventLog eventLog = new EventLog(); 
    eventLog.Log = "Application";
    
    // Read in each line of the Event Log
    foreach( EventLogEntry entry in eventLog.Entries )
    {
        DataRow dr = dt.NewRow();
        string sTime = entry.TimeGenerated.ToString();
        dr["Time"] = sTime.Replace( 'T', ' ' );
        dr["Source"] = entry.Source;
        dr["Message"] = entry.Message;;
        dt.Rows.Add( dr );
    }

    // Set the dataset to the Grid
    m_dgTest.SetDataBinding(dt.DataSet, "MyApplicationLog" );   

Note:

As with all database operations they MUST be performed inside a try/catch area. This has been omitted for brevity.

Comments Date
Datagrid 29-Aug-2002 Sonia
Sorry,

How can i fill datagrid with item of differentes tables. I want to do more than one select, and display the result in a datagrid, but now, i can only display items of one element of a table.
Can you help me please.

Here my code :
string SelectNbMvtAtt = `Select item from toto`;
string SelectTotalImperr = `Select * from tutu`;
OleDbConnection myconnection= new OleDbConnection (`Provider=MSDAORA;Password=TOTO;User ID=TATA;Data Source=TITI`);
OleDbDataAdapter DA1 = new OleDbDataAdapter();
OleDbDataAdapter DA2 = new OleDbDataAdapter();
DA1.SelectCommand = new OleDbCommand(SelectNbMvtAtt, myconnection);
DA2.SelectCommand = new OleDbCommand(SelectTotalImperr, myconnection);
//OleDbDataAdapter nb_attente_mars_request = new OleDbDataAdapter (SelectNbMvtAtt, myconnection);
OleDbDataAdapter nb_erreur_mars_request = new OleDbDataAdapter (`Select implin_num as TOTO from MRTBIMPLINES where IMP_ID in(select imp_id from MRTBIMPORT where IMP_DATETIMEEND is null) `, myconnection);

DataSet ds_nb_att_mars = new DataSet();
DataSet ds_nb_err_mars = new DataSet();

DA1.Fill(ds_nb_att_mars, `MRTBIMPLINES`);
nb_erreur_mars_request.Fill(ds_nb_err_mars, `Erreurs`);

DataTable mvt_table = ds_nb_att_mars.Tables[0];
DataTable fraicheur_table = new DataTable();




DataGridMvt.DataSource = dvm;
DataGridFraicheur.DataSource = ds_nb_err_mars;

DataGridMvt.DataBind();
DataGridFraicheur.DataBind();
Home Search Contact us About us