【问题标题】:unable to cast object of type 'system.windows.forms.bindingsource' to type 'system.data.datatable'无法将“system.windows.forms.bindingsource”类型的对象转换为“system.data.datatable”类型
【发布时间】:2018-02-14 16:23:26
【问题描述】:

我遇到以下异常

无法将“system.windows.forms.bindingsource”类型的对象转换为“system.data.datatable”类型

这是我的方法

private void GridViewStudentsList_RowValidated(object sender, DataGridViewCellEventArgs e) {
    try {
        BindingSource bindingSource = (BindingSource) GridViewStudentsList.DataSource;
        DataTable changes = (DataTable) bindingSource.DataSource;
        changes.GetChanges();
        if (changes != null) {
            OracleConnection con = new OracleConnection(connection);
            con.Open();
            OracleDataAdapter adapter = new OracleDataAdapter();
            OracleCommandBuilder mcb = new OracleCommandBuilder(adapter);
            adapter.UpdateCommand = mcb.GetUpdateCommand();
            adapter.Update(changes);
            changes.AcceptChanges();
            MessageBox.Show("Cell Updated");
            con.Close();
            return;
        }
    } catch (Exception ex) {
        MessageBox.Show(ex.Message);
    }
}

【问题讨论】:

  • 那么你有没有试过调试它并偷看bindingSource.DataSource是什么类型?
  • bindingSource.DataSource = 'bindingSource.DataSource' 引发了“System.NullReferenceException”类型的异常
  • bindingSource.DataSource = {College_Management_System.ViewStudentData}
  • 现在我已将 DataTable 更改为 DataSet 现在它可以工作但再次显示错误\“由于对象的当前状态,操作无效”
  • 新的异常在哪一行抛出?

标签: c# .net c#-4.0 .net-core


【解决方案1】:

我犯了一些小错误

下面的代码是工作代码

    private void GridViewStudentsList_RowValidated(object sender, DataGridViewCellEventArgs e)
  
 {


        try
       
          {
            
            BindingSource bindingSource = (BindingSource)GridViewStudentsList.DataSource;

            DataSet changes = (DataSet)bindingSource.DataSource;

            changes.GetChanges();

            if (changes != null)
            {
                OracleConnection con = new OracleConnection(connection);
                con.Open();
                OracleDataAdapter adapter = new OracleDataAdapter("select * from students_list",con );
                GridViewStudentsList.EndEdit();
               OracleCommandBuilder mcb = new OracleCommandBuilder(adapter);
           
                adapter.UpdateCommand = mcb.GetUpdateCommand(true);
              
         
                adapter.Update(changes,"students_list");
               changes.AcceptChanges();

                MessageBox.Show("Cell Updated");
               // GridViewStudentsList.EndEdit();
                con.Close();
                return;
            }


        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.StackTrace);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 2016-09-20
    相关资源
    最近更新 更多