当出现新表单时,如何保存/记住组合框中的选择
本文关键字:保存 选择 组合 新表单 表单 何保存 | 更新日期: 2023-09-27 17:56:07
假设有一个Winform允许用户使用组合框回答问题。 选择答案后,他们可以单击"下一步"并查看一个新问题以及一个新的组合框以选择他们的答案。
如何保存上一页的答案,以便按下"上一个",之前选择的相同答案仍将填充该组合框?
编辑:我对你的例子遇到的问题是这两个。 "无法解析符号组合框 1"
comboBox1.SelectedIndexChanged += SelectedAnswerChanged;
question.SelectedChoice = (AnswerChoice)comboBox1.SelectedItem;
这是你需要做的
将问题类别更改为:
public class Questions
{
public string QuestionType { get; set; }
public string QuestionText { get; set; }
public Choice[] Choice { get; set; }
public Choice SelectedChoice { get; set; }
}
这将向其添加一个Choice
对象,从而允许我们保存用户从 ComboBox 中选择的Choice
将 AnswerChoice 类更改为:
public class AnswerChoice
{
public string AnswerText { get; set; }
public Questions Question { get; set; }
public override void ToString() {
return AnswerText;
}
}
这只是在 ToString 方法上添加重写。这样做允许我们将实际对象添加到组合框,而不仅仅是答案文本。这给了它一个更加面向对象的方法,并允许我们在问题的SelectedChoice
保存对该对象的引用。如果我们添加的对象而不使用 override ToString 方法,那么组合框将显示类似System.Namespace.ClassHere.AnswerChoice
将 ComboBoxControl 类更改为:
public partial class ComboBoxControl : UserControl
{
public ComboBoxControl(Questions question)
{
InitializeComponent();
label1.Text = question.QuestionText;
Choice[] choices = question.Choice;
foreach (var ch in choices)
{
comboBox1.Items.Add(ch.AnswerChoice);
if (ch.IsDefault)
{
comboBox1.Text = ch.AnswerChoice;
}
}
// load the saved answer if it exists
if (question.SelectedChoice != null) {
comboBox1.Text = string.Empty // not sure if this is needed or not
comboBox1.SelectedItem = question.SelectedChoice;
}
}
}
这里更改了两件事:
- 我们没有添加
ch.AnswerChoice.AnswerText
而是添加了实际的AnswerChoice
对象,从而允许我们保存对实际对象的引用以供以后使用 - 每当加载问题时,它都会检查
SelectedChoice
属性是否为 null。如果不是,则它将该对象(已加载)设置为SelectedItem
在 SurveyView 表单中添加此方法:
private void SelectedAnswerChanged(object sender, EventArgs e) {
Questions question = _presenter.GetQuestion(questionNumber);
question.SelectedChoice = (Choice)((ComboBox)sender).SelectedItem;
}
这是我们稍后将与我们创建的 ComboBox 上的 SelectedIndexChanged
事件相关联的方法。这将保存用户选择的选项。
将 DisplayQuestion() 方法更改为:
private void DisplayQuestion(int questionNumber)
{
var qNumber = _presenter.GetQuestion(questionNumber);
if (string.Equals(qNumber.QuestionType, "ComboBoxControl"))
{
controlPanel.Controls.Clear();
var comboBox = new ComboBoxControl(qNumber);
comboBox.Dock = DockStyle.Fill;
comboBox.SelectedIndexChanged += SelectedAnswerChanged;
controlPanel.Controls.Add(comboBox);
}
}
这只是将我们刚刚放入 SurveryView 窗体中的 SelectedAnswerChanged 方法与我们创建的 ComboBox 上的 SelectedIndexChanged 事件联系起来。