我有一个使用 switch 语句通过双击事件过滤的 datagridview。数据源最初是由基于用户输入的 LINQ to SQL 查询设置的,然后他们可以选择双击单元格来过滤类似的项目,例如型号、计算机名称或操作系统。
这里似乎有太多重复的代码。关于更好的方法的任何想法?
private void gridInventory_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex > 0 && e.RowIndex > 0)
{
var cell = this.gridInventory[e.ColumnIndex, e.RowIndex];
var clickedValue = (cell.Value != null) ? cell.Value.ToString() : string.Empty;
if (!string.IsNullOrEmpty(clickedValue))
{
switch (this.gridInventory.Columns[e.ColumnIndex].Name.ToUpper())
{
case @"MODEL":
CurrentList = CurrentList.Where(r => r.Model != null && r.Model.ToUpper() == clickedValue.ToUpper()).ToList();
break;
case @"COMPUTERNAME":
CurrentList = CurrentList.Where(r => r.ComputerName != null && r.ComputerName.ToUpper() == clickedValue.ToUpper()).ToList();
break;
case @"SERIALNUMBER":
CurrentList = CurrentList.Where(r => r.SerialNumber != null && r.SerialNumber.ToUpper() == clickedValue.ToUpper()).ToList();
break;
case @"COMPUTERID":
CurrentList = CurrentList.Where(r => r.ComputerID.ToString().ToUpper() == clickedValue.ToUpper()).ToList();
break;
case @"MANUFACTURER":
CurrentList = CurrentList.Where(r => r.Manufacturer != null && r.Manufacturer.ToUpper() == clickedValue.ToUpper()).ToList();
break;
case @"OSVERSION":
CurrentList = CurrentList.Where(r => r.OSVersion != null && r.OSVersion.ToUpper() == clickedValue.ToUpper()).ToList();
break;
case @"AUDITDATE":
CurrentList = CurrentList.Where(r => r.AuditDate != null && r.AuditDate.ToString().ToUpper() == clickedValue.ToUpper()).ToList();
break;
case @"AUDITGUID":
CurrentList = CurrentList.Where(r => r.AuditGUID != null && r.AuditGUID.ToString().ToUpper() == clickedValue.ToUpper()).ToList();
break;
default:
break;
}
if (this.CurrentList != null)
{
gridInventory.DataSource = this.CurrentList;
this.lblRecords.Text = string.Format(@"Total Records: {0}", CurrentList.Count(c => c.ComputerID > 0));
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, @"error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}