ZengCode.Com (The Thai Php Framework)  


Home   Download   Manual   About us    

Facebook   


MAIN MENU
News
Php Tips
Android Programming
Design Pattern By PHP
Spring+Strut+Hibernate
C# Tips & Technique
C# Design Pattern
Linux Quick Tips
C# using Linq น่าใช้จริงๆ
Java & JavaScript Tips
Database & SQL
ZengCode Framework Guide
Zeng Code Code
Programming
IPhone (Tips and Trick)

Download เอกสารที่น่าสนใจ

     C# DataTable Examples, Columns and Rows  (2009-11-03)

C# DataTable Examples, Columns and Rows

by Sam Allen - Updated October 11, 2009

Problem. You need to store data that was read from a database such as SQL Server or generated in memory from user input. DataTable is ideal for this purpose, as you can take objects from memory and display the results in controls such as DataGridView in Windows Forms. Solution. Here we see examples for DataTable in the C# language, first looking at how you can generate a simple DataTable with rows and columns in memory, and then rendering it to the screen.

DataTable is found in the System.Data namespace.              
    It stores data in memory from databases or user input.    
    It helps with using DataGridView and SQL Server databases.

1. Simple DataTable example

First, the DataTable type is probably the most convenient and powerful way to store data in memory. You may have fetched this data from a database, or you may have generated it dynamically. In this example, we get a DataTable with four columns of type int, string and DateTime. This DataTable could then be persisted or displayed.

using System;
using System.Data;

class Program
{
    static void Main()
    {
        //
// Get the DataTable.
//
DataTable table = GetTable(); //
// Use DataTable here with SQL, etc.
//
} /// <summary>
/// This example method generates a DataTable.
/// </summary>
static DataTable GetTable() { //
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable(); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patient", typeof(string)); table.Columns.Add("Date", typeof(DateTime)); //
// Here we add five DataRows.
//
table.Rows.Add(25, "Indocin", "David", DateTime.Now); table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); return table; } }

Note on GetTable method. This method simply instantiates a new DataTable reference, adds four column collections to it, and then adds five drug and patient records. The next step to using this code could be to assign the DataSource to a Windows Forms control.

2. Detailed DataTable example

The first example was simplistic, but the next example here will show you how to insert data from object collections such as List into a DataTable, and then render that table onto the screen with Windows Forms.

DataTable example screenshot

Why use DataTable here? It makes your DataGridView simpler and easier. You could manually add data to the DataGridView using the Add method, but it's better to put the logic in a separate class. DataGridView has performance problems with manually adding rows.

How to use a DataGridView. Make a new Windows Forms project and add a DataGridView to it. It will be named dataGridView1 for you automatically. Its purpose will be rendering the DataTable you will make. You need some actual data for the example. You will have something important, so just use that.

Getting started with the DataTable. We want to make a new class and make a method that returns DataTable. This method will return the full DataTable. In my testing the application handled one million numbers with only moderate slowdowns.

using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        /// <summary>
/// Contains column names.
/// </summary>
List<string> _names = new List<string>(); /// <summary>
/// Contains column data arrays.
/// </summary>
List<double[]> _dataArray = new List<double[]>(); public Form1() { InitializeComponent(); // Example column. _names.Add("Cat"); // Three numbers of cat data _dataArray.Add(new double[] { 1.0, 2.2, 3.4 }); // Another example column _names.Add("Dog"); // Add three numbers of dog data _dataArray.Add(new double[] { 3.3, 5.0, 7.0 }); // Render the DataGridView. dataGridView1.DataSource = GetResultsTable(); } /// <summary>
/// This method builds a DataTable of the data.
/// </summary>
public DataTable GetResultsTable() { // Create the output table. DataTable d = new DataTable(); // Loop through all process names. for (int i = 0; i < this._dataArray.Count; i++) { // The current process name. string name = this._names[i]; // Add the program name to our columns. d.Columns.Add(name); // Add all of the memory numbers to an object list. List<object> objectNumbers = new List<object>(); // Put every column's numbers in this List. foreach (double number in this._dataArray[i]) { objectNumbers.Add((object)number); } // Keep adding rows until we have enough. while (d.Rows.Count < objectNumbers.Count) { d.Rows.Add(); } // Add each item to the cells in the column. for (int a = 0; a < objectNumbers.Count; a++) { d.Rows[a][i] = objectNumbers[a]; } } return d; } } }

3. Detailed description

It is an entire Form. The above code can be dropped into a Windows Forms application with a DataGridView in the designer. The two arrays are initialized in the class and in the constructor. They contain column information.

How to create a new DataTable. In the above code, we create a new DataTable. This is populated with all the data and put into the DataGrid. Note that there are more efficient ways of modifying existing DataTables.

How to loop through columns. We have a collection that contains many arrays. Each of those arrays needs to be a new column. So the main loop in the above code loops through the data we want to put in each column, one column at a time. This site now contains more information about looping through the rows and cells in the DataTable type in the C# language. [C# DataTable Foreach Loops - dotnetperls.com]

How to add columns by name. We add the column names to the DataTable. This can be the data series type, such as "name", "number" or "id". These are the column headers, which must be added with Columns.Add().

How to use an object array. The DataTable requires that we use arrays of objects to assign to the cells. Here we loop through each point in the column, which each point being a new row.

How to add empty rows. We keep adding rows until we have enough to contain all the data points in our array. If we don't add empty rows, the runtime will throw an exception. Right after this step, we assign the cells. [C# DataRow Examples - dotnetperls.com]

How to assign each cell in your column. We set each cell in this column to its data value. Be careful with the indexer syntax on the DataTable and make sure there are enough rows. We directly use our object list that we converted from another value type.

4. Example use

Here you can assign the DataSource of your DataGridView directly to the result value. We use .NET's built-in display logic instead of reinventing the wheel. For Windows Forms, the DataSource property usually provides better display performance than trying to add cells or rows to the DataGridView individually.

//
// Draw new cells on DataGridView.
//
dataGridView1.DataSource = null; dataGridView1.DataSource = GetResultsTable();
Question

5. Parts

The two most important parts of DataTable are its Rows collection and its Columns collection. Use the instance Add method to add to either of these collections. There is more information, including many examples, of using DataRow collections on this site. The article on the DataColumn type provides more details on the internal representations of the DataTable in the .NET Framework. [C# DataColumn Class - dotnetperls.com]

6. When should I use DataTable?

When you have lots of data in objects, you can construct a DataTable and use it to display information in your DataGridView. Additionally, you can use DataTable with SqlAdapter and SqlCommandBuilder to easily insert chunks of data into SQL Server 2005. [C# SqlCommandBuilder Example - dotnetperls.com]

7. Sorting views

One very useful way to manipulate your DataTable's representation is to sort it using DataView. The DataView has a sort property you can assign. More detail about the DataView and sorting DataTables is available here. [C# DataView Usage Examples - dotnetperls.com]

8. Summary

Here we saw how you can add data to a DataTable in the C# programming language. This code is effective when storing more than one million data points and rendering them every three seconds. DataTable is far smoother for Windows Forms than manually adding rows, and it separates presentation from logic.


Comment
Name
Comment
Security CodeCAPTCHA Image

web hit counter

This page took 0.089949 seconds to load.