Exactly how you do it depends on you, and what you have put in your City class - but I notice that the City constructor accepts and X and Y position:
city = new City(textBox1.Text, e.X, e.Y, greenPen);
So you could just have a public Location property in the City class:
public Point Location ( get; private set; }
And use that when you want to draw the line between them.
All you have to do in your constructor is:
Location = new Point(x, y);
And drawing the line becomes trivial:
gr.DrawLine(greenPen, firstCity.Location, secondCity.Location);
"No I want to get just the coordinates(x,y) from the objects in the combobox.
private void button2_Click(object sender, EventArgs e)
{
foreach (City c in m.Cities)
{
listBox1.Items.Add(c.AsString());
comboBox1.Items.Add(c.Id);
comboBox2.Items.Add(c.Id);
}
m.Cities.Clear();
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
comboBox2.Items.Remove(comboBox1.SelectedItem);
}
private void comboBox2_SelectedValueChanged(object sender, EventArgs e)
{
comboBox1.Items.Remove(comboBox2.SelectedItem);
label2.Text = "End point: " + comboBox2.SelectedItem.ToString();
}
I tried the commented code but it said that I have no reference to an object."
OK...there are some oddities there...
Why are you removing the selected item from the combobox each time the selection changes? Surely the Combobox is going to run out of items rather quickly? Shouldn't you be putting the "old" items back in?
Now, to your problem - and it's both simpler to fix than you think, and a little more complex! :laugh:
I want you to change your City class, and add an override method (Have you covered them yet?)
public override string ToString()
{
return ...
}
Now, remove the contents of your AsString method, and move them into ToString, replacing the
return
line I didn't complete. Almost certainly, it will now look something like this:
public override string ToString()
{
return CityName;
}
You can now get rid of the AsString method completely, (and if you use it in code you haven't shown here, change the name to ToString)
What happens now is that whenever C# wants to use your City instance as a string, it will automatically call ToString for you - which means that this code can change:
private void button2_Click(object sender, EventArgs e)
{
foreach (City c in m.Cities)
{
listBox1.Items.Add(c);
comboBox1.Items.Add(c);
comboBox2.Items.Add(c);
}
m.Cities.Clear();
}
What that does is get the system to use the name of the city in the textbox and the comboboxes,
because they will automatically call ToString for you.
Now, when you fetch the SelectedValue from the combobox, you can cast it straight to the actual instance of the City:
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
City citycombo = comboBox1.SelectedItem as City;
if (citycombo != null)
{
comboBox2.Items.Remove(citycombo);
label1.Text = "Starting point: " + citycombo;
}
}
And it should all start to work...