user1350264
user1350264

Reputation: 39

Cast string from a list box to separate text fields

I'm building a program that would allow me to pull data from by selecting it from a group of Trips, and populate all found items as part of that Trip into a listbox. When I select an item from the listbox, I want it to populate a series of textboxes that allow me to edit each field.

Here's where my problem code lies within the Form (tripChoose is the combo box and listExpenses is the list box):

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;
}

The JIT debugger lets me know that I implicitly convert an object to a string

I've tried using a ToString method like this:

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());
}

I think I'm on the right track there, as I get an error telling me that the object reference is not set to an instance of an object.

Upvotes: 1

Views: 196

Answers (1)

aqwert
aqwert

Reputation: 10789

I believe the issue is the implementation of the ToString() method in TripExpense. When you use the string out of that and feed it into the FindTrip it cannot find it anymore.

What you can do instead is to have your original setting of the combo items and modify the SelectedIndexChanged instead

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;
    ... 
}

This way the ComboBox text will still grab the ToString() of the TripExpense object but you will still be able to get the actual object from the SelectedItem to play with rather than trying to requery for the object.

Upvotes: 1

Related Questions