我正在构建一个程序,允许我通过从一组Trips中选择数据来提取数据,并将所有找到的项目作为该Trip的一部分填充到列表框中。当我从列表框中选择一个项目时,我希望它填充一系列允许我编辑每个字段的文本框。
这是我的问题代码在Form中的位置(tripChoose是组合框,listExpenses是列表框):
private void tripChoose_SelectedIndexChanged(object sender, EventArgs e)
{
IEnumerable<TripExpense> selectedExpenses = roster.ToFind((string)tripChoose.SelectedItem);
foreach (TripExpense item in selectedExpenses)
listExpenses.Items.Add(item);
}
private void listExpenses_SelectedIndexChanged(object sender, EventArgs e)
{
specificExpenses = (TripExpense)roster.TripFind((string)listExpenses.SelectedItem);
tripTextBox.Text = specificExpenses.Trip;
tripTextBox.Enabled = false;
descriptionTextBox.Text = specificExpenses.Description;
amountTextBox.Text = specificExpenses.Amount.ToString();
paymentMethodTextBox.Text = specificExpenses.PaymentMethod;
dateExpenseTimePicker.Value = specificExpenses.Date;
dateExpenseTimePicker.Enabled = true;
noteTextBox.Text = specificExpenses.Note;
}
JIT调试器让我知道我隐式地将对象转换为字符串
我尝试过使用像这样的ToString方法:
private void tripChoose_SelectedIndexChanged(object sender, EventArgs e)
{
IEnumerable<TripExpense> selectedExpenses = roster.ToFind((string)tripChoose.SelectedItem);
foreach (TripExpense item in selectedExpenses)
listExpenses.Items.Add(item.ToString());
}
我认为我在那里正确,因为我收到错误告诉我对象引用没有设置为对象的实例。
答案 0 :(得分:1)
我认为问题是在ToString()
中实施TripExpense
方法。当您使用该字符串并将其输入FindTrip
时,它将无法再找到它。
您可以做的是获得组合项目的原始设置并修改SelectedIndexChanged
而不是
private void tripChoose_SelectedIndexChanged(object sender, EventArgs e)
{
IEnumerable<TripExpense> selectedExpenses = roster.ToFind((string)tripChoose.SelectedItem);
foreach (TripExpense item in selectedExpenses)
listExpenses.Items.Add(item);
}
private void listExpenses_SelectedIndexChanged(object sender, EventArgs e)
{
specificExpenses = (TripExpense)listExpenses.SelectedItem;
...
}
这样,ComboBox文本仍会抓取ToString()
对象的TripExpense
,但您仍然可以从SelectedItem
获取实际对象而不是尝试重新查询对象。