无法将类型为"System.Data.DataColumn"的对象转换为类型为"System.IConvertible"的对象 [英] Unable to cast object of type 'System.Data.DataColumn' to type 'System.IConvertible'

查看:61
本文介绍了无法将类型为"System.Data.DataColumn"的对象转换为类型为"System.IConvertible"的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to save a record from a query into a DataRow, but did not make it. I could need some help. This my code:

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

推荐答案

您可以直接将 DataAdapter 用于

You can use the DataAdapter directly to load a DataTable:

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

我认为上面的其余代码是多余的.

The rest of the code above is redundant in my opinion.

旁注:之所以会出现异常,是因为要将记录的字段传递给DataRow的字段.但是实际上您正在传递 DataColumn .

Side-note: You're getting the exception because you want to pass a field of a record to a DataRow's field. But actually you're passing the DataColumn.

这可以工作,但不是必需的:

This would work but is unnecessary:

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

其中 sdr 是您的 DataReader .

这篇关于无法将类型为"System.Data.DataColumn"的对象转换为类型为"System.IConvertible"的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆