c# - Problem creating datatable via code and binding to a datagridview -
i trying bind data table inventorytable datagrid viewer.the problem in code when compiles,it says column"make" not belong table make column in code follows:
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' not belong table. dr["color"] = c.carcolor; dr["petname"] = c.carpetname; inventorytable.rows.add(dr); } datagridview1.datasource = inventorytable;//binds data table grid view } } }
i have added class form named car code follows:
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; }
please help!!!!!!!! p.s. (i wrote statement
datatable inventorytable=new datatable();
because when wrote datatable inventorytable
, giving exception "object refence not set instance of object ".)
you need following:
datacolumn carmake = new datacolumn("make", typeof(string)); datacolumn carcolor = new datacolumn("color", typeof(string)); datacolumn carpetname = new datacolumn("petname", typeof(string)); // missing part: inventorytable.columns.add(carmake); inventorytable.columns.add(carcolor); inventorytable.columns.add(carpetname);
you forgot add columns table when create row, has no columns in , code fails column name lookup.
Comments
Post a Comment