Reputation: 39
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
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
Reputation: 887355
It doesn't make to have a header row.
Tables store data, not presentation.
You should set your columns' Name
s.
Upvotes: 1
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