我有 2 個 Windows 表單。在第一個表單上,我有一個 DataGridView,而在第二個表單上,我只有幾個checkedListBoxes。
我發現這個問題類似于我:
我的想法是你必須在第二個表格上做一些標記,它現在保存你點擊的內容,但我需要在 DGV 的第一個表格上獲得這些點擊。
問題是:如何制作具有兩種形式的過濾器?
uj5u.com熱心網友回復:
您需要的是一種將資料從一個物件發送到另一個物件的方法。有很多可能性,但最干凈的要么是實作觀察者模式,要么利用事件,這是實作觀察者模式的最簡單的形式。
就像您從表單訂閱 Buttons clickevent 一樣,您也可以自己公開事件,并使用相應的 eventargs 將資料發送到訂閱您的事件的任何內容:
public class Form1 // ignore class names it's just to demonstrate =)
{
// ... other code
public void PickTags_Click(object sender, EventArgs args)
{
// i suppose you instanciate the form here...
var filterForm = new FormWithFilters();
filterForm.FilterChanged = OnFilterChanged; // here you subscribe
filterForm.Show();
}
public void OnFilterChanged(object sender, FilterEventArgs args)
{
// ... apply your filter
}
}
public class FormWithFilters
{
// ... other code
public void YourUiHandler(object sender, EventArgs args)
{
// collect the data for the filter
var eventArgs = new FilterEventArgs
{
// assign your Properties for the subscribers to consume
};
FilterChanged?.Invoke(this, eventArgs); // notify subscribers
}
public event EventHandler<FilterEventArgs> FilterChanged; // your very own event
}
public class FilterEventArgs : EventArgs
{
// add whatever properties you need to communicate what has to be filtered...
}
uj5u.com熱心網友回復:
不清楚“何時”要更新表單 1 中的網格。有超過 40 個選項供用戶選擇,那么我認為當用戶單擊表單 2 上的“確定”按鈕時,您會更新網格。在這種情況下,您可以使用ShowDialogfor 表單 2,并且在表單 2 關閉后,您的代碼應該仍然能夠獲取表單 2 中的任何“公共”變數。因此,如果您將CheckListBox表單 2 中的(s)設為“公開”,那么您可以在下面的表格 1 中檢查它們。
private void buttonToOpenForm2_Click(object sender, EventArgs e) {
Form2 f2 = new Form2();
f2.ShowDialog();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Checked Options are: ... ");
for (int i = 0; i < f2.checkedListBox1.Items.Count; i ) {
sb.AppendLine("Option: " f2.checkedListBox1.Items[i].ToString());
sb.AppendLine(" " (f2.checkedListBox1.GetItemChecked(i) ? " Is" : "Is Not") " Checked");
}
textBox1.Text = sb.ToString();
}

顯然,如果表單 2 沒有將CheckedListBoxes公開,那么您將無法在表單 1 中看到它們。在表單 2 的設計器中……選擇CheckListBox(s) 并將Modifier屬性更改為true。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344730.html
