从数据网格中获取 int 值 c# wpf

get int value from data grid c# wpf

我想从数据网格中获取值

我用这个代码

 if (Convert.ToString((datagrid_customer.SelectedCells[3].Column.GetCellContent(datagrid_customer.SelectedItem) as TextBlock).Text) == Convert.ToString((datagrid_customer.SelectedCells[1].Column.GetCellContent(datagrid_customer.Items[i]) as TextBlock).Text))
                { 
...
}

它可以工作,但请显示字符串。

当我将它转换为 int 时出现错误

Mah m = database.Mahs.FirstOrDefault(x => x.MahID == int.Parse((datagrid_customer.SelectedCells[0].Column.GetCellContent(datagrid_customer.Items[i]) as TextBlock).Text.Trim()));

错误

System.NotSupportedException: 'LINQ to Entities 无法识别方法 'Int32 Parse(System.String)' 方法,并且此方法无法转换为存储表达式。'

值不是字符串。

我该怎么做?

尝试将其拆分为单独的操作:

TextBlock tb = datagrid_customer.SelectedCells[0].Column.GetCellContent(datagrid_customer.Items[i]) as TextBlock;
// null check
if(tb == null) return;

int i;
bool success = int.TryParse(tb.Text.Trim(), out i);
if(success)
  Mah m = database.Mahs.FirstOrDefault(x => x.MahID == i);