Search code examples
c#sqldatabasewinformssearch

How can i search SQL Server Database while typing in C# Winforms application?


I am showing some sql table results in data grid view in winforms app. I normally use DbEntities but i had to use join in my query to get results from multiple results, so instead i used this code.

And i want to add a query and a textbox to search results while typing. How can i do that from what i already started?

        SqlConnection con = new SqlConnection("server=.; Initial 

        Catalog=winforms;Integrated Security=SSPI");

        DataTable dt = new DataTable();

        string sql = "SELECT Personel.ad, Personel.soyad, Personel.tc, Personel.dogum, Personel.isgiris, Birim.birimad AS [Birim], Sube.subead AS [Şube] FROM Personel JOIN Birim ON Birim.birimid = Personel.birimid JOIN Sube ON Sube.subeid = Personel.subeid";

        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        da.Fill(dt);
        dataGridView1.DataSource = dt;

Solution

  • Found this answer to search in DataTable.

    So for your solution you would need to implement

    public static DataTable SearchInAllColums(this DataTable table, string keyword, StringComparison comparison)
    {
        if(keyword.Equals(""))
        {
            return table;
        }
        DataRow[] filteredRows = table.Rows
           .Cast<DataRow>()
           .Where(r => r.ItemArray.Any(
           c => c.ToString().IndexOf(keyword, comparison) >= 0))
           .ToArray();
    
        if (filteredRows.Length == 0)
        {
            DataTable dtProcessesTemp = table.Clone();
            dtProcessesTemp.Clear();
            return dtProcessesTemp;
        }
        else
        {
            return filteredRows.CopyToDataTable();
        }
    }
    

    And then you could use it in your changeevent:

    void textBox1_TextChanged(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("server=.; Initial 
    
        Catalog=winforms;Integrated Security=SSPI");
    
        DataTable dt = new DataTable();
    
        string sql = "SELECT Personel.ad, Personel.soyad, Personel.tc, Personel.dogum, Personel.isgiris, Birim.birimad AS [Birim], Sube.subead AS [Şube] FROM Personel JOIN Birim ON Birim.birimid = Personel.birimid JOIN Sube ON Sube.subeid = Personel.subeid";
    
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        da.Fill(dt);
    
        dataTable.SearchInAllColums(textBox1.Text, StringComparison.OrdinalIgnoreCase);
    
        dataGridView1.DataSource = dataTable;
    }
    

    HOWEVER: Doing it like this will cause alot of traffic to your sql server. I would strongly suggest you to also implement some form of cache here for getting all searchable data. If that's an option.