在SAS中需使用哪个DATAGRID函数获取指定列值并按条件赋值?
DataGrid遍历与条件赋值实现方案
没有单一的"DataGrid专属函数"直接完成你描述的需求,通常需要结合行遍历和条件判断逻辑来实现,以下是具体实现方式:
1. 遍历DataGrid所有行获取AccountGGS值
你可以通过DataGrid的Rows集合遍历每一行,跳过新增行(如果启用了自动添加新行功能),提取目标单元格的值:
C# 示例代码
foreach (DataGridViewRow row in mydatagrid.Rows) { // 跳过未提交的新增行 if (row.IsNewRow) continue; // 获取AccountGGS单元格值,注意处理空值 object ggsRawValue = row.Cells["AccountGGS"].Value; if (ggsRawValue == null || ggsRawValue == DBNull.Value) continue; // 转换为你需要的数据类型(假设是decimal,可根据实际调整) if (decimal.TryParse(ggsRawValue.ToString(), out decimal accountGGS)) { // 这里加入你的条件赋值逻辑 } }
VB.NET 示例代码
For Each row As DataGridViewRow In mydatagrid.Rows ' 跳过未提交的新增行 If row.IsNewRow Then Continue For ' 获取AccountGGS单元格值,处理空值 Dim ggsRawValue As Object = row.Cells("AccountGGS").Value If ggsRawValue Is Nothing OrElse ggsRawValue Is DBNull.Value Then Continue For End If ' 转换目标数据类型 Dim accountGGS As Decimal If Decimal.TryParse(ggsRawValue.ToString(), accountGGS) Then ' 加入条件赋值逻辑 End If Next
2. 基于AccountGGS的条件赋值逻辑
拿到accountGGS值后,根据你的特定条件(比如取最大值、求和、判断是否满足阈值等)给目标变量赋值,举几个常见场景示例:
示例1:提取所有AccountGGS的最大值
decimal maxGGS = 0; foreach (DataGridViewRow row in mydatagrid.Rows) { if (row.IsNewRow) continue; if (decimal.TryParse(row.Cells["AccountGGS"].Value?.ToString(), out decimal ggs)) { if (ggs > maxGGS) maxGGS = ggs; } } // maxGGS即为所有账户的AccountGGS最大值
示例2:统计符合条件的账户数量
int qualifiedCount = 0; foreach (DataGridViewRow row in mydatagrid.Rows) { if (row.IsNewRow) continue; if (decimal.TryParse(row.Cells["AccountGGS"].Value?.ToString(), out decimal ggs)) { // 条件:AccountGGS大于500 if (ggs > 500) qualifiedCount++; } }
3. 优化方案:直接遍历绑定数据源
如果你的DataGrid绑定了DataTable或其他数据源,直接遍历数据源的效率会更高(避免UI层的交互开销):
DataTable dataSource = mydatagrid.DataSource as DataTable; if (dataSource != null) { foreach (DataRow row in dataSource.Rows) { object ggsValue = row["AccountGGS"]; if (ggsValue != DBNull.Value && decimal.TryParse(ggsValue.ToString(), out decimal ggs)) { // 条件赋值逻辑 } } }
内容的提问来源于stack exchange,提问作者Umut Koc
相关产品推荐
相关产品推荐

