tags:

views:

5634

answers:

5

Hi

Can any body plz help me creating DataTable in c#. I did like this

 DataTable dt=new DataTable();
 dt.clear();
 dt.Columns.Add("Name");
 dt.Colums.Add("Marks");

and how to see the structure of DataTable.

Now i want to add for name : ravi and Marks : 500 how to do this one

Any Help will greatly Appreciated

+1  A: 

To add a row:

DataRow row = dt.NewRow();
row["Name"] = "Ravi";
row["Marks"] = 500;
dt.Rows.Add(row);

To see the structure:

Table.Columns
GenericTypeTea
You forgot to add dt.AddRow(row); at the end of your code.
Canavar
+1  A: 

You have to add datarows to your datatable for this.

// Creates a new DataRow with the same schema as the table.
DataRow dr = dt.NewRow();

// Fill the values
dr["Name"] = "Name";
dr["Marks"] = "Marks";

// Add the row to the rows collection
dt.Rows.Add ( dr );
rahul
+4  A: 

Here's the code..

DataTable dt=new DataTable(); 
dt.clear(); 

dt.Columns.Add("Name"); 
dt.Colums.Add("Marks");

DataRow _ravi = dt.NewDataRow();
_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 this..

To export only Schema/Structure

dt.WriteXMLSchema("dtSchemaOrStructure.xml");

Additionally you can also Export your data

dt.WriteXML("dtDataxml");

Thanks,

this. __curious_geek
There is no need to apply clear in a newly created datatable
rahul
DataTable class doesn't have AddRow method. You have to do dt.Rows.Add(_ravi); instead
Salamander2007
And there's no such thing as AddRow. It's DataTable.Rows.Add()
GenericTypeTea
Don't forget to call dt.AcceptChanges() in case you use DataView with filter other than CurrentRows.
Salamander2007
@DanD, @Salamander2007: agreed. I changed it now. Sry for the mistake, that happened bcoz I use typed datasets which support this thing.
this. __curious_geek
@phoenix: I just wanted the question asker to happily relate with my answer.
this. __curious_geek
@Salamander2007 : It seems just an in memory datatable created at runtime, so we dnt need to call AcceptChanges()
this. __curious_geek
A: 

In addition to the other answers.

If you control the structure of the DataTable there is a shortcut for adding rows:

// Assume you have a data table defined as in your example named dt dt.Rows.Add("Name", "Marks");

The DataRowCollection.Add() method has an overload that takes a param array of objects. This method lets you pass as many values as needed, but they must be in the same order as the columns are defined in the table.

So while this is a convenient way to add row data, it can be risky to use. If the table structure changes your code will fail.

Rune Grimstad
+1  A: 

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 });
James McConnell