c# - How to fill DataGridView from two tables with ComboBox -
i have 2 next tables:
| part_id | name |part_type| |----------|---------|---------| | 1 | abc | nut | | 2 | def | nut | | 3 | ghi | washer | | type | |----------| | nut | | screw | | washer |
how can fill datagridview this:
| part_id | name | part_type | |----------|---------|-------------------| | 1 | abc | nut(combobox) | | 2 | def | nut(combobox) | | 3 | ghi | washer(combobox) |
with combobox every type on part_type column, user may alter type of specific part?
this have:
string mycmdtext = "select * parts"; mysqlcommand myquery = new mysqlcommand(mycmdtext, myconnection); using (mysqldataadapter myadapter = new mysqldataadapter(myquery)) { dataset ds = new dataset(); myadapter.fill(ds); mydatagridview.datasource = ds.tables[0]; }
i tried casting part_type field cells of datagridview comboboxcells , adding missing part types manually, i'm getting invalidcastexception.
is there way this, preferably easier 1 tried?
to utilize dropdown cell type need 2 things:
create cells of typedatagridviewcomboboxcell
fill them appropriate data creating drop downwards cells:
you have either create columns
types want them in code, instead of using automatic column generation. set mydatagridview.autogeneratecolumns = false;
needs done before issuing query, since can't alter column type later.
but there workaround: later changing type have exchange each cell
want special, against cell of type want. note: cells, not columns, need loop on rows, in code below!
filling them appropriate data:
you can a) utilize databinding:
setdatasource
comboboxcells, query 2nd table; set them select distinct first query result or other source.. set displaymember
& valuemember
(in case same field.) or b) fill items
collection unbound data.
you can utilize this:
string mycmdtext = "select * parts"; string mycmdtext2 = "select * types"; int yourdropdownindex = 2; mysqlcommand myquery = new mysqlcommand(mycmdtext, myconnection); mysqlcommand myquery2 = new mysqlcommand(mycmdtext2, myconnection); using (mysqldataadapter myadapter = new mysqldataadapter(myquery)) using (mysqldataadapter myadapter2 = new mysqldataadapter(myquery2)) { dataset ds = new dataset(); datatable dt2 = new datatable(); myadapter.fill(ds); myadapter2.fill(dt2); ds.tables.add(dt2); mydatagridview.datasource = ds.tables[0]; foreach (datagridviewrow row in mydatagridview.rows) { var temp = row.cells[yourdropdownindex].value; datagridviewcomboboxcell combocell = new datagridviewcomboboxcell(); combocell.displaymember = "type"; combocell.valuemember = "type"; combocell.datasource = ds.tables[1]; row.cells[yourdropdownindex] = combocell; row.cells[yourdropdownindex].value = temp; } }
if necessary can cast single cell
datagridviewcomboboxcell
:
int ddlcount = ((datagridviewcomboboxcell) mydatagridview.rows[row].cells[yourdropdownindex]).items.count;
you may want declare dataset ds
@ class level..
c# datagridview
No comments:
Post a Comment