2017-04-17 106 views
1

我正在尝试使用datagridview进行简单的产品代码搜索。使用多个组合框过滤datagridview

我能够筛选数据库,但没能得到我想要的

功能我现在有它设置为

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    productsBindingSource.Filter = string.Format("Type = '{0}'", 
    comboBox1.SelectedItem.ToString()); 
} 

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    productsBindingSource.Filter = string.Format("Type = '{0}' AND Fitting = '{1}'", 
    comboBox1.SelectedItem.ToString(), 
    comboBox2.SelectedItem.ToString()); 
} 

此代码的作品,但在做出选择后,我改变comboBox1数据重置并且不保留comboBox2的选择。

我在当前的代码明白,这是不会发生的,但我无法弄清楚如何让这种情况发生。

我也想在将来添加一个文本框,并让它更窄的过滤器。

回答

0

你应该多一点的一般处理这个像这样

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    FilterProducts(); 
} 

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    FilterProducts(); 
} 

// Create a function to handle filters 
private void FilterProducts() 
{ 
    string filter = ""; 
    if (comboBox1.SelectedItem != null) 
    { 
     filter += string.Format("Type = '{0}'", comboBox1.SelectedItem.ToString()); 
    } 

    if (comboBox2.SelectedItem != null) 
    { 
     if (filter.length > 0) filter += "AND " 
     filter += string.Format("Fitting = '{0}'", comboBox2.SelectedItem.ToString()); 
    } 

    // Add another like above for your future textbox 
    // if (!string.IsNullOrEmpty(textBox1.Text)) 
    // { 
    //  if (filter.length > 0) filter += "AND " 
    //  filter += string.Format("OtherColumn = '{0}'", textBox1.Text); 
    // } 

    productsBindingSource.Filter = filter; 
} 

的代码可以进一步重构为更好DRY标准,但至少应该让你开始。

+0

谢谢你这个工作就像我想要的 –

+0

很高兴我可以帮助!如果您有时间确保点击向上和向下投票箭头下方的复选框。 –

+0

@AndreTurgeon - 请勾选holo复选框让所有人都回答这个问题。滴答它会给你几个代表点。 –