Was hanging out StackOverflow and I saw Marc Gravell initializing the DataTable in a simpler and cleaner way. Here goes
DataTable dataTable = new DataTable
{
Columns = {
{"ID", typeof(int)},
{"Name", typeof(string)},
"Location"
},
TableName="NaveenTest"
};
dataTable.Rows.Add(1, "Naveen", "Coder");
Please note that if you don't specify the type it will automatically be converted to string. See how "Location" is initialisedAnd my old method
DataTable dtOld = new DataTable("NaveenTest");
dtOld.Columns.Add("MyID", typeof(int));
dtOld.Columns.Add("Name");
dtOld.Columns.Add("Location");
DataRow drOld = new DataRow();
drOld[0] = 1;
drOld[1] = "Naveen";
drOld[2] = "Coder";
dtOld.Rows.Add(drOld);
Aaarghhh...
A lot cleaner!
What do you say?
0 comments on "Different ways to create a DataTable and set Schema"
Subscribe in a Reader
Post a Comment