I created a console application that connects to a MySQL database and loads a list of video games into memory. It works fine and prints out the games correctly. Here’s the importnant part:
Program class:
internal class Program
{
static void Main(string[] args)
{
Statistics statistics = new Statistics();
Console.ReadKey();
}
}
Class:
private List<VideoGame> games;
public Statistics()
{
Initialize();
ShowGameCount();
Oldest();
}
public void Initialize()
{
string connStr = "server=localhost;user=root;database=gamesdb;port=3306;password=";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
conn.Open();
string sql = "SELECT id, title, platform, release_year FROM videogames";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
games = new List<VideoGame>();
while (rdr.Read())
{
var game = new VideoGame(rdr.GetInt32(0), rdr.GetString(1), rdr.GetString(2), rdr.GetInt32(3));
games.Add(game);
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Environment.Exit(1);
}
conn.Close();
}
Now I tried to switch to WPF to display the list visually. I created a method ReturnGames() and set it as the ItemsSource of a ListBox, but the list is empty. Here's the WPF part:
private Statistics statistics = new Statistics();
public MainWindow()
{
InitializeComponent();
gameList.ItemsSource = statistics.ReturnGames().ToString();
}
XAML:
<ListBox x:Name="gameList" />
What should I do to fill the data list in wpf? I used this website to get the basics.
Besides couple of issues, such as:
your issue comes down to this line:
gameList.ItemsSource = statistics.ReturnGames().ToString();
ReturnGames probably return something like VideoGame[], which then you just convert to string with ToString().
This way, items source for the list is just collection of characters (a string).
You need to drop that ToString. Most probably you wanted to convert each item to string, in which case you'd write:
gameList.ItemsSource = statistics.ReturnGames();
This will display default string representation of items in collection (by calling ToString on each item). This however could be adjusted (either by overloading ToString method or specifying some DataTemplates).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With