我的组合框名称为cmbContactType
. 我将此组合与 dataSource 绑定为 DisplayMember ValueName
(字符串类型)和 valueMember 作为ValueID
(数字类型)。当用户更改 cmbContactType 中的值时,然后 cmbContactType.SelectValue 被设置,我可以使用此 Selectedvalue 保存文档。我在从类型为编号的数据库中设置 cmbContactType 值时遇到问题。每次我尝试设置值时,将null
值设置为cmbContactType.SelectValue
. 以下是我将数据源绑定到cmbContactType
并设置 SelectedValue 的代码cmbContactType
。我正在使用 VS2010 和 MS-Access。请帮忙。
//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;
}
}
这是我将 dataSource 与 cmbConactType 绑定的代码。此方法调用 Form_Load 事件。
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");
}