简体   繁体   中英

Search in current column of DataGridView using LINQ in C#

I want to search in selected column (current column) an showing result in DataGridView, but when search a value don't show anything in DataGridView
Check my code :

private void txt_search_TextChanged(object sender, EventArgs e)
{
    int columnIndx = dgv_prs_add.CurrentCell.ColumnIndex;
    string columnName = dgv_prs_add.Columns[columnIndx].Name;
    lblPath.Text = columnIndx.ToString() + columnName.ToString();
    var query = (from d in db.tbl_PrsInfos
            where txt_search.Text.Contains(columnName)
            select d).ToList();
    dgv_prs_add.DataSource = query;
}

You should create criteria to filter the records at run time based on the selected column.

You can use Where LINQ method to apply criteria on the table. This method takes criteria in the form of Func<T, bool> and applies to the list at run time.

private void txt_search_TextChanged(object sender, EventArgs e)
{
    int columnIndx = dgv_prs_add.CurrentCell.ColumnIndex;
    string columnName = dgv_prs_add.Columns[columnIndx].Name;
    lblPath.Text = columnIndx.ToString() + columnName.ToString();

    //Assuming that class name is "PersonInfo".
    Func<PersonInfo, bool> criteria;

    var searchString = txt_search.Text;
    //Assuming that columns are "FirstName", "LastName" and "Address".
    switch (columnName)
    {
        case "FirstName":
            criteria = person=> person.FirstName.Contains(searchString);
            break;
        case "LastName":
            criteria = person=> person.LastName.Contains(searchString);
            break;
        case "Address":
            criteria = person=> person.Address.Contains(searchString);
            break;
        default:
            criteria = person=> true;
            break;
    }

    var query = db.tbl_PrsInfos.Where(criteria).ToList();

    dgv_prs_add.DataSource = query;
}

As mentioned in the code, I have assumed some of the things such as ClassName and its properties. You need to put appropriate values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM