基于其他值的c#组合框过滤器

时间:2017-01-08 09:24:00

标签: c# combobox

我有2个组合框。txtlocationtxtstep

我静态添加了这些项目。txtlocation的项目是:TO QC TP MAT SUP DCC FIN REC SIG

txtstep项目是:

TO As SUP
TO As PIP
TO  HW
TO  MOD
TO  FSQ
QC HW
QC LC
QC RE
QC TEST
QC PAD
QC WJCS
TP 
MAT NIS
MAT DATA
SUP ASBUILT
SUP REPORT
SUP REPORT/ASBUILT
DCC MONO LC
DCC MONO RE
FIN LC
FIN PAD
FIN TEST
FIN DRY
FIN FL
FIN RE
REC FIN LC
REC FIN  PAD
REC FIN TEST
REC FIN DRY
REC FIN FL
REC FIN RE
SIG LC
SIG PAD
SIG TEST
SIG DRY
SIG FL
SIG RE

我在txtlocation上添加了一个事件(selectedindexchang)。如果用户选择TO 应该过滤TO的步骤。TO As SUP TO As PIP TO HW TO MOD TO FSQ

我应该使用数据源吗?

 private void txtlocation_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

1 个答案:

答案 0 :(得分:1)

不同的数据源可能更清晰,您可以使用Dictionary<TLocation, List<TStep>>将所选值与相应的数据源相关联。

private Dictionary<string, List<string>> _data = new Dictionary<string, List<string>>
{
    { "TO", new List<string> { "TO AS SUP", "TO AS PIP" }},
    { "DCC", new List<string> { "DCC MONO LC", "DCC MONO RE" }},
    { "MAT", new List<string> { "MAT NIS", "MAT DATA" }},
};

comboBoxLocation.DataSource = data.Keys.ToList();

使用SelectedValueChanged eventhandler在位置选择上设置正确的数据源。

private void comboBoxlocation_SelectedValueChanged(object sender, EventArgs e)
{
    var comboBoxLocations = (ComboBox)sender;
    comboBoxSteps.DataSource = _data[comboBoxLocations.SelectedValue.ToString()];
}

如果您只有一个步骤列表,则可以过滤列表并将过滤结果设置为DataSource。

private void comboBoxlocation_SelectedValueChanged(object sender, EventArgs e)
{
    var comboBoxLocations = (ComboBox)sender;
    var selectedLocation = comboBoxLocations.SelectedValue.ToString();
    comboBoxSteps.DataSource = _AllSteps.Where(step => step.StartsWith(selectedLocation))
                                        .ToList();
}

使用这种方法,每次更改位置组合框时都会循环列表。