Monday, October 5, 2009

Create DataTable and sort Programmatically in C#, ASP.NET

Create a DataTable instance

DataTable table = new DataTable();

Create 7 columns for this DataTable

DataColumn col1 = new DataColumn("ID");
DataColumn col2 = new DataColumn("Name");
DataColumn col3 = new DataColumn("Checked");
DataColumn col4 = new DataColumn("Description");
DataColumn col5 = new DataColumn("Price");
DataColumn col6 = new DataColumn("Brand");
DataColumn col7 = new DataColumn("Remarks");

Define DataType of the Columns

col1.DataType = System.Type.GetType("System.Int");
col2.DataType = System.Type.GetType("System.String");
col3.DataType = System.Type.GetType("System.Boolean");
col4.DataType = System.Type.GetType("System.String");
col5.DataType = System.Type.GetType("System.Double");
col6.DataType = System.Type.GetType("System.String");
col7.DataType = System.Type.GetType("System.String");

Add All These Columns into DataTable table

table.Columns.Add(col1);
table.Columns.Add(col2);
table.Columns.Add(col3);
table.Columns.Add(col4);
table.Columns.Add(col5);
table.Columns.Add(col6);
table.Columns.Add(col7);

Create a Row in the DataTable table

DataRow row = table.NewRow();

Fill All Columns with Data

row[col1] = 1100;
row[col2] = "Computer Set";
row[col3] = true;
row[col4] = "New computer set";
row[col5] = 32000.00
row[col6] = "NEW BRAND-1100";
row[col7] = "Purchased on July 30,2008";

Add the Row into DataTable

table.Rows.Add(row);


Sort DataTable

dt_table.DefaultView.Sort = "[" + dt_table.Columns[1].ColumnName + "] DESC";
table.AcceptChanges();
string PIdmax = table.DefaultView[0]["Name"].ToString();

3 comments:

Anonymous said...

Il semble que vous soyez un expert dans ce domaine, vos remarques sont tres interessantes, merci.

- Daniel

Anonymous said...

Thanks, The microsoft way (on msdn) was extremely complicated and didn't work most of the time.

Anonymous said...

Dapfor provide a net grid which is privide excellent features and higher performance visit dapfor. com