在下拉框,但第一个相同的两个项目始终被选中C# [英] Same two items in combobox but first one always gets selected C#

查看:94
本文介绍了在下拉框,但第一个相同的两个项目始终被选中C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Windows窗体应用程序我有很奇怪的问题,组合框。

I've got really weird problem with combobox on my windows form application.

所以我的组合框使用数据源填充,它会显示人的名字和其持有的。ID作为cmbRequestor.ValueMember

So my combobox is populated using datasource, it displays names of people and it holds their IDs as cmbRequestor.ValueMember.

public BindingSource requestorBindingSource = null;
private const string cmdAssoc = "SELECT * FROM assoc_vw ORDER BY assoc_name";
requestorBindingSource.DataSource = populateDataTable(cmdAssoc);

cmbRequestor.DisplayMember = "assoc_name";
        cmbRequestor.ValueMember = "ID";
        cmbRequestor.DataSource = requestorBindingSource;
        cmbRequestor.SelectedIndex = 0;



在这里输入的形象描述

它工作正常,但如果有一人具有相同名称的实例,我选择第二名称(同名)从ComboBox,由于某种原因,一旦我关闭该组合框,它选择,即使我选择了第2名的第一个名字

It works fine but if there is an instance of people with the same name and I select 2nd name (of the same name) from the combobox, for some reason once I close the combobox it selects the first name even though I selected 2nd name.

所以,以确保他们对他们的名字我已经创建SelectedIndexChanged事件持不同的价值观

So to make sure they hold different values against their names I have created SelectedIndexChanged event.

private void cmbRequestor_SelectedIndexChanged(object sender, EventArgs e)
    {
        int x = cmbRequestor.SelectedIndex;
        string j = cmbRequestor.SelectedValue.ToString();
        var y = cmbRequestor.Items[x];
    }

当我调试的代码,我选择第二名称(同名)其背后的ID是3069.一旦我关闭该组合框,然后点击保存,保存的SelectedIndexChanged再次触发的形式(即不应该发生),并转到第一人具有相同的名称和它的ID是不同的。

When I debug the code and I select 2nd name (of the same name) the ID behind it is 3069. Once I close the combobox and click save to save the form SelectedIndexChanged is triggered again (that should not happen) and it goes to the first person with the same name and its ID is different.

有此控件不再对其他事件,我不使用其他任何地方。它看起来像控制会很困惑,如果本身有相同名称的一个实例。

There are no other events on this control and I dont use it anywhere else. It looks like the control gets confused itself if there is an instance of the same name.

推荐答案

更改DropDownStyle属性为DropDownList。结果,标准值是下拉并在这种情况下,选择的项目将在列表中的第一匹配的文本来确定。下拉主要是配合使用的自动完成逻辑搜索结果
编辑:结果
如果你坚持使用下拉式的,最好的解决办法将是处理DropDownClosed事件,在这一点上,你将不得不选择正确的索引。

Change DropDownStyle property to DropDownList.
Default value is DropDown and in that case selected item will be determined by the first matched text in the list. DropDown is mainly used in conjunction with autocomplete logics.


If you have to stick with DropDown style, the best workaround will be to handle DropDownClosed event, at that point you will have the correct index selected.

这篇关于在下拉框,但第一个相同的两个项目始终被选中C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆