如何在c#数据表中命名行?

时间:2013-09-16 16:52:48

标签: c# datatable

我有一个DataTable,我以编程方式添加列(因此,没有一定数量的列):

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

然后我将空行添加到表中以获取数据:

MyTable.Rows.Add(0);       

我想添加行标签,例如“价格”,“数量”,“出价”等 如果我按照我知道的方式添加这些,我需要知道我们将拥有的列数

如何将此代码编码为更强大,其中列数不是静态的? 感谢

3 个答案:

答案 0 :(得分:1)

没有标题行 表存储数据,而不是表示。

您应该将列设置为Name s。

答案 1 :(得分:0)

您可以访问Columns集合中的列。

我将使用字符串列表演示itteration:

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

请注意,该列表的列price为两次,但只会添加一次。

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

答案 2 :(得分:0)

查看DataTable成员。 http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx

var columnCount = MyTable.Columns.Count;
相关问题