也许将每个选中项的标识符保存到 json 文件中。
在下面我对 CheckedListBox 所做的事情中,对于多个 CheckedListBox 控件,您需要调整代码以使用一个具有修改结构的 json 文件来处理多个 CheckedListBox 控件或每个 CheckedListBox 一个 json 文件。
例如,将项目加载到以下类中
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public override string ToString()
{
return ProductName;
}
}
使用以下类读取/写入 json 文件,在本例中使用 json.net,但也可以使用 system.text.json。
public class JsonOperations
{
/// <summary>
/// In your app you need to setup a different file name for each CheckedListBox
/// </summary>
public static string FileName =>
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Checked.json");
/// <summary>
/// Save only checked products
/// </summary>
/// <param name="list"></param>
public static void Save(List<ProductItem> list)
{
string json = JsonConvert.SerializeObject(list, Formatting.Indented);
File.WriteAllText(FileName, json);
}
/// <summary>
/// Read back if file exists
/// </summary>
/// <returns></returns>
public static List<ProductItem> Read()
{
List<ProductItem> list = new List<ProductItem>();
if (File.Exists(FileName))
{
list = JsonConvert.DeserializeObject<List<ProductItem>>(File.ReadAllText(FileName));
}
return list;
}
}
以下类提供了从上面提到的json中获取选中项设置选中项的方法。
public static class CheckedListBoxExtensions
{
public static List<ProductItem> IndexList(this CheckedListBox sender)
{
return
(
from item in sender.Items.Cast<Product>()
.Select(
(data, index) =>
new ProductItem()
{
ProductID = data.ProductID,
Index = index
}
)
.Where((x) => sender.GetItemChecked(x.Index))
select item
).ToList();
}
public static void SetChecked(this CheckedListBox sender, int identifier, bool checkedState = true)
{
var result = sender.Items.Cast<Product>()
.Select((item, index) => new CheckItem
{
Product = item,
Index = index
})
.FirstOrDefault(@this => @this.Product.ProductID == identifier);
if (result != null)
{
sender.SetItemChecked(result.Index, checkedState);
}
}
}
公共类 CheckItem
{
公共产品产品 { 获取;放; }
公共 int 索引 { 获取;放; }
}
表单代码将类似于以下内容,以读取表单显示事件中的选中项并保存表单关闭事件中的选中项。
public partial class SaveItemsForm : Form
{
private List<Product> _products = new List<Product>();
public SaveItemsForm()
{
InitializeComponent();
Shown += OnShown;
Closing += OnClosing;
}
private void OnClosing(object sender, CancelEventArgs e)
{
List<ProductItem> checkedItems = ProductCheckedListBox.IndexList();
if (checkedItems.Count > 0)
{
JsonOperations.Save(checkedItems);
}
else
{
JsonOperations.Save(new List<ProductItem>());
}
}
private void OnShown(object sender, EventArgs e)
{
_products = SqlServerOperations.ProductsByCategoryIdentifier(1);
ProductCheckedListBox.DataSource = _products;
/*
* Search for each product by id, if in the CheckedListBox check it
*/
var items = JsonOperations.Read();
if (items.Count >0 )
{
items.ForEach( x => ProductCheckedListBox.SetChecked(x.ProductID));
}
}
}