How do create a DataTable in C#?
I did like this:
DataTable dt = new DataTable();
dt.clear();
dt.Columns.Add(\"Name\");
dt.Columns.Add(\"Marks\")
You can also pass in an object array as well, like so:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);
Or even:
dt.Rows.Add(new object[] { "Ravi", 500 });
You can write one liner using DataRow.Add(params object[] values) instead of four lines.
dt.Rows.Add("Ravi", "500");
As you create new DataTable
object, there seems no need to Clear
DataTable
in very next statement. You can also use DataTable.Columns.AddRange
to add columns with on statement. Complete code would be.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });
dt.Rows.Add("Ravi", "500");
Here's the code:
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);
To see the structure, or rather I'd rephrase it as schema, you can export it to an XML file by doing the following.
To export only the schema/structure, do:
dt.WriteXMLSchema("dtSchemaOrStructure.xml");
Additionally, you can also export your data:
dt.WriteXML("dtDataxml");
To add a row:
DataRow row = dt.NewRow();
row["Name"] = "Ravi";
row["Marks"] = 500;
dt.Rows.Add(row);
To see the structure:
Table.Columns
You can add Row in a single line
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
DataTable dt=new DataTable();
DataColumn Name = new DataColumn("Name",typeof(string));
dt.Columns.Add(Name);
DataColumn Age = new DataColumn("Age", typeof(int));`
dt.Columns.Add(Age);
DataRow dr=dt.NewRow();
dr["Name"]="Kavitha Reddy";
dr["Age"]=24;
dt.add.Rows(dr);
dr=dt.NewRow();
dr["Name"]="Kiran Reddy";
dr["Age"]=23;
dt.Rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();