使用DataView

时间:2017-05-03 17:44:17

标签: c# winforms datagridview

我有一个文本框,用于从我的数据库中搜索客户。

这是我的代码:

DataView dv = new DataView(tabSearchCustomer);
dv.RowFilter = string.Format("CONVERT({0},System.String) LIKE '%{1}%'", "ID", txtboxSearchCustomer.Text);
dgvCustomers.DataSource = dv; 

dgvCustomers.DataSource = dv只显示新数据,它不会在dgv中替换它。

我希望我的dgv会更新我搜索到的新数据(替换dgv中的旧数据),我该怎么做?

搜索前我的dgv: enter image description here

搜索后我的dgv:enter image description here

1 个答案:

答案 0 :(得分:0)

public static DataTable ExecuteQuery(string storedProcedure, SqlParameter[] parameters)
{
    using (SqlConnection sqlConnection = new SqlConnection(DLLConfig.GetDataBaseConnection()))
    {
        DataTable dataTable = new DataTable();

        SqlCommand sqlCommand = new SqlCommand(storedProcedure, sqlConnection);
        sqlCommand.CommandTimeout = 0;
        sqlCommand.CommandType = CommandType.StoredProcedure;

        foreach (SqlParameter param in parameters)
        {
            sqlCommand.Parameters.Add(param);
        }

        SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand);
        sqlAdapter.Fill(dataTable);

        SqlConnection.ClearAllPools();

        return dataTable;
    }
}

用法:

dataGridView1.DataSource = ExecuteQuery().DefaultView;