Reputation: 65
Im new to WPF and im trying to add tabs to my TabControl. The LoadTable Function returns a DataTable which contains the Information and should be represented to the DataGrid for every Tab.
for (int i = 1; i <= number_MaxSemester; i++)
{
TabItem item = new TabItem();
// Name of TabItem
item.Header = i + ". Semester";
//Contains the Data from Database
item.DataContext = loadTable();
Tabs.Items.Add(item);
}
loadTable Function which returns the Datatable
public DataTable loadTable()
{
DataTable dt = new DataTable();
try
{
//Open Connection to Database
using (SQLiteConnection con = new SQLiteConnection(cs))
{
//Command string for the Sqlite Command
string query = "SELECT Fach, Note, Statusfach, Versuch from infostudent WHERE username = + '" + UserName.Content + "'";
SQLiteDataAdapter dbAdapter = new SQLiteDataAdapter(query, con);
//Fill Data with SQLite Data
dbAdapter.Fill(dt);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return dt;
}
Here is the XAML Code:
<TabControl x:Name="Tabs" Margin="10,61,0,57" Width="584" HorizontalAlignment="Left">
<TabControl.ItemTemplate>
<DataTemplate>
<DataGrid />
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
Upvotes: 1
Views: 1364
Reputation: 169160
Set the Content property of the TabItem to your DataTable:
for (int i = 1; i <= number_MaxSemester; i++)
{
TabItem item = new TabItem();
// Name of TabItem
item.Header = i + ". Semester";
//Contains the Data from Database
item.Content = loadTable();
Tabs.Items.Add(item);
}
...and bind the ItemsSource property of the DataGrid to the DefaultView of the DataTable in the ContentTemplate of the TabControl:
<TabControl x:Name="Tabs">
<TabControl.ContentTemplate>
<DataTemplate>
<StackPanel>
<DataGrid ItemsSource="{Binding DefaultView}" />
</StackPanel>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
Upvotes: 1