How can i get the value of a datagrid cell on the dataGrid1_BeginningEdit Event?
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)' bu开发者_运维知识库t 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
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;
}
I found a different approach:
ContentPresenter cp = (ContentPresenter)e.Column.GetCellContent(e.Row);
YourDataType item = (YourDataType)cp.DataContext;
Try this -
(e.EditingEventArgs.Source as TextBlock).Text
var row = e.Row.Item as DataRowView;
var value = row["ColumnName"];
//now you can do whatever you want with the value
private void dataGrid2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (dataGrid2[e.ColumnIndex, e.RowIndex].Value == null)
{}
}
If you take a look at the DataGridBeginningEditEventArgs
, they contain a property Column
and Row
which you can use to select the cell from the datagrid.
This is lot simpler then some of the other working answers:
private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
string content = (e.EditingEventArgs.Source as TextBlock).Text;
if (String.IsNullOrEmpty(content))
e.Cancel = true;
}
精彩评论