xxxxxxxxxx
DataTable dt = new DataTable();
// Add columns to the DataTable
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
// Add rows to the DataTable
dt.Rows.Add(1, "John", 30);
dt.Rows.Add(2, "Jane", 25);
dt.Rows.Add(3, "Bob", 40);
This creates a DataTable with three columns: "ID" (of type int), "Name" (of type string), and "Age" (of type int). It then adds three rows to the DataTable, with values for each of the columns.
xxxxxxxxxx
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
DataRow _ravi = dt.NewRow();
_ravi["Name"] = "ravi";
_ravi["Marks"] = "500";
dt.Rows.Add(_ravi);
you can use reflection to get the properties of the class and create columns in the DataTable based on them. Then, you can loop through the instances of the class and add them as rows to the DataTable.
xxxxxxxxxx
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
foreach (T item in items)
{
DataRow row = dataTable.NewRow();
foreach (PropertyInfo property in properties)
{
row[property.Name] = property.GetValue(item) ?? DBNull.Value;
}
dataTable.Rows.Add(row);
}
return dataTable;
}
//To use this method, you can pass in a List of instances of your class, and it will return a DataTable that represents the data in the List. For example:
List<Person> people = new List<Person> {
new Person { Name = "John", Age = 30 },
new Person { Name = "Jane", Age = 25 }
};
DataTable dataTable = ToDataTable<Person>(people);
This will create a DataTable with columns "Name" and "Age", and two rows of data for John and Jane.
xxxxxxxxxx
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
DataRow _ravi = dt.NewRow();
_ravi["Name"] = "ravi";
_ravi["Marks"] = "500";
dt.Rows.Add(_ravi);
xxxxxxxxxx
String[] arr = new String[] { "a", "b" };
DataTable dt = new DataTable();
dt.Columns.Add("name");
dt.Columns.Add("other");
dt.Rows.Add(arr);
foreach (DataRow r in dt.Rows)
{
Console.WriteLine(r["name"].ToString() + " - " + r["other"].ToString());
}