【问题标题】:Get selected cell value from DataGrid Cell从 DataGrid Cell 中获取选定的单元格值
【发布时间】:2026-01-09 22:15:02
【问题描述】:

我想从 DataGrid 中获取选定的单元格值。当我单击特定单元格时,单元格值应显示在 MessageBox 中,但在我的情况下无法做到这一点。异常发生在Datagrid.SelectedCells[0];

System.ArgumentOutOfRangeException: '指定的参数超出 有效值的范围。参数名称:index'

<DataGrid  DataGridCell.Selected="DataGrid_GotFocus" SelectionUnit="Cell" 
                   SelectionMode="Single" Name="Datagrid"  AutoGenerateColumns="False" 
                   PreviewKeyDown="Datagrid_PreviewKeyDown" 
                   CurrentCellChanged="Datagrid_CurrentCellChanged" SelectionChanged="Datagrid_SelectionChanged">

            <DataGrid.Columns>

                <DataGridTextColumn Header="Code" Width="1*" Binding="{Binding Code}"/>
                <DataGridTextColumn Header="Code" Width="1*" Binding="{Binding Name}"/>
            </DataGrid.Columns>
        </DataGrid>

在选择更改时

 private void Datagrid_CurrentCellChanged(object sender, EventArgs e)
        {
            Datagrid.BeginEdit();

            DataGridCellInfo cell = Datagrid.SelectedCells[0];
            string value =((TextBlock)cell.Column.GetCellContent(cell.Item)).Text;
            MessageBox.Show(value);

        }

Datagrid 中的 AddValues:

    public FileTab()
            {
                InitializeComponent();

                AddValues();
    }



 void AddValues()
    {
        Datagrid.ItemsSource = null;

        List<Item> list = new List<Item>();
        list.Clear();

        for(int i = 0; i<10; i++)
        {
            string number = i.ToString();
            Item item = new Item()
            {
                Code = number,
                Name = "item "+number
            };
            list.Add(item);
        }


        Datagrid.ItemsSource = list;
    }

【问题讨论】:

  • 我已经访问了,但解决方案在我的情况下不起作用

标签: c# wpf datagrid


【解决方案1】:

试试

选定的事件

,我想你不会有任何问题。

或者如果你想保留它

SelectionChanged

您必须知道当您的 DataGrid 失去焦点时它会触发。所以在那种情况下你有

DataGrid.SelectedCells=null;

好的做法是测试你的

DataGrid.SelectedCells.Coun>0

如果没有则继续或返回

【讨论】:

    【解决方案2】:

    Datagrid_CurrentCellChanged 将在Datagrid_SelectedCellsChanged() 被调用之前被调用,然后Datagrid.SelectedCells 仍然为空。

    应该使用 Datagrid_SelectedCellsChanged 事件而不是 Datagrid_CurrentCellChanged 来检索选定的单元格。

    private void Datagrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        Datagrid.BeginEdit();
        DataGridCellInfo cell = Datagrid.SelectedCells[0];
        // Put your code here
    }
    

    【讨论】:

      最近更新 更多