Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

winforms - How to filter DataGridView in C# Win Forms?

Guys I have created a simple datagridview through toolbox and selected data through wizard (no code in .cs file) from database. It is working flawlessly as you can see in the picture below. DataGridView1

Now I want to filter the entries in it by contact person name. I have a textbox and search button so when the user enter a "contact person name" such as "Altaf" and then click on search, the gridview should refresh and only entry with ticketid=4 should appear.

The only code in the .cs file is : (it was auto-generated)

       private void Form2_Load(object sender, EventArgs e)
    { 
        this.tblTicketDetailTableAdapter.Fill(this.sTDataSet1.tblTicketDetail); //auto-generated
    }

I tried this in buttonClick event as suggested by someone but it generates error : "Cannot interpret token '{' at position 27"

        BindingSource bs = new BindingSource();
        bs.DataSource = dataGridView1.DataSource;
        bs.Filter = issuerNameDataGridViewTextBoxColumn + "like '%" + txtbxSearch.Text.Trim().Replace("'", "''") + "%'";
        dataGridView1.DataSource = bs.DataSource;

I have no experience in datagridviews or win form coding for that matter, so please explain in detail. Your help is really appreciated.

Regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thank you everyone that has answered to my query, I really appreciate your help guys. You guys are the most helpful bunch.

I have solved my problem by doing following modifications to my code :

    public void btnSearch_Click(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = dataGridView1.DataSource;
        bs.Filter = dataGridView1.Columns[5].HeaderText.ToString() + " LIKE '%" + txtbxSearch.Text + "%'";
        dataGridView1.DataSource = bs;
    }

Thank you again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...