将BindingSource.Filter
过滤器应用于已加载到您的DataGridView
. 因此,如果您显示了帐户,并且您正在寻找一个特定的帐户,那么您将按帐号过滤该数据。
,Filter
无法为您运行另一个 SQL 查询。
如果您想INNER JOIN
对该数据执行一次搜索,那么您将需要执行另一次搜索并加载DataGridView
. 听起来您不想执行过滤器,但您想在同一网格中的数据上显示两个单独的集合。
您的基本流程是:
- 加载你的 DataGridView
- 使用选择他们想要的过滤器或记录
- 使用您的 INNER JOIN 执行第二次搜索
- 使用新数据重新加载 DataGridView。
编辑这里是一些可能让你开始的代码:
如何:将数据绑定到 Windows 窗体 DataGridView 控件
private void GetData(string selectCommand)
{
try
{
// Specify a connection string. Replace the given value with a
// valid connection string for a Northwind SQL Server sample
// database accessible to your system.
String connectionString =
"Integrated Security=SSPI;Persist Security Info=False;" +
"Initial Catalog=Northwind;Data Source=localhost";
// Create a new data adapter based on the specified query.
dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
// Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
// Resize the DataGridView columns to fit the newly loaded content.
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}
private void Button1_Click(object sender, EventArgs e)
{
// Bind the DataGridView to the BindingSource
// and load the data from the database.
dataGridView1.DataSource = bindingSource1;
GetData("select * from Customers");
}
将数据绑定到网格后,您将为用户提供某种过滤方式,但您希望他们再次搜索数据。因此,您将希望在代码中使用某种方式来选择要运行的 SQL。因此,您可以将 SQL 作为您根据用户选择设置的字符串传递给 GetData()
private void Button1_Click(object sender, EventArgs e)
{
// Bind the DataGridView to the BindingSource
// and load the data from the database.
dataGridView1.DataSource = bindingSource1;
string sqlQuery = string.Empty;
if(your check goes here)
{
sqlQuery = "select * from Customers";
}
else
{
sqlQuery = "your new SQL";
}
GetData(sqlQuery);
}
然后您将根据新查询重新绑定您的数据。