检查Datatable表指定字段的值是否重复|C/S框架网
检查Datatable表指定字段的值是否重复|C/S框架网
C# Code:
/// <summary>
/// 检查Datatable表指定字段的值是否重复
/// </summary>
/// <param name="dtCheck">需要检查的表</param>
/// <param name="fieldName">字段名</param>
/// <param name="sb">需要返回的结果信息</param>
/// <returns></returns>
public static bool IsDuplicateFieldValue(DataTable dtCheck, string fieldName, StringBuilder sb = null)
{
if (sb != null)
{
DataRow[] rows; string value;
foreach (DataRow R in dtCheck.Rows)
{
value = R[fieldName] == DBNull.Value ? "" : R[fieldName].ToString();
rows = dtCheck.Select(string.Format("{0}='{1}'", fieldName, value));
if (rows.Length > 1) sb.Append(sb.Length == 0 ? value : "," + value);
}
return sb.Length > 0;
}
else
{
//使用DataView对象获取唯一值
DataView dv = new DataView(dtCheck);
return dv.Count != dv.ToTable(true, fieldName).Rows.Count;
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
/// <summary>
/// 检查Datatable表指定字段的值是否重复
/// </summary>
/// <param name="dtCheck">需要检查的表</param>
/// <param name="fieldName">字段名</param>
/// <param name="sb">需要返回的结果信息</param>
/// <returns></returns>
public static bool IsDuplicateFieldValue(DataTable dtCheck, string fieldName, StringBuilder sb = null)
{
if (sb != null)
{
DataRow[] rows; string value;
foreach (DataRow R in dtCheck.Rows)
{
value = R[fieldName] == DBNull.Value ? "" : R[fieldName].ToString();
rows = dtCheck.Select(string.Format("{0}='{1}'", fieldName, value));
if (rows.Length > 1) sb.Append(sb.Length == 0 ? value : "," + value);
}
return sb.Length > 0;
}
else
{
//使用DataView对象获取唯一值
DataView dv = new DataView(dtCheck);
return dv.Count != dv.ToTable(true, fieldName).Rows.Count;
}
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
应用场景:
C# Code:
StringBuilder sb = new StringBuilder();
if (CommonTools.IsDuplicateFieldValue(detail, tb_PlanMainDtl.OrderID, sb))
{
Msg.Warning("表格中存在重复的订单号!\r\n"+sb.ToString());
return false;
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
StringBuilder sb = new StringBuilder();
if (CommonTools.IsDuplicateFieldValue(detail, tb_PlanMainDtl.OrderID, sb))
{
Msg.Warning("表格中存在重复的订单号!\r\n"+sb.ToString());
return false;
}
//来源:C/S框架网(www.csframework.com) QQ:23404761
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网