【发布时间】:2020-10-17 17:26:44
【问题描述】:
我收到错误:
“System.ArgumentException:”无法将对象类型“WinForm.Model.EntityModel”转换为类型“System.IConvertible”。无法在 Id 列中保存
问题。
如何解决错误?
代码EntityModel.cs
namespace WinForm.Model
{
class EntityModel
{
public int Id { get; set; }
public string String_Prop { get; set; }
public int Int_Prop { get; set; }
}
}
代码Form1.cs
using System.Windows.Forms;
using WinForm.Model;
using System.Data;
namespace WinForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("String", typeof(string));
dt.Columns.Add("Int", typeof(int));
dt.Rows.Add(new EntityModel { Id = 1, String_Prop = "String_1", Int_Prop = 11 });
dt.Rows.Add(new EntityModel { Id = 2, String_Prop = "String_2", Int_Prop = 12 });
dt.Rows.Add(new EntityModel { Id = 3, String_Prop = "String_3", Int_Prop = 13 });
}
}
}
【问题讨论】:
-
您正在尝试将
EntityModel对象作为一行添加到DataTable中。Rows.Add需要一个DataRow对象或可转换为一个的对象 -
@Flydog57 这样做更好吗?
dt.Rows.Add (1," String_1 ", 11); -
该代码有效吗?