简体   繁体   English

从DataGrid中的ComboBox获取价值

[英]Getting Value from ComboBox in DataGrid

I need to retrieve the selected values from a ComboBox nested in a WPF DataGrid. 我需要从嵌套在WPF DataGrid中的ComboBox中检索选定的值。 The problem is, I seem to be only able to access the data that is bound to ComboBox (a List) and not the selected value itself. 问题是,我似乎只能访问绑定到ComboBox(列表)的数据,而不能访问所选值本身。 How can I access the ComboBox, and thus the selected value of the ComboBox item, when it is in a DataGrid and bound to a List? 当它位于DataGrid中并绑定到列表时,如何访问ComboBox,从而访问ComboBox项的选定值? The ComboBox populates just fine, I just cannot figure out how to access the selection. ComboBox可以很好地填充,我只是无法弄清楚如何访问选择。

I have been struggling with this for some time, so I would sincerely appreciate any help: 我已经为此苦苦挣扎了一段时间,因此我将不胜感激任何帮助:

The XAML: 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>

and the C# 和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

            }

        }






    }
}

Thanks in advance. 提前致谢。

这可能是这里提出的问题的重复问题,但是您可以使用该线程的公认答案来解决此问题。

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

Try this to get SelectedValue: 尝试此操作以获得SelectedValue:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM