What I am trying to do is simply have a combobox populate with data from an sqlite table. While I have done this with code methods, I wold really like to do this in what I can see is the better WPF way to do things.
From what I understand the flow should go something like this:
I should have a class that holds the data, I made a quick class which the default constructor is to connect to the database and dump it's results to a list like so:
internal class mainmenusql
{
private List<string> _Jobs;
public mainmenusql()
{
SQLiteConnection conn = new SQLiteConnection();
conn.ConnectionString = "Data Source=C:\\Users\\user\\Documents\\db.sqlite;Version=3";
try
{
conn.Open();
SQLiteDataReader reader;
SQLiteCommand command = new SQLiteCommand(conn);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM Tasks";
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
_Jobs.Add(reader.GetValue(0).ToString());
}
}
else
{
MessageBox.Show("No records");
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
finally
{
conn.Close();
}
}
}
Having some errors with the list "Object reference not set to an instance of an object".
But anyways, the next step should be to set the DataContext
of the form to this object right?
public MainWindow()
{
DataContext = new mainmenusql();
InitializeComponent();
}
And finally the combobox should have a binding right?
<Window x:Class="sqliteDatacontext.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox DataContext="{Binding Path=_Jobs}" HorizontalAlignment="Left" Margin="141,124,0,0" VerticalAlignment="Top" Width="120"/>
</Grid>
</Window>
What am I doing wrong here?