DolemiteMofo
DolemiteMofo

Reputation: 39

How do I name my row in a c# data table?

I have a DataTable and I add Columns programatically (therefore, there isn't a set number of columns):

MyTable.Columns.Add(Value.name, typeof(double)); 

I then add empty rows to the table for the data:

MyTable.Rows.Add(0);       

I want to add a row labels, such as "price", "quantity", "bid", etc If I add these the way I know how, I need to know the number of columns we will have

How do I code this to be more robust, where the number of columns isn't static? Thanks

Upvotes: 0

Views: 162

Answers (3)

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

You may access columns in the Columns collection.

I will demonstrate the itteration using a list of strings:

List<string> columns = new List<string>();
columns .Add("price");
columns .Add("quantity");
columns .Add("bid");
columns .Add("price");

foreach(string columnName in columns)
{
    if(MyTable.Columns[columnName] == null)
    {
        //Col does not exist so add it:
        MyTable.Columns.Add(columnName);
    } 
}

Notice that the list has the column price twice, but it will only add it once.

public DataTable GetDataTable() 
{ 
    var dt = new DataTable(); 
    dt.Columns.Add("Id", typeof(string)); // dt.Columns.Add("Id", typeof(int));    
    dt.Columns["Id"].Caption ="my id"; 
    dt.Columns.Add("Name", typeof(string)); 
    dt.Columns.Add("Job", typeof(string)); 
    dt.Columns.Add("RowLabel", typeof(string));
    dt.Rows.Add(GetHeaders(dt)); 
    dt.Rows.Add(1, "Janeway", "Captain", "Label1"); 
    dt.Rows.Add(2, "Seven Of Nine", "nobody knows", "Label2"); 
    dt.Rows.Add(3, "Doctor", "Medical Officer", "Label3"); 
    return dt; 
}

Upvotes: 0

SLaks
SLaks

Reputation: 887355

It doesn't make to have a header row.
Tables store data, not presentation.

You should set your columns' Names.

Upvotes: 1

HeimerTown
HeimerTown

Reputation: 55

Look at the DataTable members. http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx

var columnCount = MyTable.Columns.Count;

Upvotes: 0

Related Questions