Reputation: 1
I have a listbox, named listBox2, that I am trying to populate. "ProSailor" is a class and the three numbers at the end are values from said class.
I need to add these values to listBox2.
public string[] listBoxBoard = new string[10];
List<string> _scoreboard = new List<string>();
ProSailor sailor1 = new ProSailor(1, 24, 7);
ProSailor sailor2 = new ProSailor(2, 23, 14);
ProSailor sailor3 = new ProSailor(3, 20, 5);
However, if I try this:
_scoreboard.Add(sailor1);
I just get two errors that say:
The best overloaded method match for 'System.Collections.Generic.List.Add(string)' has some invalid arguments
Argument 1: cannot convert from 'SailingEvent.ProSailor' to 'string'
I have also tried:
_scoreboard.Add(listBoxBoard[0]);
This doesn't return any errors but does not populate the listbox.
Upvotes: 0
Views: 330
Reputation: 19296
If your class looks like this one:
class ProSailor
{
public ProSailor(int num1, int num2, int num3)
{
Num1 = num1;
Num2 = num2;
Num3 = num3;
}
public int Num1 { get; set; }
public int Num2 { get; set; }
public int Num3 { get; set; }
}
And you want to get List of string with values you should create new method to get this list:
class ProSailor
{
public ProSailor(int num1, int num2, int num3)
{
Num1 = num1;
Num2 = num2;
Num3 = num3;
}
public int Num1 { get; set; }
public int Num2 { get; set; }
public int Num3 { get; set; }
public List<string> GetAllValues()
{
return new List<string> { Num1.ToString(), Num2.ToString(), Num3.ToString() };
}
}
Now if you want create one List of string and combine values from few object you can use AddRange
methond:
List<string> _scoreboard = new List<string>();
ProSailor sailor1 = new ProSailor(1, 24, 7);
ProSailor sailor2 = new ProSailor(2, 23, 14);
ProSailor sailor3 = new ProSailor(3, 20, 5);
_scoreboard.AddRange(sailor1.GetAllValues());
_scoreboard.AddRange(sailor2.GetAllValues());
_scoreboard.AddRange(sailor3.GetAllValues());
Now you can populate your list using following code:
listBox2.DataSource = _scoreboard;
Upvotes: 0
Reputation: 2267
The reason you're getting a type mismatch is because you've initialized your list as List<string>
and then try to add a ProSailor
type object to the list. If sailor has some string property you could try the following:
say ProSailor looks something like this:
class ProSailor
{
public string MyStringProperty { get; set; }
public ProSailor(int a, int b, int c)
{
}
}
then to accomplish what you're doing:
List<ProSailor> sailorList = (new ProSailor[]
{
new ProSailor(1, 24, 7),
new ProSailor(2, 23, 14),
new ProSailor(3, 20, 5)
}).ToList();
List<string> stringList = sailorList.Select(s => s.MyStringProperty).ToList();
Upvotes: 1
Reputation: 9024
In your ProSailer
class you override the ToString()
Function so the Listbox will know what to display. Add you collection of ProSailor
to the Listbox
since it adds items as Objects that includes class objects.
public override string ToString()
{
return "your string to display";
}
Upvotes: 1