I have comboBox name as cmbContactType. I binded this combo with dataSource as DisplayMember ValueName(string type) and valueMember as ValueID(number type). When user change value in cmbContactType then cmbContactType.SelectValue get set and I am able to save document with this Selectedvalue. I facing problem while setting cmbContactType value from database which is of type number. Every time I am trying to set value, null value set to the cmbContactType.SelectValue.
Following is the code by which I am binding datasource to cmbContactType and for setting SelectedValue of cmbContactType. I am using VS2010 and MS-Access. Please help.
//method to bind dataSource.
public static void BindDataSourceWithCombo(ref ComboBox cmb, string query, string valueMember, string displayMember)
{
DataTable _tableSource = (new AccessConnectionManager()).GetDataTableBySQLQuery(query);
var _dataSource = (from DataRow _row in _tableSource.Rows
select new
{
ValueMember = _row[valueMember],
DisplayMember = _row[displayMember].ToString()
}).ToList();
cmb.DisplayMember = "DisplayMember";
cmb.ValueMember = "ValueMember";
cmb.DataSource = _dataSource;
}
// Method to set values in document.
public void SetDocumentProperties()
{
string _query = string.Format("Select ContactCode,ContactName,ContactType from ContactMaster where ContactCode = '{0}'", Convert.ToString(cmbContactCode.Text));
DataTable _table = AccessConnectionManagers.GetDataTableBySQLQuery(_query);
if (_table.Rows.Count > 0)
{
DataRow _row = _table.Rows[0];
txtContactCode.Text = Convert.ToString(_row["ContactCode"]);
txtContactName.Text = Convert.ToString(_row["ContactName"]);
cmbContactType.SelectedValue = _row["ContactType"];
}
else
{
txtContactCode.Text = string.Empty;
txtContactName.Text = string.Empty;
cmbContactType.SelectedValue = 1;
}
}
Here is code by which I bind dataSource with cmbConactType. This method call on Form_Load event.
private void LoadContactTypeCombo()
{
//Table: PicklistValues(ID,MasterID,ValueID,ValueName)
string _query = string.Format("select ValueID,ValueName from PicklistValues where MasterID = {0}", 1);
BindDataSourceWithCombo(ref cmbContactType, _query, "ValueID", "ValueName");
}
_row["ContactType"]has value. I tried_row["ContactType"] != null ? Convert.ToInt32(_row["ContactType"]) : -1this also. But wasnt work. - Ankush MadankarcmbContactType? - King KingDataSourceto yourcmbContactTypeanywhere in your code. It's important to solve your problem. - King King