从DataGrid中的选定行获取特定单元格的数据WPF C# [英] Get data of specific cell from selected row in DataGrid WPF C#

查看:978
本文介绍了从DataGrid中的选定行获取特定单元格的数据WPF C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataGrid,我填充从我的sql数据库的数据。
现在我想从我用复选框选择的行获得一个特定的单元格(第2个单元格)。

I have a DataGrid which I fill with data from my sql database. Now I want to get a specific cell (2nd cell) from the row I selected with a checkbox.

这是我现在的状态:
WPF XAML:

This is what I have now: WPF XAML:

<DataGrid Name="myGrid">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox Checked="CheckBox_Checked"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    <DataGridTextColumn Header="CustomerID" Width="Auto" Binding="{Binding CustomerID}"/>
    <DataGridTextColumn Header="ItemID" Width="Auto" Binding="{Binding ItemID}"/>
<DataGrid>

C#代码:

private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        DataGrid row = (DataGrid)myGrid.SelectedItems[1];
        System.Windows.MessageBox.Show(row);
    }

运行时出现错误:


System.ArgumentOutOfRangeException

System.ArgumentOutOfRangeException

{索引超出范围,必须为非负数且小于the collection.\r\\\
Parameter name:index}

{"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}

我做错了什么?我必须使用另一种方法来获得我想要的单元格。

What am I doing wrong? Do I have to use another approach to get the cell I want?

推荐答案

我终于找到了!很简单。

I finally found it! Very simple.

DataRowView drv = (DataRowView)myGrid.SelectedItem; 
String result = (drv["CustomerID"]).ToString(); 
MessageBox.Show(result);

这篇关于从DataGrid中的选定行获取特定单元格的数据WPF C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆