简体   繁体   中英

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

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

You should set your columns' Name s.

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; 
}

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

var columnCount = MyTable.Columns.Count;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM