3
我有一個使用switch語句通過雙擊事件過濾的datagridview。數據源最初是通過基於用戶輸入的LINQ to SQL查詢設置的,然後他們可以選擇雙擊單元格以篩選類似項目,例如模型,計算機名稱或操作系統。有沒有更好的方法來過濾這個datagridview?
這裏似乎有太多重複的代碼。有沒有更好的方法來做到這一點?
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);
}
}
謝謝!這很好。我喜歡這個代碼提供的靈活性,因爲我們將來最喜歡添加列。至於案例問題,屬性名稱和列名都來自同一個數據源,所以不應該是一個問題。再次感謝你。 – bzsparks