Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / performance

Accessing Value from System.Data.DataTable : Tip

3.13/5 (8 votes)
23 Oct 2010CPOL 29.7K  
Accessing Value from System.Data.DataTable
I frequently notice that most programmers access data from a datatable using column indexes as shown below:
public class TestClass
{
  public void MyTestMethod()
  {
    //GetTableData Method fetches data from database using a sql query.
    DataTable dt = DataAccessLayer.GetTableData();
    
     foreach(DataRow dRowin dt.Rows)
     {
        //Accessing data through column index
        int empId = Convert.ToInt32(dRow[0]);
     }
  }
}


In the above example what if the column order in the SQL query fetching data changes, your application will break for sure.

Always access the values through column names as shown below:
public class TestClass
 {
    private const string EMP_ID = "EmpId";
    public void MyTestMethod()
    {
        //GetData fetches data from the database using a SQL query
        DataTable dt = DataAccess.GetTableData();
        foreach (DataRow dRow in dt.Rows)
        {
           //Accessing data through column name
           int empId = Convert.ToInt32(dRow[EMP_ID]);
        }
     }
 }

The code above won't break, even if the column order is changed.

Use a constant variable to hold the column names at a single place so that even if the column name changes in the future then you will have to modify the code in only one place.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)