I frequently notice that most programmers access data from a datatable using column indexes as shown below:
public class TestClass
{
public void MyTestMethod()
{
DataTable dt = DataAccessLayer.GetTableData();
foreach(DataRow dRowin dt.Rows)
{
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()
{
DataTable dt = DataAccess.GetTableData();
foreach (DataRow dRow in dt.Rows)
{
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.