Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get the value of a datagrid cell on the dataGrid1_BeginningEdit Event?

Tags:

c#

wpf

datagrid

I'm trying to check if the value of a datagrid cell is null when i use the dataGrid1_BeginningEdit Event to stop the event.

code is as follows, i can use '(((TextBox)e.EditingElement).Text' when im doing 'dataGrid2_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)' but not for the below.

    private void dataGrid2_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        int column = dataGrid2.CurrentCell.Column.DisplayIndex;
        int row = dataGrid2.SelectedIndex;

        if (((TextBox)e.EditingElement).Text == null)
            return;

Many thanks

like image 634
user980150 Avatar asked Dec 16 '22 08:12

user980150


2 Answers

I think this will help you....

    private void DataGrid_BeginningEdit(
        object sender,
        Microsoft.Windows.Controls.DataGridBeginningEditEventArgs e)
    {
        e.Cancel = GetCellValue(((DataGrid) sender).CurrentCell) == null;
    }

    private static object GetCellValue(DataGridCellInfo cell)
    {
        var boundItem = cell.Item;
        var binding = new Binding();
        if (cell.Column is DataGridTextColumn)
        {
            binding
              = ((DataGridTextColumn)cell.Column).Binding
                    as Binding;
        }
        else if (cell.Column is DataGridCheckBoxColumn)
        {
            binding
              = ((DataGridCheckBoxColumn)cell.Column).Binding
                    as Binding;
        }
        else if (cell.Column is DataGridComboBoxColumn)
        {
            binding
                = ((DataGridComboBoxColumn)cell.Column).SelectedValueBinding
                     as Binding;

            if (binding == null)
            {
                binding
                  = ((DataGridComboBoxColumn)cell.Column).SelectedItemBinding
                       as Binding;
            }
        }

        if (binding != null)
        {
            var propertyName = binding.Path.Path;
            var propInfo = boundItem.GetType().GetProperty(propertyName);
            return propInfo.GetValue(boundItem, new object[] {});
        }

        return null;
    }
like image 200
WPF-it Avatar answered Dec 18 '22 20:12

WPF-it


I found a different approach:

ContentPresenter cp = (ContentPresenter)e.Column.GetCellContent(e.Row);
YourDataType item = (YourDataType)cp.DataContext;
like image 25
Gytis S Avatar answered Dec 18 '22 22:12

Gytis S