[英]Save Checked Boxes C#
嗨,我有一個正在制作的表格,該人可以在其中選中復選框以查看他們已經閱讀的內容。 如何保存選中的框,而無需經歷每個復選框的大量循環? (總共有66盒)。
您可以使用Linq優雅地遍歷復選框:
var checkBoxes = Controls.OfType<CheckBox>();
foreach (var chk in checkBoxes)
{
// Save state
}
一種簡單的保存狀態的方法是使用控件名稱作為鍵將選中的狀態放置在Dictionary<string, bool>
。 將字典序列化為文件。
所以,
// Save state
可能看起來像這樣:
Dictionary<string, bool> state = new Dictionary<string, bool>();
var checkBoxes = Controls.OfType<CheckBox>();
foreach (var chk in checkBoxes)
{
if (!state.ContainsKey(chk.Name))
{
state.Add(chk.Name, chk.Checked);
}
else
{
state[chk.Name] = chk.Checked;
}
}
然后,只需使用您喜歡的支持通用詞典的序列化器序列化state
。
充實我的評論,假設所有復選框都位於一個我稱為“父級”的控件(窗體或面板)上。
foreach (CheckBox child in parent.Controls)
{
if (child == null) // Skip children that are not Checkboxes
continue;
// Save the child Checkbox
}
您無法序列化表格。 如果您有一個運行在該類后面的類,則在選中或未選中復選框時跟蹤該類,您可以對其進行序列化。 然后反序列化以重建表格。
您可以使用CheckedListbox 。 並且通過使用CheckedListBox.CheckedItems屬性,您只能獲取選中的項目。
private void WhatIsChecked_Click(object sender, System.EventArgs e) {
// Display in a message box all the items that are checked.
// First show the index and check state of all selected items.
foreach(int indexChecked in checkedListBox1.CheckedIndices) {
// The indexChecked variable contains the index of the item.
MessageBox.Show("Index#: " + indexChecked.ToString() + ", is checked. Checked state is:" +
checkedListBox1.GetItemCheckState(indexChecked).ToString() + ".");
}
// Next show the object title and check state for each item selected.
foreach(object itemChecked in checkedListBox1.CheckedItems) {
// Use the IndexOf method to get the index of an item.
MessageBox.Show("Item with title: \"" + itemChecked.ToString() +
"\", is checked. Checked state is: " +
checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(itemChecked)).ToString() + ".");
}
}
您可以處理CheckBox的CheckedChanged
事件,並相應地更新本地變量(或列表)。 這樣,您將始終知道每個復選框的CheckState
,而不必每次都進行迭代。
CheckBox box = new CheckBox();
box.CheckedChanged += new EventHandler(box_CheckedChanged);
// Event Handler
void box_CheckedChanged(object sender, EventArgs e)
{
if (sender is CheckBox)
{
CheckBox cb = (CheckBox)sender;
bool checkState = cb.Checked;
}
}
希望能幫助到你...!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.