如何动态地将列和行添加到空数据集中?

时间:2011-04-19 06:36:54

标签: c# asp.net dataset

我创建了一个新的数据集

DataSet local_ds2 = new DataSet();

我试过这个动态添加行和列

DataColumn dcAmount = new DataColumn("EmpID");
    local_ds2.Tables["ACHFile"].Columns.Add(dcAmount);

    DataColumn dcName = new DataColumn("Name");
    local_ds2.Tables["ACHFile"].Columns.Add(dcName);

    DataColumn dcBnkRoutingNumber = new DataColumn("BankRoutingNumber");
    local_ds2.Tables["ACHFile"].Columns.Add(dcBnkRoutingNumber);

    DataColumn dcBnkAccount = new DataColumn("BankAccount");
    local_ds2.Tables["ACHFile"].Columns.Add(dcBnkAccount);

    DataColumn dc = new DataColumn("Amount");
    local_ds2.Tables["ACHFile"].Columns.Add(dc);

    DataColumn dc1 = new DataColumn("BankAccountTypeID");
    local_ds2.Tables["ACHFile"].Columns.Add(dc1);

    for (int i = 0; i < chkcnt; i++)
    {
        local_ds2.Tables["ACHFile"].Rows[i]["EmpID"] = EmpID[i];
        local_ds2.Tables["ACHFile"].Rows[i]["Name"] = Empname[i];
        local_ds2.Tables["ACHFile"].Rows[i]["BankRoutingNumber"] = BnkRoutingNumber[i];
        local_ds2.Tables["ACHFile"].Rows[i]["BankAccount"] = BnkAccount[i];
        local_ds2.Tables["ACHFile"].Rows[i]["BankAccountTypeID"] = AchDB.strBankTypeID[i];
        local_ds2.Tables["ACHFile"].Rows[i]["Amount"] = AchDB.Amount1[i];
        if (AchDB.strBankTypeID[i].ToString() == "D")
            strBankAccntType = "BankAccountTypeID='" + AchDB.strBankTypeID[i].ToString() + "'";
    }

但我无法动态添加列和行,任何人都可以帮助我

3 个答案:

答案 0 :(得分:3)

尝试将代码更改为此

DataRow dr;        

for (int i = 0; i < chkcnt; i++)
        {
            dr = local_ds2.Tables["ACHFile"].NewRow();
            dr["EmpID"] = EmpID[i];
            dr["Name"] = Empname[i];
            dr["BankRoutingNumber"] = BnkRoutingNumber[i];
            dr["BankAccount"] = BnkAccount[i];
            dr["BankAccountTypeID"] = AchDB.strBankTypeID[i];
            dr["Amount"] = AchDB.Amount1[i];
            if (AchDB.strBankTypeID[i].ToString() == "D")
                strBankAccntType = "BankAccountTypeID='" + AchDB.strBankTypeID[i].ToString() + "'";
            local_ds2.Tables["ACHFile"].Rows.Add(dr);
        }

您没有将行添加到Datatable

答案 1 :(得分:2)

应该像......

        DataRow myRow;
        DataTable ACHFile = new DataTable();
        DataColumn EmpID = new DataColumn("EmpID", System.Type.GetType("System.String"));
        ACHFile.Columns.Add(EmpID );

    for (int i = 0; i < chkcnt; i++)
    {
        myRow = ACHFile.NewRow();
        myRow["EmpID"] = EmpID[i];
        ACHFile.Rows.Add(myRow);
.......
    }

答案 2 :(得分:0)

尝试将datacolums放在tablerow中,然后将tablerow添加到表中。现在看起来你正在向表中添加一个列,跳过行的步骤