Click here to Skip to main content
15,880,469 members
Articles / Programming Languages / C#
Article

Using the DataGrid Control

Rate me:
Please Sign up or sign in to vote.
4.76/5 (62 votes)
13 Jun 20056 min read 791.6K   27.9K   209   40
An introduction to using the ADO.NET control.

Sample Image

Introduction

This small application for DataGrid allows users to:

  • add a new row in the DataGrid.
  • save or update a row of the DataGrid.
  • delete an existing row from the DataGrid.
  • read the data from an XML file.
  • copy the current data of the DataSet to three files on C:\ root directory:
    1. MyXMLText.txt (text file)
    2. MyXMLdata.xml (XML file)
    3. MyXMLschema.xsd (schema file)
  • write the current data of the table to a text file on C:\.

The DataGrid control in the "DataGrid Application" binds to a single DataSet object. The DataSet object of the "DataGrid Application" is initially populated from a database using an OleDbDataAdapter object.

What is a DataGrid?

The Windows Forms DataGrid control provides a user interface to ADO.NET datasets, displays ADO.NET tabular data in a scrollable grid, and allows for updates to the data source. In cases where the DataGrid is bound to a data source with a single table containing no relationships, the data appears in simple rows and columns, as in a spreadsheet. The DataGrid control is one of the most useful and flexible controls in Windows Forms. As soon as the DataGrid control is set to a valid data source, the control is automatically populated, by creating columns and rows based on the structure of the data. The DataGrid control can be used to display either a single table or the hierarchical relationships between a set of tables.

For example: if you bind the DataGrid to data with multiple related tables, and if you enable navigation on the DataGrid, the DataGrid displays so called 'expanders' in each row.

Image 2

With an expander, you can navigate from a parent table to a child table. If you click a node in the DataGrid, it displays the child table. If you click the Back button, it displays the original parent table. In this fashion, the grid displays the hierarchical relationships between tables.

Image 3

Bear in mind that only one table can be shown in the DataGrid at a time. Valid data sources for the DataGrid include:

  • DataTable
  • DataView
  • DataSet
  • DataViewManager
  • A single dimension array
  • Any component that implements the IListSource interface.

How to display data in the DataGrid programmatically?

If you want to display data in a DataGrid, you need to define a DataGrid object. There are, of course, different ways to populate the data in the DataGrid. For example:

Define first a DataGrid and declare a new DataGrid, and then set some properties of the DataGrid (location, name, size etc..).

C#
private System.Windows.Forms.DataGrid dataGrid1;
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.dataGrid1.Location = new System.Drawing.Point(16, 40);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(256, 176);

Now we can put all the commands needed into a method "fnDisplayDataInDataGrid()", to display data in the DataGrid.

C#
private void fnDisplayDataInDataGrid()
{
   string conStr ="Integrated Security=SSPI;" +
   "Initial Catalog=Northwind;" +
   "Data Source=SONY\\MYSQLSERVER;";
   SqlConnection conn = new SqlConnection(conStr);
   // Open the connection
   conn.Open();
   // Create a data adapter object
   SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM MyTable", conn);
   // Create a DataSet object
   DataSet ds = new DataSet();
   // filling the DataSet 
   adapter.Fill(ds,"MyTable");
   // you can use one of the followings.Both works fine.
   // this.dataGrid1.SetDataBinding(ds,"MyTable"); or
   this.dataGrid1.DataSource=ds.DefaultViewManager;
}

At this point, I would refer you to my previous article (Using ADO.NET for beginners) where you can find some more interesting tips and tricks for DataGrids (i.e., how to trap keystroke events - Up, Down, Escape etc. - in a DataGrid).

How It Works

After you get connected to the MS Access database, all records are displayed on the DataGrid.

When you run the application first time, the method "fnRefresh()" will be called. It clears the contents of the DataSet, fills the DataAdapter, and displays the data from the data source in the DataGrid. After that, all the buttons are ready to be used. Here is the code snippet of the method "fnRefresh()":

C#
private void fnRefresh() 
{
   this.dataSet11.Clear(); 
   this.oleDbDataAdapter1.Fill(this.dataSet11,"MyContactsTable"); 
   this.dataGrid1.DataSource=this.dataSet11.Tables["MyContactsTable"].DefaultView; 
}

Insert a new row

If you click the "Insert" button to add a new record, the last row on the DataGrid is selected and the previous clicked row is unselected. After entering the data for that row, you click the 'Save/Update'-button to save the new row. Here is the method for inserting a new row:

C#
private void fnInsertNew() 
{
   //keep in mind the previous clicked row to unselect
   int iPrevRowindex=this.iRowIndex; 
   MessageBox.Show("Enter the new record at the end" + 
     " of the DataGrid and click 'Save/Update'-button", "Stop"); 
   this.btInsertnew.Enabled=false; 
   //get how many records in the table 
   this.iRowIndex=this.dataSet11.Tables["MyContactsTable"].Rows.Count; 
   //select the last row 
   this.dataGrid1.Select(this.iRowIndex);
   //unselect the previous row
   this.dataGrid1.UnSelect(iPrevRowindex);
}

Save or Update the new/changed row(s)

The code snippet for the method "fnSaveUpdate()" saves the changes that are made to the DataSet back to the database. The 'GetChanges' method of dataSet11 will return a new DataSet which is called 'myChangedDataset' containing all the rows that have been modified (updated, deleted or inserted). If no changes have been made, the method 'GetChanges' returns a 'null' DataSet.

If any sort of error occurs while updating the database, the 'Update' method of OleDbDataAdapter will generate an exception. This logic is held in a try/catch block. If an exception occurs, you get a message box informing you of the error. And the "RejectChanges" method is then called to discard the changes you made. If any changes are made, the user is told how many rows were affected/changed, and the "AcceptChanges()" method will mark the changes made as permanent in the DataSet. Now we need to invoke refreshing the DataSet with the method "fnRefresh()". I think this is a 'simple' and robust technique when updating the database.

Here is the code snippet for the 'fnSaveUpdate()' method:

C#
private void fnSaveUpdate() 
{
   try 
   { 
      //put the modified DataSet into a new DataSet(myChangedDataset) 
      DataSet myChangedDataset= this.dataSet11.GetChanges(); 
      if (myChangedDataset != null) 
     { 
        //get how many rows changed 
        int modifiedRows = this.oleDbDataAdapter1.Update(myChangedDataset); 
        MessageBox.Show("Database has been updated successfully: " + 
                      modifiedRows + " Modified row(s) ", "Success"); 
        this.dataSet11.AcceptChanges(); //accept the all changes 
        fnRefresh(); 
     } 
     else 
     } 
        MessageBox.Show("Nothing to save", "No changes"); 
      }//if-else 
   } 
   catch(Exception ex) 
  { 
     //if something somehow went wrong 
    MessageBox.Show("An error occurred updating the database: " + 
      ex.Message, "Error",  MessageBoxButtons.OK, MessageBoxIcon.Error); 
    this.dataSet11.RejectChanges(); //cancel the changes 
  }//try-catch 
  fnEnableDisableAllButtons(true);
}

Delete the current row

It is always a good practice to ask the user before deleting a row. After clicking 'Yes', the current row on the DataGrid is deleted, updated and refreshed. The method for deleting a row is as below:

C#
private void fnDelete() 
{
    //ask user if wanting to delete
    DialogResult dr=MessageBox.Show("Are you sure you want to delete this row ? ", 
           "Confirm deleting",  MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (dr ==DialogResult.Yes) 
    {
        DataTable tbl=new DataTable("MyContactsTable");
        tbl=this.dataSet11.Tables[0];
        int i=this.iRowIndex;//get the index of the row you clicked
        tbl.Rows[i].Delete(); //delete the row
        this.oleDbDataAdapter1.Update(tbl); //update the table
        this.fnRefresh(); //refresh the table 
    }
}

Reading the data from an XML file

Sometimes you have to read the data from an XML file and display it in a DataGrid. In order to do this, I pass the XML file to the method; if the file exists, I clear the DataSet and read the XML data into the DataSet using the specified file. The following code snippet shows this:

C#
private void fnDataReadingFromXMLFile(string filename)
{
  //check if the file exists
  if ( File.Exists(filename))
  {
    //clear the DataSet contents
    this.dataSet11.Clear();
    MessageBox.Show("Data reading from "+filename+" -file");
    this.dataSet11.ReadXml(filename);
   } //if
   else {
    MessageBox.Show(filename + " does NOT exist; Please click" + 
       " first the button 'CopyToXML' ", "File Error", 
       MessageBoxButtons.OK, MessageBoxIcon.Error );
  }//else
}

Copy the DataSet to the Text / XML / Schema file

Clicking the 'CopyToXML' button invokes the 'fnCopyToXMLandTextFile()' method. As you can guess from its name, it writes the current data of the DataSet to three files on the C:\ root directory:

  1. Text file: MyXMLdataText.txt.
  2. XML file: XMLdata.xml.
  3. Schema file: MyXMLschema.xsd.

If you wish to use another path instead of 'C:\', you have to change the code accordingly. The following code snippet demonstrates this feature:

C#
private void fnCopyToXMLandTextFile() 
{
    if (this.dataSet11 == null) 
    {
        return; //cancel 
    }
    files. this.dataSet11.WriteXml("C:\\MyXMLText.txt"); 
    this.dataSet11.WriteXml("C:\\MyXMLdata.xml", XmlWriteMode.WriteSchema); 
    this.dataSet11.WriteXmlSchema("C:\\MyXMLschema.xsd"); 
    string s="The current data of the DataSet coppied on C:\\ as: \n"; 
    s +="* Text file: MyXMLdataText.txt\n"; 
    s +="* XML file: XMLdata.xml\n"; 
    s +="* Schema file: MyXMLschema.xsd"; 
    MessageBox.Show(s, "Copy to XML/Text/Schema file"); 
}

Writing the current data of the table into a text file on hard disk (C:\)

Because ExecuteReader requires an open and available connection, first we have to open the database connection. If the connection's current state is Closed, you get an error message. After opening the connection, we create an instance of OleDbCommand, a CommandText for the SQL statement, an OleDbDataReader and an instance of StreamWriter. And then, in a while-loop, the OleDbDataReader reads through the data rows and writes them out to the text file. Finally, it closes the OleDbDataReader. In StreamWriter writer = new StreamWriter("C:\\MyTextFile.txt", false), we pass the the text file and set the bool value to 'false'. If the file doesn't exist, in any case a new text file will be created. If the file exists and it the second parameter is 'false', the file will be overwritten because of 'false'. If the value is 'true', then the file won't be overwritten and the data will then be appended to the file. Here is the code snippet for writing to the text file:

C#
private void fnWriteToTextFile()
{
  OleDbDataReader reader;
  OleDbCommand cmd=new OleDbCommand();  
  this.oleDbConnection1.Open(); //open the connection
  cmd.CommandText="SELECT Address, City, Country, Email," + 
      " FirstName, LastName, Message, Phone FROM MyContactsTable";
  cmd.Connection=this.oleDbConnection1;
  reader=cmd.ExecuteReader();
 //the "using" statement causes the close method to be called internally.
 //if "using" not used, use "writer.Close()" in try-catch-finally explicitly
  using (StreamWriter writer = new StreamWriter("C:\\MyTextFile.txt",false)) 
  { 
  //false means: textfile is overwritten
  try
  {
    while (reader.Read())
    {
      writer.Write(reader["LastName"]);
      writer.Write("#"); //separator
      writer.Write(reader["FirstName"]);
      writer.Write("#");
      writer.Write(reader["Address"]);
      writer.Write("#");
      writer.Write(reader["City"]);
      writer.Write("#");
      writer.Write(reader["Country"]);
      writer.Write("#");
      writer.Write(reader["Email"]);
      writer.Write("#");
      writer.Write(reader["Message"]);
      writer.Write("#");
      writer.Write(reader["Phone"]);
      writer.WriteLine(); //next new line
    }//while 
  }catch (Exception excp) 
  {
    MessageBox.Show(excp.Message);
  }finally {
    reader.Close(); //close the OleDbDataReader
  }//try-catch-finally
 }//using
   MessageBox.Show("Data of table writtten into" + 
      " C:\\MyTextFile.txt file","Writing completed");
}

And Finally

I think the code is quite simple to understand because I tried to make comments to almost every line of code. I hope you can find something useful here for your projects. As ever, all feedback is welcome. For more tips about the DataGrid, here is the link of my other article: Using ADO.NET for beginners.

Happy coding!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionRead and Write to a single XML file Pin
penguinman57311-May-14 16:07
penguinman57311-May-14 16:07 
QuestionHow to upgrade the datagrid record. Pin
Member 101928356-Oct-13 22:38
Member 101928356-Oct-13 22:38 
GeneralMy vote of 5 Pin
Ibrahim Swaiss10-Oct-11 5:11
Ibrahim Swaiss10-Oct-11 5:11 
QuestionMandatory field Pin
Member 45771397-Aug-11 20:03
Member 45771397-Aug-11 20:03 
GeneralMy vote of 5 Pin
rajkarthik8622-Jun-11 21:31
rajkarthik8622-Jun-11 21:31 
GeneralOne suggestion... Pin
crashandburn525-Mar-11 20:01
crashandburn525-Mar-11 20:01 
QuestionYOU HAVE DONE GREAT JOB. THANKS ALOT. But I have little Question. Pin
Serkan116-Jan-11 14:44
Serkan116-Jan-11 14:44 
AnswerRe: YOU HAVE DONE GREAT JOB. THANKS ALOT. But I have little Question. Pin
Member 313221131-Mar-11 23:32
Member 313221131-Mar-11 23:32 
QuestionChanging the text color in a specified row Pin
Mark Remington22-Sep-10 6:07
Mark Remington22-Sep-10 6:07 
Generalthanks Pin
cslxxwilliam4-Aug-10 22:53
cslxxwilliam4-Aug-10 22:53 
GeneralDataGridView (from xml) export to xls. Pin
gs_virdi24-May-10 23:53
gs_virdi24-May-10 23:53 
GeneralText box binding Pin
mikabongio29-Apr-10 4:24
mikabongio29-Apr-10 4:24 
QuestionUsing ADO and the Datagrid control in VB6 Pin
chris_xi0123-Mar-09 22:48
chris_xi0123-Mar-09 22:48 
QuestionHow do you access the elements of a SelectedRow in datagird C#.net [modified] Pin
djMcCauley23-Mar-09 3:09
djMcCauley23-Mar-09 3:09 
QuestionHow i can create public connection Pin
abudjava20-Dec-08 5:01
abudjava20-Dec-08 5:01 
General64bit and Microsoft.Jet.OLEDB.4. Pin
vguerrero19-Nov-08 18:16
vguerrero19-Nov-08 18:16 
GeneralDataGrid File Reder Pin
Reza Madani7-Aug-08 11:21
Reza Madani7-Aug-08 11:21 
Questiondatagrid bound to AD? Pin
ladypins27-Jul-08 2:50
ladypins27-Jul-08 2:50 
GeneraldataGrid event generation Pin
kanza azhar14-May-08 11:11
kanza azhar14-May-08 11:11 
GeneralDatagrig write txtfile fixed Pin
maxmonte17-Apr-08 1:43
maxmonte17-Apr-08 1:43 
QuestionGroup columns Pin
evgeny6813-Apr-08 22:26
evgeny6813-Apr-08 22:26 
QuestionHow can i access the elements of a selectedrow in datagird C#.net Pin
Member 424298420-Jan-08 20:17
Member 424298420-Jan-08 20:17 
Jokefadsfsadf Pin
le xuan nam25-Sep-07 21:12
le xuan nam25-Sep-07 21:12 
GeneralTotal should be displayed in the TextBox Pin
juliesamy27-Feb-07 20:19
juliesamy27-Feb-07 20:19 
QuestionGrid View Pin
John.L.Ponratnam8-Jan-07 20:56
John.L.Ponratnam8-Jan-07 20:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.