【发布时间】:2010-07-27 01:48:21
【问题描述】:
我正在尝试将我的数据表库存表绑定到数据网格查看器。代码中的问题是当它编译时,它说“make”列不属于该表,但我在代码中按如下方式创建列:
public partial class Form1 : Form
{
List<Car> listCars = new List<Car>();
DataTable inventorytable=new DataTable();
public Form1()
{
InitializeComponent();
listCars.Add(new Car("Chucky", "BMW", "Green"));
listCars.Add(new Car("Tiny", "Yugo", "White"));
listCars.Add(new Car("Ami", "Jeep", "Tan"));
listCars.Add(new Car("Pain Inducer", "Caravan", "Pink"));
listCars.Add(new Car("Fred", "BMW", "Pea Soup Green"));
listCars.Add(new Car("Sidd", "BMW", "Black"));
listCars.Add(new Car("Mel", "Firebird", "Red"));
listCars.Add(new Car("Sarah", "Colt", "Black"));
createdatatable();
}
void createdatatable()//create data table schema
{
DataColumn carmake = new DataColumn("make", typeof(string));
DataColumn carcolor = new DataColumn("color", typeof(string));
DataColumn carpetname = new DataColumn("petname", typeof(string));
foreach (Car c in listCars)
{
DataRow dr = inventorytable.NewRow();
**dr["make"] = c.carMake;**//column 'make' does not belong to the table.
dr["color"] = c.carColor;
dr["petname"] = c.carPetName;
inventorytable.Rows.Add(dr);
}
dataGridView1.DataSource = inventorytable;//binds data table to the grid view
}
}
}
我还在这个表单中添加了一个名为 car 的类,其代码如下:
class Car
{
public string carPetName { get; set; }
public string carMake { get; set; }
public string carColor { get; set; }
public Car(string petname, string make, string color)
{
carPetName = petname;
carMake = make;
carColor = color;
}
请帮忙!!!!!!!!!附言(我把声明写成
DataTable inventorytable=new DataTable();
因为当我把它写成DataTable inventorytable 时,它给出了一个例外
“对象引用未设置为对象的实例”。)
【问题讨论】: