0

我试图将查询中的记录保存到 中DataRow,但没有成功。我可能需要一些帮助。这是我的代码:

private DataSet CreateDataSet()
{
    DataSet ds = new DataSet();

    // create Countries table and columns
    DataTable dtApplications = ds.Tables.Add("Applications");
    DataColumn dtApplicationID = dtApplications.Columns.Add("ApplicationID", typeof(int));
    DataColumn dtApplicationName= dtApplications.Columns.Add("ApplicationName", typeof(string));

    DataTable dt = new DataTable();
    SqlConnection con = new SqlConnection(MoahannedConnectionString);
    SqlCommand cmd1 = new SqlCommand("select AppID,AppName from Application", con);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlDataReader sdr = null;
    dt.TableName = "Application";
    con.Open();
    sdr = cmd1.ExecuteReader();
    while (sdr.Read())
    {
       AddDataToTable(dtApplicationID, dtApplicationName, dtApplications, ds);
    }
}

private void AddDataToTable(DataColumn ID, DataColumn Name, DataTable myTable,DataSet ds)
{
    DataRow row;
    row = myTable.NewRow();
    row["ApplicationID"] = ID;
    row["ApplicationName"] = Name;
    myTable.Rows.Add(row);
}
4

1 回答 1

0

您可以使用DataAdapter直接加载DataTable

using(var da = new SqlDataAdapter("select AppID,AppName from Application", con))
{
    da.Fill(dt);
}

在我看来,上面的其余代码是多余的。

旁注:您遇到异常是因为您想将记录的字段传递给 DataRow 的字段。但实际上你正在通过DataColumn.

这会起作用,但没有必要:

row["ApplicationID"] = sdr.GetInt32(sdr.GetOrdinal("ApplicationID"));
row["ApplicationName"] = sdr.GetString(sdr.GetOrdinal("ApplicationName"));

sdrDataReader.

于 2012-09-09T10:58:56.793 回答