I am trying to add an item to aircraftList
ListBox and be able to click on it and on a detailsList
TextBox display all information per item selected. However, I am using BindingList<AircraftDetails> Details = new BindingList<AircraftDetails>();
and AircraftClass
which contains the following method:
public override string ToString()
{
List<string> builder = new List<string>();
builder.add("something here like a variable");
which wil return all details to the detailsList
textBox.
Now, the issue is that when I tried to do something like aircraftList.Items.Add("Test")
it will show a error message showing this
I am at a loss for what to do, however I will provide the repository of my code that is hosted on gitHub so that you can better comprehend it. REPOSITORY
CodePudding user response:
The error message tells you exactly what the issue is. You cannot modify the Items collection when you have set the DataSource property. The whole point of binding a list to the control is that the control displays what's in that list. If you want to add a new item, you have to add it to the list you bound to the control.
CodePudding user response:
Thank you for posting your repository in support of your question. That made it easy to reproduce the issue. I made a minor change to your addaircraftButton_Click
that "should" do the trick.
public void addaircraftButton_Click(object sender, EventArgs e)
{
//FlightSetup is a form which will fill out the Main's Form Variables
//Trying to add "planeModel" to aircraftList and display details once it is selected from the list
FlightSetup addplane = new FlightSetup();
AircraftDetails aircraftDetails = new AircraftDetails();
using (addplane)
{
DialogResult result = addplane.ShowDialog();
planeModel = addplane.planeModel_textbox.Text;
airline = addplane.airline_textbox.Text;
fuelG = double.Parse(addplane.fuel_textbox.Text); //TESTING (Look at BuildLogs.txt for complete code before this one)
bag1 = int.Parse(addplane.carryonTextBox.Text);
bag2 = int.Parse(addplane.checkedBagsTextBox.Text);
object o = new AircraftDetails
{
AircraftModel = planeModel,
Airline = airline,
Fuel = fuelG, //TESTING
OnBoardBags = bag1,
CheckedBags = bag2,
};
detailsList.Text = o.ToString();
}
//aircraftList.Items.Add(planeModel); // not working right here <--
// Do this instead!
Details.Add(aircraftDetails);
}
Obviously, you were very close to having the right code yourself. The thing to remember is that once you bind to a DataSource
, you should be able to work directly with that data (in this case Details.Add(aircraftDetails)
) and should no longer attempt to manipulate the UI control directly.