2017-04-17 128 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複選框讓所有人都回答這個問題。滴答它會給你幾個代表點。 –