I am retrieving data from a database and trying to populate a List<>. That is my goal.
I am currently inserting the retrieved data into variables within a method and then trying to add the method to the List<>.
Here is my code:
public void Select()
{
var sprite = new Sprite();
if (Game.player.inBattle)
{
//Open a connection
databaseCon.Open(); //Works
//Create Command
var cmd = new MySqlCommand(BattleEngine.query, databaseCon); //Works
//Create a data reader and Execute the command
var dataReader = cmd.ExecuteReader(); //Works
try
{
//Read the data and store them in the list
while (dataReader.Read())
{
//Inserts matching Row's first Column attribute into method variable
sprite.id = (dataReader.GetInt32(0));
//Inserts matching Row's second Column attribute into method variable
sprite.identifier = (dataReader.GetString(1));
Console.WriteLine(sprite.id + ": " + sprite.identifier); //Works. Variables are loaded with data
//Fails. Doesn't load the method into the list
Game.sprite.Add(new Sprite());
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex);
}
finally
{
if (dataReader != null)
{
//close Data Reader
dataReader.Close();
}
if (databaseCon != null)
{
//close Connection
databaseCon.Close();
}
}
}
}
I then have a test Console.WriteLine(Game.sprite[0]); setup after this loops and it displays Namespace.Sprite
There are probably other ways of doing this but ultimately I would like to have the list populated with each record within a new method. By storing it in the List<> I can then pull specific information to be used later.
In theory I want to be able to do this;
Console.WriteLine("{0}", Game.sprite[0].id);
I have seen this done before but I cannot seem to replicate it.
ADDITION:
public class Game
{
public static Player player;
public static List<Character> sprite;
GameScreens mainMenu = new GameScreens();
GameScreens titleScreen = new GameScreens();
public Game()
{
Console.SetWindowSize(100, 50);
Console.BufferHeight = 50;
Console.BufferWidth = 100;
titleScreen.TitleScreen();
player = new Player();
sprite = new List<Character>();
Player.Initialize(player);
GameLoop();
}
void GameLoop() //Our game loop.
{
mainMenu.MainMenu();
}
}
Try:
Game.sprite.Add(sprite);Instead of:
Game.sprite.Add(new Sprite());Your code adds an empty
Spriteobject – not the one you declared