Zohaib
Zohaib

Reputation: 199

Get selected cell value from DataGrid Cell

I want to get selected cell value from DataGrid. When i click on a particular cell, the cell value should be show in MessageBox but in my case unable to do that. The exception occurs in Datagrid.SelectedCells[0];.

System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: 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>

and on selection change

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

        }

AddValues in Datagrid:

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

Upvotes: 0

Views: 4008

Answers (2)

Nhan Phan
Nhan Phan

Reputation: 1302

The Datagrid_CurrentCellChanged will be called before Datagrid_SelectedCellsChanged() is called then the Datagrid.SelectedCells is still empty.

Should use Datagrid_SelectedCellsChanged event instead of Datagrid_CurrentCellChanged to retrieve selected cells.

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

Upvotes: 1

J.Memisevic
J.Memisevic

Reputation: 1454

Try with

Selected Event

, i think u won't have any problems.

Or if u want to keep it in

SelectionChanged

you have to know that it fires when your DataGrid loses focus. So in that case u have

DataGrid.SelectedCells=null;

Good practice will be to test if your

DataGrid.SelectedCells.Coun>0

then continue or return if it don't

Upvotes: 1

Related Questions