附加信息:无法将“System.Windows.Forms.BindingSource”类型的对象强制转换为“System.Data.DataTable”类型

时间:2013-12-11 13:52:44

标签: c# winforms datagridview

我的代码遇到了一个奇怪的问题。我正在为我的数据网格编写一个过滤器。

每当用户清除文本字段时,都会显示以下错误消息:

  

无法将'System.Windows.Forms.BindingSource'类型的对象强制转换为   输入'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 = "";
    }

2 个答案:

答案 0 :(得分:2)

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 = "";
}

答案 1 :(得分:1)

DataTable dt = ((DataView)gridView1.DataSource).Table;

DataView dv = (DataView)gridView1.DataSource;