2016-05-12 219 views
0

我需要從嵌套在WPF DataGrid中的ComboBox中檢索選定的值。問題是,我似乎只能訪問綁定到ComboBox(List)的數據,而不是所選的值本身。如何訪問ComboBox,以及ComboBox項目在DataGrid中的選定值並綁定到List時?組合框填充就好,我只是不知道如何訪問選擇。提前在DataGrid中從ComboBox獲取值

<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> 

和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 

      } 

     } 






    } 
} 

感謝:

我一直在掙扎了一段時間,所以我衷心感謝所有幫助:

的XAML。

+0

我沒有時間瀏覽你的代碼,但你有沒有試過只是定期的投射?獲取選中的行 - >獲取正確的單元格 - >強制轉換爲字符串(ToString()) –

回答

0

這可能是一個重複的問題問here,但你可以做到這一點使用線程的接受的答案

ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem; string value = typeItem.Content.ToString();

+0

感謝您的回答,但問題不在於訪問ComboBox值(我實際上是通過代碼中其他地方的其他Combobox ),但ComboBox本身(它在Bound DataGrid中)。不過謝謝。 – KellyMarchewa

0

嘗試使用此方法得到的SelectedValue:

private void updateScore(object sender, SelectionChangedEventArgs e) 
{ 
    int point = (int)((ComboBox)e.OriginalSource).SelectedValue; 
}