Hello Developers,
I have a problem with a WPF/C# menu item. I want to make the menu items populate from a SQL database. I have the following code. I'm likely missing somehting in the XAML to bind the data from the database to the window, but let's see what you think.
C# Snippet
const string sql = "SELECT DISTINCT [PT].[PhysTypeCode], [PT].[PhysTypeDesc], 0 AS [ParentID] FROM [dbo].[PhysicianTypes] AS [PT] WHERE [PT].[PhysTypeDesc] <> '-- Select --' ORDER BY [PT].[PhysTypeDesc] ASC;";
Log.Debug("SP: " + sql + " for GetPhysTypes()");
Log.Debug("Dbconn called and created for GetPhysTypes()");
var connectionString = Settings.Default.Dbconn;
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, conn))
{
try
{
conn.Open();
using (var adapter = new SqlDataAdapter(cmd))
{
var ds = new DataSet();
var dt = new DataTable();
adapter.Fill(ds);
dt = ds.Tables[0];
var mbar = dt.Select("ParentID=" + 0);
foreach (var dr in mbar)
{
MiTypeAc.Items.Add(new MenuItem(dr["PhysTypeDesc"].ToString()));
}
Log.Debug("Command executed and reader completed for GetPhysTypes()");
}
}
catch (SqlException ex)
{...
Calling GetPhysTypes
private void MiTypeAc_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
GetPhysTypes();
}
Now the part I really hate (mainly because I don't fully understand binding that well)
XMAL
<MenuItem Header="By Type">
<MenuItem x:Name="MiTypeAc" Header="A-C" ItemsSource="{Binding PhysTypeDesc}" Loaded="MiTypeAc_Loaded"/>
</MenuItem>
What happens is the window loads, I navigate to the menu, and the menu opens with a large area (vertical about what 21 records would look like - 21 records being the count of records from the SQL statement), but it's empty. So the query works, the C# is working (i guess), but the binding of data to the window is not... it's empty...
thoughts?
Update: I am getting data from the SQL, so it has to be an issue getting data from C# to XAML...
Debugger: mbar = {System.Data.DataRow[21]}
Debugger: mbar[0].ItemArray[1] = "Anesthesiology Assistant"
What I have tried:
The above code. I really don't want to hard code the values since the users can, and will, add descriptions and types to the system as time goes on.