无法将“System.Data.DataColumn”类型的对象强制转换为“System.IConvertible”类型

时间:2012-09-09 10:55:12

标签: c# ado.net

我尝试将查询中的记录保存到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);
}

1 个答案:

答案 0 :(得分:0)

您可以DataAdapter直接使用load a 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