【发布时间】:2021-02-12 23:44:48
【问题描述】:
我在另一个答案中的第一个 C# 应用程序上取得了进展,但我仍然无法理解下一部分。
我有一个 JSON 文件,其中包含一个包含我的数据的数组。我的应用程序从包含数组的 JSON 文件中获取信息,并使用每个结果的“名称”填充我的 checklistbox1。当您单击选中列表框1 中的任何项目(未选中)时,它会在相邻的富文本框1 中显示特定结果的信息(名称、风险、描述、定义为“CompleteFinding”的推荐)。这一切都很棒。
我现在要做的是获取在我的checkedlistbox1 中选中的任何项目的CompleteFinding 并用它做我想做的事情,即变量或要在文本框中引用的东西,或者稍后在单击Button1 时在其他地方输出等等。我尝试使用“checkedlistbox1.SelectedItems”并收到关于转换为我的结果类型的错误。我还尝试使用 foreach 循环,它只返回检查的最后一项。我需要在单击 Button1 时使用每个选中项目的 CompleteFinding。
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;
}
}
【问题讨论】:
标签: c#