2011-10-13 42 views
3

我試圖檢查datagrid單元格的值是否爲空,當我使用dataGrid1_BeginningEdit事件來停止事件。如何獲取dataGrid1_BeginningEdit事件上的datagrid單元格的值?

代碼如下,我可以使用 '(((文本框)e.EditingElement)。文本' 時即時通訊做 'dataGrid2_CellEditEnding(對象發件人,DataGridCellEditEndingEventArgs E)',但不是爲下方。

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; 

非常感謝

回答

5

我認爲這將有助於你....

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

@ wpf-it--無法找到Datagrid的CurrentCell屬性。 –

+1

我不知道你爲什麼找不到它,但你也可以使用DataGridBeginningEditEventArgs e對象。它具有e.Column和e.Row.DataContext屬性,以使您受益。在GetCellValue()調用中,boundItem現在是e.Row.DataContext,而cell.Column將是e.Column。 –

+0

是的,我也是這樣做的 –

0
private void dataGrid2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) 
     { 
      if (dataGrid2[e.ColumnIndex, e.RowIndex].Value == null) 
       {} 
     } 
+0

對不起它是一個DataGrid我有,而不是一個DataGrid視圖。你知道如何做到這一點的數據網格嗎? – user980150

1

試試這個 -

(e.EditingEventArgs.Source as TextBlock).Text 
+0

似乎沒有工作 – user980150

+0

什麼是你的列類型? DataGridTextColumn還是別的?如果你使用上述coed面臨什麼問題? –

4

我發現了一個不同的方法:

ContentPresenter cp = (ContentPresenter)e.Column.GetCellContent(e.Row); 
YourDataType item = (YourDataType)cp.DataContext; 
0
var row = e.Row.Item as DataRowView; 
var value = row["ColumnName"]; 
//now you can do whatever you want with the value 
相關問題