WPF DataGrid实现为某个单元格赋值、获取某列的和、积等

一、DataGrid实现为某个单元格赋值
在WPF中,要对DataGrid的某个单元格进行赋值。一般不便直接对DataGrid赋值。而是对其绑定的数据源进行赋值。
现在假定有: dt_Common 为DataTable类型,dataGrid_CommonSeat为某个DataGrid.可以通过以下方式绑定:
//绑定普通坐席数据 dt_Common = (DataTable)DBHelper.ExecSql(sql_Common, conStr, DBHelper.OperateType.Select); dataGrid_CommonSeat.ItemsSource = dt_Common.DefaultView;
现在要对其中的某些单元格进行赋值。则可以通过对齐绑定的数据源dt_Common 进行赋值来实现。
string price = dt_Common.Rows[dataGrid_CommonSeat.SelectedIndex][1].ToString(); string count = dt_Common.Rows[dataGrid_CommonSeat.SelectedIndex][2].ToString(); if (string.IsNullOrEmpty(price) || string.IsNullOrEmpty(count)) return; double d = double.Parse(price) * double.Parse(count); dt_Common.Rows[dataGrid_CommonSeat.SelectedIndex][4] = d;
这样,就对dataGrid_CommonSeat的当前行第4列的单元格内容赋值成功了。
二、获取DataGrid某列的和、积等
这个很简单,遍历、判断不为空则相加或想减相乘即可。下面是封装的一个方法。改改就可以自己用了。
/// /// 获取DataGrid中第index列的值的和 /// /// 宿主DataGrid
/// 列下标.
/// /// frd 2011-9-20 20:03 public static double GetDataGridColumnSum(DataGrid datagrid, int index) { double result = 0; double temp = 0; for (int i = 0; i < datagrid.Items.Count; i++) { DataRowView mySelectedElement = datagrid.Items[i] as DataRowView; if (mySelectedElement == null) continue; double.TryParse(mySelectedElement.Row.ItemArray[index].ToString(), out temp); result += temp; } return result; }

Tags: 

延伸阅读

最新评论

发表评论