我的代码有一个奇怪的问题。我目前正在为我的数据网格编写过滤器。
每当用户清除文本字段时 - 会出现以下错误消息:
Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'System.Data.DataTable'.
到目前为止,这是我的代码:
private void driverNo_TextChanged(object sender, EventArgs e)
{
// if driverNo text is empty then return all rows
if (string.IsNullOrEmpty(driverNo.Text))
{
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Empty;
return;
}
// if driverNo is a numerical value then view result
int temp;
if (int.TryParse(driverNo.Text, out temp))
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = "DriverNo = " + driverNo.Text;
else
MessageBox.Show("Invalid driver number.");
driverNo.Text = "";
}
请您参考如下方法:
DataSource的值是BindingSource的类型,不是DataTable。基本上你的期望是不正确的。 DataTable 可能实际上支持 BindingSource。
您的 WinForms 设计界面上很可能有一个 BindingSource 组件。您可以通过以下方式进入表格:
var bindingSource = this.myBindingSource;
var dt = (DataTable)bindingSource.DataSource;
您可以通过以下方式间接获取它:
var bindingSource = (BindingSource)dataGridView1.DataSource;
var dt = (DataTable)bindingSource.DataSource;
对于您的代码,它可能如下所示:
private void driverNo_TextChanged(object sender, EventArgs e)
{
// if driverNo text is empty then return all rows
if (string.IsNullOrEmpty(driverNo.Text))
{
var bindingSource = (BindingSource)dataGridView1.DataSource.
var table = (DataTable)bindingSource.DataSource;
table.DefaultView.RowFilter = string.Empty;
return;
}
// if driverNo is a numerical value then view result
int temp;
if (int.TryParse(driverNo.Text, out temp))
{
var bindingSource = (BindingSource)dataGridView1.DataSource.
var table = (DataTable)bindingSource.DataSource;
table.DefaultView.RowFilter = "DriverNo = " + driverNo.Text;
}
else
MessageBox.Show("Invalid driver number.");
driverNo.Text = "";
}
