如何使用数据网格进行搜索

时间:2013-02-02 23:15:45

标签: c# datagridview

我想在按下搜索按钮时从文本框中取出字符串,然后我希望突出显示放置该数据网格的行。我相信这是可能的。我不知道如何做到这一点。请帮帮我。

string query = " SELECT * FROM suboffice where so_id like '%" + sor_id.Text + "%' ";
            SqlConnection objConn = new SqlConnection(connectionString);
            objConn.Open();
            SqlDataAdapter   subofficeTableAdapter1 =new SqlDataAdapter(query,objConn);
            SqlCommandBuilder cBuilder = new SqlCommandBuilder(subofficeTableAdapter1);
            DataTable dTable = new DataTable();
            subofficeTableAdapter1.Fill(dTable);
            dataGridView1.DataSource = dTable;
            subofficeTableAdapter1.Update(dTable);

其中sor是一个搜索选项卡,当我在运行时放入任何东西时,我的数据网格视图会更新。该程序将在c#

中完成

1 个答案:

答案 0 :(得分:0)

如果您使用的是Windows窗体,这是一个开始。如果要实现某种功能,例如“查找下一个”,“查找上一个”,“全部查找”等,您可能需要为您的目的修改代码。

以下假设您有一个名为SearchButton的Button,一个名为SearchTextBox的文本框和一个名为MyDataGridView的DataGridView。以下代码位于搜索按钮的点击事件中。

    private void SearchButton_Click(object sender, EventArgs e)
    {
        MyDataGridView.ClearSelection(); //this will clear any currently selected cells
        string searchstring = SearchTextBox.Text;
        foreach (DataGridViewRow r in MyDataGridView.Rows)
            foreach (DataGridViewCell c in r.Cells)
            if (c.Value.ToString().Contains(searchstring))
            {
                r.Selected = true; //this will highlight the entire row
                break; //if you want to "Select All" that are found, take this line out
            }
    }