日期:2014-05-18  浏览次数:21072 次

datatable创建行,并为行赋值(列已固定)
如题,我在尝试为新建行赋值时失败,不提示错误,就是无法赋值
DataRow dr = dt.NewRow();
  dr["要素类型"] = GElist[i].ElName;
  dt.Rows.Add(dr);
等号右边的值是“线”,结果得到的单元格的值是“要素类型”……
疯了……

------解决方案--------------------
private void showData()
 3 {
 4 DataTable dt = new DataTable("OneEmployee");
 5 dt.Columns.Add("Caption", System.Type.GetType("System.String"));
 6 dt.Columns.Add("Department", System.Type.GetType("System.String"));
 8
 9 DataRow dr = dt.NewRow();
10 dr["Caption"] = list[i].Name;
11 dr["Department"] = list[i].Department;
14 dt.Rows.Add(dr);
15
17 }
------解决方案--------------------
FROM MSDN:

C# code

private void CreateNewDataRow()
{
    // Use the MakeTable function below to create a new table.
    DataTable table;
    table = MakeNamesTable();

    // Once a table has been created, use the 
    // NewRow to create a DataRow.
    DataRow row;
    row = table.NewRow();

    // Then add the new row to the collection.
    row["fName"] = "John";
    row["lName"] = "Smith";
    table.Rows.Add(row);

    foreach(DataColumn column in table.Columns)
        Console.WriteLine(column.ColumnName);
    dataGrid1.DataSource=table;
}

private DataTable MakeNamesTable()
{
    // Create a new DataTable titled 'Names.'
    DataTable namesTable = new DataTable("Names"); 

    // Add three column objects to the table.
    DataColumn idColumn = new  DataColumn();
    idColumn.DataType = System.Type.GetType("System.Int32");
    idColumn.ColumnName = "id";
    idColumn.AutoIncrement = true;
    namesTable.Columns.Add(idColumn);

    DataColumn fNameColumn = new DataColumn();
    fNameColumn.DataType = System.Type.GetType("System.String");
    fNameColumn.ColumnName = "Fname";
    fNameColumn.DefaultValue = "Fname";
    namesTable.Columns.Add(fNameColumn);

    DataColumn lNameColumn = new DataColumn();
    lNameColumn.DataType = System.Type.GetType("System.String");
    lNameColumn.ColumnName = "LName";
    namesTable.Columns.Add(lNameColumn);

    // Create an array for DataColumn objects.
    DataColumn [] keys = new DataColumn [1];
    keys[0] = idColumn;
    namesTable.PrimaryKey = keys;

    // Return the new DataTable.
    return namesTable;
}

------解决方案--------------------
C# code

  DataRow dr = dt.NewRow();
  dr["要素类型"] = GElist[i].ElName;//你确定这里的值是“线”?
  dt.Rows.Add(dr);