2016-05-12 147 views
0

WPF DataGridにネストされたComboBoxから選択した値を取得する必要があります。問題は、選択した値そのものではなく、ComboBox(List)にバインドされているデータにしかアクセスできないようです。 ComboBoxアイテム、それがDataGridにあり、Listにバインドされている場合、ComboBoxアイテムに選択された値をどのようにしてアクセスできますか? ComboBoxがうまくいっているだけで、選択肢にアクセスする方法がわかりません。DataGridのComboBoxから値を取得する

私はしばらくの間これで苦労してきたので、私は心から任意の助けいただければ幸いです:

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> 

と事前に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 

      } 

     } 






    } 
} 

感謝を。

+0

Iをあなたのコードを調べる時間がありませんが、通常のキャスティングを試してみましたか?選択した行を取得する - >正しいセルを取得する - >文字列にキャストする(ToString()) –

答えて

0

は、これは、1つの重複した質問がhereを求められる場合がありますが、

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

+0

答えがありがとうございますが、問題はあまりコンボボックスの値にアクセスしていません(実際にはコード内の別のコンボボックス)、ComboBox自体(Bound DataGridにあります)。しかしもう一度ありがとう。 – KellyMarchewa

0

はSelectedValueの取得するには、これを試してみてください、あなたはそのスレッドの受け入れ答えを使用してこれを達成することができます

private void updateScore(object sender, SelectionChangedEventArgs e) 
{ 
    int point = (int)((ComboBox)e.OriginalSource).SelectedValue; 
} 
関連する問題