gpt4 book ai didi

c# - ComboBox 的 SelectedValue 未设置

转载 作者:行者123 更新时间:2023-12-02 17:43:06 25 4
gpt4 key购买 nike

我的组合框名称为 cmbContactType。我将此组合与数据源绑定(bind)为 DisplayMember ValueName(字符串类型),将 valueMember 绑定(bind)为 ValueID(数字类型)。当用户更改 cmbContactType 中的值时,会设置 cmbContactType.SelectValue,我可以使用此 Selectedvalue 保存文档。我在从类型为数字的数据库中设置 cmbContactType 值时遇到问题。每次我尝试设置值时,null 值都设置为 cmbContactType.SelectValue。以下是我将数据源绑定(bind)到 cmbContactType 并设置 cmbContactType 的 SelectedValue 的代码。我正在使用 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 绑定(bind)的代码。此方法调用 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");
}

最佳答案

用这个方法试试

int index;
// Search the Item that matches the string
index=cmbContactType.FindString(_row["ContactType"]);
// Select the Item in the Combo
cmbContactType.SelectedIndex=index;

关于c# - ComboBox 的 SelectedValue 未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18119624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com