在DatagridView中优化可选搜索

时间:2013-09-02 09:19:57

标签: c# sql sql-server winforms datagridview

例如,我有4个textbox和4个comboBox,我想在DatagridView中搜索值 输入textboxescomboBoxes以及我不想搜索空的。 我可以使用if Condition来完成这项工作,但我认为它不是优化的并且非常复杂。

1 个答案:

答案 0 :(得分:1)

在页面加载时从sql server获取数据到静态列表。 然后在过滤器按钮单击事件中, 如果像if(combox1.checked){ list.Where(obj=>obj.<field name for that combobox>)这样的语句,请逐步添加8个明智的过滤器。以下是示例代码。我想你可能会理解这一点。

static List<CRMIssueHeader> issueheader=new List<CRMIssueHeader>();

    protected void Page_Load(object sender, EventArgs e)
    {
        btnUpdate.Visible = false;
        if (!Page.IsPostBack)
        { 
            issueheader = _CRMService.CRMTRN02_GetIssueHeader();
        }
    }

protected void btnOK_Click(object sender, EventArgs e)
{
  List<CRMIssueHeader> IHeader = new List<CRMIssueHeader>();
        IHeader = issueheader;
       //_CRMService = new CRMService();
        //issueheader  = _CRMService.CRMTRN02_GetIssueHeader();
        if (!chknew.Checked)
            IHeader = IHeader.Where(obj => obj.IssueStatus != 0).ToList();
        if (!chkWIP.Checked)
            IHeader = IHeader.Where(obj => obj.IssueStatus != 1).ToList();
        if (!chkFixed.Checked)
            IHeader = IHeader.Where(obj => obj.IssueStatus != 2).ToList();
        if (chkAccepted.Checked)
            IHeader = IHeader.Where(obj => obj.IssueStatus != 3).ToList();
        if (chkClarification.Checked)
            IHeader = IHeader.Where(obj => obj.IssueStatus != 4).ToList();
        if (chkCancel.Checked)
            IHeader = IHeader.Where(obj => obj.IssueStatus != 5).ToList();
        if (chkOnHold.Checked)
            IHeader = IHeader.Where(obj => obj.IssueStatus != 6).ToList();
        if (ddlCustomers.SelectedValue.ToString() != "All")
            IHeader = IHeader.Where(obj => obj.CustomerCode == ddlCustomers.SelectedValue.ToString()).ToList();
        if (txtFrom.Text.Length != 0 && txtTo.Text.Length != 0)
            IHeader = IHeader.Where(obj => obj.ReportedOn >= DateTime.Parse(txtFrom.Text) && obj.ReportedOn <= DateTime.Parse(txtTo.Text)).ToList();
        else if (txtFrom.Text.Length != 0 && txtTo.Text.Length == 0)
            IHeader = IHeader.Where(obj => obj.ReportedOn >= DateTime.Parse(txtFrom.Text)).ToList();
        else if (txtFrom.Text.Length == 0 && txtTo.Text.Length != 0)
            IHeader = IHeader.Where(obj => obj.ReportedOn <= DateTime.Parse(txtTo.Text)).ToList();
        else ;

}