Ich muss die ausgewählten Werte aus einer ComboBox abrufen, die in einem WPF DataGrid verschachtelt ist. Das Problem ist, dass ich nur auf die Daten zugreifen kann, die an ComboBox gebunden sind (eine Liste) und nicht auf den ausgewählten Wert selbst. Wie kann ich auf die ComboBox und damit den ausgewählten Wert des ComboBox-Elements zugreifen, wenn es sich in einem DataGrid befindet und an eine Liste gebunden ist? Die ComboBox füllt sich gut, ich kann einfach nicht herausfinden, wie man auf die Auswahl zugreifen kann.Wert aus ComboBox in DataGrid abrufen
Ich habe seit einiger Zeit mit diesem zu kämpfen, so würde ich aufrichtig danken Ihnen für jede Hilfe:
Die XAML:
<Window x:Class="hotels.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="700" Width="1000" Loaded="Window_Loaded" WindowStyle="ThreeDBorderWindow">
<ScrollViewer>
<StackPanel Orientation="Vertical" Margin="20">
<WrapPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Label Content="Room:" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Center" />
<TextBox x:Name="roomTextBox" Margin="5,0,0,0" TextWrapping="Wrap" Width="50" Panel.ZIndex="-1" VerticalAlignment="Center"/>
<Label x:Name="locationLabel" Content="Location:" Margin="25,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Right"/>
<ComboBox x:Name="locationComboBox" SelectionChanged="filterEmployees" ItemsSource="{Binding}" Margin="5,0,0,0" SelectedIndex="-1" VerticalAlignment="Center" Width="150"/>
<Label x:Name="inspectLabel" Content="Inspector:" HorizontalAlignment="Left" Margin="50,0,0,0" VerticalAlignment="Center" Height="27"/>
<ComboBox x:Name="inspectorBox" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="15,0,0,0" VerticalAlignment="Center" Width="100"/>
<Label x:Name="empLabel" Content="Attendant:" HorizontalAlignment="Left" Margin="50,0,0,0" VerticalAlignment="Center"/>
<ComboBox x:Name="employeeBox" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="5,0,0,0" VerticalAlignment="Center" Width="100"/>
</WrapPanel>
<WrapPanel>
<Label x:Name="scoreLabel" Content="Score: "></Label>
<Label x:Name="currentPointLabel"></Label>
<Label x:Name="totalPointLabel"></Label>
</WrapPanel>
<DataGrid x:Name="itemGrid" AutoGenerateColumns="False" ItemsSource="{Binding}" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" MinHeight="400" Height="400" >
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Header="Name" Binding="{Binding Name}" CanUserResize="False" />
<DataGridTextColumn IsReadOnly="True" Header="Description" Binding="{Binding Description}" />
<DataGridTextColumn IsReadOnly="True" Header="Points Possible" Binding="{Binding Points}" />
<DataGridTemplateColumn Header="Deductions">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Score}" SelectedIndex="0" Se SelectionChanged="updateScore" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Comments" MinWidth="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Comments}"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="submitButton" Click="submitData" Content="Submit" HorizontalAlignment="right" Margin="00, 0, 00, 00 " VerticalAlignment="Center" Width="75"/>
</StackPanel>
</ScrollViewer>
</Window>
und die C#
public partial class MainWindow : Window
{
private SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
private DataSet ds = new DataSet();
private int totalPoints;
private int currentPoints;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
employeeBox.IsEnabled = false;
inspectorBox.IsEnabled = false;
initializeData();
currentPoints = totalPoints;
totalPointLabel.Content = " \\ " + totalPoints;
}
private void initializeData()
{
try { con.Open(); }
catch (SqlException er) { Console.Write(er); }
String query = "SELECT * from dbo.locations";
SqlDataAdapter locAdapter = new SqlDataAdapter(query, con);
locAdapter.Fill(ds, "Locations");
query = "SELECT * from dbo.report";
SqlDataAdapter reportAdapter = new SqlDataAdapter(query, con);
reportAdapter.Fill(ds, "Reports");
SqlCommand insert = new SqlCommand("INSERT into dbo.report (report_id, inspector, employee, room, date, score) " + " VALUES (@report_id, @inspector, @employee, @room, @date, @score)", con);
insert.Parameters.Add("@report_id", SqlDbType.Int, 5, "report_id");
insert.Parameters.Add("@inspector", SqlDbType.Int, 5, "inspector");
insert.Parameters.Add("@employee", SqlDbType.Int, 4, "employee");
insert.Parameters.Add("@date", SqlDbType.Date, 50);
insert.Parameters.Add("@score", SqlDbType.Int, 4);
reportAdapter.InsertCommand = insert;
query = "SELECT * from dbo.report_details";
SqlDataAdapter detailsAdapter = new SqlDataAdapter(query, con);
detailsAdapter.Fill(ds, "Details");
insert = new SqlCommand("INSERT into dbo.report_details (reportID, itemID, points, comments) " + " VALUES (@reportID, @itemID, @points, @comments)", con);
insert.Parameters.Add("@reportID", SqlDbType.Int, 5, "reportID");
insert.Parameters.Add("@itemID", SqlDbType.Int, 5, "itemID");
insert.Parameters.Add("@points", SqlDbType.Int, 4, "points");
insert.Parameters.Add("@comments", SqlDbType.Text, 150);
detailsAdapter.InsertCommand = insert;
locationComboBox.DataContext = ds.Tables["Locations"];
locationComboBox.DisplayMemberPath = "locName";
DataTable grid = new DataTable("Grid");
grid.Columns.Add("ID", typeof(int));
grid.Columns.Add("Name", typeof(String));
grid.Columns.Add("Description", typeof(String));
grid.Columns.Add("Points", typeof(Int16));
grid.Columns.Add("Score", typeof(List<int>));
grid.Columns.Add("Comments", typeof(String));
query = "SELECT itemID, name, description, points, category FROM dbo.items";
SqlDataReader reader = new SqlCommand(query, con).ExecuteReader();
while (reader.Read())
{
DataRow row = grid.NewRow();
row["ID"] = reader["itemID"];
row["Name"] = reader["name"];
row["Description"] = reader["description"];
row["Points"] = reader["points"];
totalPoints += (int)reader["points"];
int pointsPossible = (int)reader["points"];
List<int> rowList = new List<int>();
for (int i = pointsPossible; i >= 0; i--)
{
rowList.Add(i);
}
rowList.Sort();
row["Score"] = rowList;
grid.Rows.Add(row);
}
ds.Tables.Add(grid);
itemGrid.ItemsSource = ds.Tables["Grid"].DefaultView;
}
private void filterEmployees(object sender, SelectionChangedEventArgs e)
{
DataRowView row = (DataRowView)locationComboBox.SelectedItem;
Int16 locationID = Int16.Parse(row["locID"].ToString());
employeeBox.IsEnabled = true;
inspectorBox.IsEnabled = true;
if (ds.Tables["Employees"] != null) {
ds.Tables["Employees"].Rows.Clear();
}
String query = "SELECT * from dbo.employees where empLocation = " + locationID;
SqlDataAdapter empAdapter = new SqlDataAdapter(query, con);
empAdapter.Fill(ds, "Employees");
employeeBox.DataContext = ds.Tables["Employees"];
employeeBox.DisplayMemberPath = "empName";
inspectorBox.DataContext = ds.Tables["Employees"];
inspectorBox.DisplayMemberPath = "empName";
}
private void submitData(object sender, RoutedEventArgs e)
{
DataRow reportRow = ds.Tables["Reports"].NewRow();
DataRowView inspectorSelection = (DataRowView)inspectorBox.SelectedItem;
reportRow["inspector"] = Int16.Parse(inspectorSelection["empID"].ToString());
DataRowView empSelection = (DataRowView)employeeBox.SelectedItem;
reportRow["employee"] = Int16.Parse(inspectorSelection["empID"].ToString());
reportRow["room"] = Int16.Parse(roomTextBox.Text);
reportRow["date"] = DateTime.Now.ToString("yyy-MM-dd");
reportRow["score"] = "";
}
private void updateScore(object sender, SelectionChangedEventArgs e)
{
foreach (DataRowView row in itemGrid.ItemsSource)
{
// returns the List, not the ComboBox
}
}
}
}
Vielen Dank im Voraus.
I Habe keine Zeit, deinen Code durchzusehen, aber hast du gerade versucht, ihn regelmäßig zu Casting? Abrufen der ausgewählten Zeile -> Abrufen der richtigen Zelle -> Umwandlung in Zeichenfolge (ToString()) –