c# - How to rebind datasource to a winform DataGridView Combobox column? -
i have datagridview in winform 2 combo box columns: 1) companies, 2) accounts. want update accounts combo box according selected company. have code:
void recipientsdatagrid_editingcontrolshowing(object sender, datagridvieweditingcontrolshowingeventargs e) { try { combobox cb = e.control combobox; if (cb != null) { cb.selectedvaluechanged -= new eventhandler(companycombobox_selectedvaluechanged); cb.selectedvaluechanged += new eventhandler(companycombobox_selectedvaluechanged); } } catch (exception ex) { } } private void companycombobox_selectedvaluechanged(object sender, eventargs e) { try { var currentcell = recipientsdatagrid.currentcelladdress; if (currentcell.x == 3) { var sendingcb = sender datagridviewcomboboxeditingcontrol; int companyid = sendingcb.selectedvalue.toint(); datatable dtaccounts = m_customersfunctions.getcompanyaccounts(companyid); datagridviewcomboboxcell cboaccounts = (datagridviewcomboboxcell)recipientsdatagrid.rows[currentcell.y].cells["account"]; cboaccounts.valuemember = "account_id"; cboaccounts.displaymember = "accountname"; cboaccounts.datasource = dtaccounts; int defaultaccountid = (from row in dtaccounts.asenumerable() row.field<string>("accountname").endswith("*") select row.field<int>("account_id")).firstordefault(); if (defaultaccountid > 0) cboaccounts.value = defaultaccountid; } } catch (exception ex) { messagebox.show(ex.message); } }
it works fine in first time select company, when change company , try update data source accounts combo box i'm getting error:
i tried add items manualy , not datasource, , got same error. how can fix ? please...
try clear value of accounts cell before rebind it, this:
private void companycombobox_selectedvaluechanged(object sender, eventargs e) { try { var currentcell = recipientsdatagrid.currentcelladdress; if (currentcell.x == 3) { var sendingcb = sender datagridviewcomboboxeditingcontrol; int companyid = sendingcb.selectedvalue.toint(); datatable dtaccounts = m_customersfunctions.getcompanyaccounts(companyid); datagridviewcomboboxcell cboaccounts = (datagridviewcomboboxcell)recipientsdatagrid.rows[currentcell.y].cells["account"]; cboaccounts.value = null; //add code cboaccounts.valuemember = "account_id"; cboaccounts.displaymember = "accountname"; cboaccounts.datasource = dtaccounts; int defaultaccountid = (from row in dtaccounts.asenumerable() row.field<string>("accountname").endswith("*") select row.field<int>("account_id")).firstordefault(); if (defaultaccountid > 0) cboaccounts.value = defaultaccountid; } } catch (exception ex) { messagebox.show(ex.message); } }
Comments
Post a Comment