Click here to Skip to main content
15,920,633 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm using C# WPF and I have DataGrid that fill with MY LIST via SQL Server Data

I have this model :
C#
public class HAVALEHA_MODEL
{
    public double? NUMBER { get; set; }
    public string NAME { get; set; }
    public string CUST_NO { get; set; }
    public long? DATE_N { get; set; }
    public string TAH { get; set; }
    public string MOLAH { get; set; }
    public string SHARAYET { get; set; }
    public int? ANBAR { get; set; }
    public double? FNUMCO { get; set; }
    public double? MAS { get; set; }
}

my list:
C#
public List<HAVALEHA_MODEL> LIST_HAVALEHA { get; set; } = new List<HAVALEHA_MODEL>();

I want to do a search in this DataGrid's Items, but I want the search to be done in such a way that a dynamic condition is automatically added for each field that is filled and finally the created condition is applied,

that is, if the user selects all the fields including the number, Fill in the number, date, etc., and make a condition for each one that is filled in, and finally apply it.

What I have tried:

C#
IEnumerable<HAVALEHA_MODEL> LINQ_SEARCH = null;

if (!string.IsNullOrEmpty(CUST_N_FLD))
{
    LINQ_SEARCH = LIST_HAVALEHA.Where(x => !(x.NAME is null) && x.NAME.ToLowerInvariant().Contains(CUST_N_FLD.ToLowerInvariant()));
}
if (!string.IsNullOrEmpty(NUMBER_FLD))
{
    LINQ_SEARCH = LIST_HAVALEHA.Where(x => !(x.NUMBER is null) && x.NAME.ToLowerInvariant().Contains(NUMBER_FLD.Text.Trim().ToLowerInvariant()));
}

MY_Data_Ggrid.ItemsSource = LINQ_SEARCH.ToList();

that is not correct and it won't work!

please give me some advice
Posted
Updated 8-Feb-23 22:28pm
v2
Comments
[no name] 8-Feb-23 14:37pm    
You're better of just looping and applying / selecting your "if's" instead of trying to concatenate some disparate / overlapping queries.
Graeme_Grant 8-Feb-23 17:06pm    
Is this a WinForms app?

IF you're using WinForms, you don't need Linq, you can use a bindingSource.Filter[^] and pass a search query like:
FirstName like '*30*' and Age > 40 and age < 50

Here is sample code used for a similar question...

1. Form1.Designer.cs
C#
partial class Form1
{
    private System.ComponentModel.IContainer components = null;

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    private void InitializeComponent()
    {
        this.dataGridView1 = new System.Windows.Forms.DataGridView();
        this.txtSearch = new System.Windows.Forms.TextBox();
        this.butSearch = new System.Windows.Forms.Button();
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
        this.SuspendLayout();
        // 
        // dataGridView1
        // 
        this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Top;
        this.dataGridView1.Location = new System.Drawing.Point(0, 0);
        this.dataGridView1.Name = "dataGridView1";
        this.dataGridView1.RowHeadersWidth = 62;
        this.dataGridView1.RowTemplate.Height = 33;
        this.dataGridView1.Size = new System.Drawing.Size(800, 419);
        this.dataGridView1.TabIndex = 0;
        // 
        // txtSearch
        // 
        this.txtSearch.Dock = System.Windows.Forms.DockStyle.Left;
        this.txtSearch.Location = new System.Drawing.Point(0, 419);
        this.txtSearch.Name = "txtSearch";
        this.txtSearch.Size = new System.Drawing.Size(682, 31);
        this.txtSearch.TabIndex = 2;
        // 
        // butSearch
        // 
        this.butSearch.Dock = System.Windows.Forms.DockStyle.Right;
        this.butSearch.Location = new System.Drawing.Point(688, 419);
        this.butSearch.Name = "butSearch";
        this.butSearch.Size = new System.Drawing.Size(112, 31);
        this.butSearch.TabIndex = 3;
        this.butSearch.Text = "button1";
        this.butSearch.UseVisualStyleBackColor = true;
        this.butSearch.Click += new System.EventHandler(this.butSearch_Click);
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(800, 450);
        this.Controls.Add(this.butSearch);
        this.Controls.Add(this.txtSearch);
        this.Controls.Add(this.dataGridView1);
        this.Name = "Form1";
        this.Text = "Form1";
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private DataGridView dataGridView1;
    private TextBox txtSearch;
    private Button butSearch;
}

2. Code-behind:
C#
public partial class Form1 : Form
{
    DataSet dataSet = new();
    BindingSource bindingSource = new();

    private Random random = new();

    public Form1()
    {
        InitializeComponent();
        InitData();
    }

    private void InitData()
    {
        DataTable dataTable = new();

        dataTable.Columns.Add(new DataColumn("FirstName"));
        dataTable.Columns.Add(new DataColumn("LastName"));
        dataTable.Columns.Add(new DataColumn("Age"));

        for (int i = 0; i < 35000; i++)
        {
            var row = dataTable.NewRow();
            row["FirstName"] = $"FirstName{i:000#}";
            row["LastName"] = $"LastName{i:000#}";
            row["Age"] = random.Next(20, 60);
            dataTable.Rows.Add(row);
        }

        dataSet.Tables.Add(dataTable);

        DataView view1 = new DataView(dataSet.Tables[0]);
        bindingSource.DataSource = view1;

        dataGridView1.AutoGenerateColumns = true;
        dataGridView1.DataSource = bindingSource;
    }

    private void butSearch_Click(object sender, EventArgs e)
        => bindingSource.Filter = txtSearch.Text;
}
 
Share this answer
 
You initialize the LINQ_SEARCH variable to null. If you haven't specified any search criteria, when you get to the LINQ_SEARCH.ToList() line, you will get a NullReferenceException.

Also, if you want to apply multiple search criteria, you need to combine them. At the moment, if both criteria are set, the second one overwrites the first.

It's simple enough to fix:
C#
IEnumerable<HAVALEHA_MODEL> result = LIST_HAVALEHA;

if (!string.IsNullOrEmpty(CUST_N_FLD))
{
    result = result.Where(x => !(x.NAME is null) && x.NAME.IndexOf(CUST_N_FLD, StringComparison.OrdinalIgnoreCase) != -1);
}

if (!string.IsNullOrEmpty(NUMBER_FLD.Text))
{
    result = result.Where(x => !(x.NUMBER is null) && x.NUMBER.IndexOf(NUMBER_FLD.Text.Trim(), StringComparison.OrdinalIgnoreCase) != -1);
}

MY_Data_Ggrid.ItemsSource = result.ToList();

NB: It's better to specify a StringComparison rather than calling ToLowerInvariant; the latter creates a new string for every comparison, whereas the former doesn't.

Since the overload of String.Contains which accepts a StringComparison was only added in .NET Core 2.1, any .NET Framework code will need to use String.IndexOf instead, which returns -1 if the value was not found in the string.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900