如何根据checklistbox c#中各自的复选框从列表返回项?



我已经从另一个答案中获得了我的第一个c#应用程序的进展,但我仍然无法理解下一部分。

我有一个JSON文件,其中包含我的数据数组。我的应用程序从包含数组的JSON文件中获取信息,并使用"name"填充我的checkedlistbox1。每个发现。当您单击checklistbox1(不是check)中的任何项时,它会显示相邻richtextbox1中特定的查找信息(名称、风险、描述、推荐定义为"completefinding")。这些都很好。

我现在要做的是抓住在我的checkedlistbox1中选中的任何项目' CompleteFinding,并做我想做的事情,即一个变量或要在文本框中引用的东西,或者当Button1被点击等后输出到其他地方。我试着使用"checkedlistbox1. selecteitems"并且我得到一个关于转换到我的发现类型的错误。我还尝试使用foreach循环,它只返回检查的最后一项。我需要每个检查项目的CompleteFinding使用时,单击Button1。

JSON文件示例内容:
[
{
"Name": "Test Name 1",
"Risk": "Low",
"Details": "Detailed description",
"Recommendation": "Recommended action"
},
{
"Name": "Test Name 2",
"Risk": "Low",
"Details": "Detailed description",
"Recommendation": "Recommended action"
}
]

代码
public partial class Form1 : Form
{
public class Findings
{
[JsonProperty("Name")]
public string Name { get; set; }

[JsonProperty("Risk")]
public string Risk { get; set; }
[JsonProperty("Details")]
public string Details { get; set; }
[JsonProperty("Recommendation")]
public string Recommendation { get; set; }

public string CompleteFinding
{
get
{
return "Name:" + "n" + Name + "n" + "n" + "Risk:" + "n" + Risk + "n" + "n" + "Details:" + "n" + Details + "n" + "n" + "Recommendation:" + Recommendation + "n";
}
}
}

public Form1()
{
InitializeComponent();
var json = JsonConvert.DeserializeObject<List<Findings>>(File.ReadAllText(@"findings-array.json"));
checkedListBox1.DataSource = json;
checkedListBox1.DisplayMember = "Name";
}
private void Button1_Click(object sender, System.EventArgs e)
{
//would like to be able to use the CompleteFinding of each checkeditem here.
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//This populates a single Finding's CompleteFinding to the richtextbox.
richTextBox1.Text = ((Findings)checkedListBox1.SelectedItem).CompleteFinding;
}
}

也许是这样的?

private void Button1_Click(object sender, System.EventArgs e) {
richTextBox1.Text = null; // clear out your results first
var sb = new StringBuilder();
foreach (var item in checkedListBox1.SelectedItems) {
var selected = (Findings)item;
sb.AppendLine(selected.CompleteFinding);
sb.AppendLine(); // adds a blank line
}
richTextBox1.Text = sb.ToString();
}

从你下面的评论,听起来像你的ListView使用物理复选框。这可能是你在最初的问题中应该提到的。

编写代码,使其只查看ListViewItems有复选标记的,用这样的格式:

private void Button1_Click(object sender, System.EventArgs e) {
richTextBox1.Text = null; // clear out your results first
var sb = new StringBuilder();
foreach (ListViewItem item in checkedListBox1.Items) {
if (item.Checked) {
var find = item.Tag as Finding;
if (find != null) {
sb.AppendLine(find.CompleteFinding);
sb.AppendLine(); // adds a blank line
}
}
}
richTextBox1.Text = sb.ToString();
}

我不知道JSON如何附加到单个ListViewItems。在上面的代码中,我展示了它从标签提取数据字段,但只有你把它写在那里,它才会在那里。写代码的方法有很多。

我一直假设这是一个基本的Windows窗体应用程序。ListView控件与Web应用程序可用的控件不同。