【问题标题】:Code not following sequential order in source代码不遵循源代码中的顺序
【发布时间】:2015-05-11 13:50:37
【问题描述】:

我有一个设置表单,上面有一个组合框,我想在加载表单时使用从访问数据库返回的数据来填写该组合框。

我遇到的困难实际上是设置组合框的数据源 - 当程序执行时,它会从填充 OleDbDataAdapter 跳转到加载表单;跳过代码。

这是我最新的代码:

表单加载

        private void frm_settings_Load(object sender, EventArgs e)
    {
        Divisions divs = new Divisions();
        DataSet ds = new DataSet();


        ds = divs.GetActiveDivisions(); //jumps from here to loading the form
        this.cmbo_divisions.DataSource = ds; //this never gets invoked
    }

还有师类

    class Divisions
{
    private string error;

    public string Error //read only
    {
        get { return this.error; }
    }

    public DataSet GetActiveDivisions()
    {
        OleDbConnection conn = new OleDbConnection();

        PinnacleConnection Pconn = new PinnacleConnection();
        string sql = "SELECT ID, title FROM Divisions WHERE active = true;";
        DataSet ds = new DataSet();
        //connect to db
        conn = Pconn.createConnection();

        try
        {
            conn.Open();
        }
        catch (Exception ex)
        {
            //error handling here
            this.error = ex.Message;
            return ds;
        }

        OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
        adapter.Fill(ds); //!!jumps from here to loading the form!!
        conn.Close(); //never gets invoked?
        return ds; //never gets invoked?
    }
}

正如您在我的 cmets 中看到的那样,执行会跳过 cmbo_divisions 对象上的数据源设置...导致组合框为空。

我很茫然,任何帮助将不胜感激。

【问题讨论】:

  • 可能抛出异常。首先,您应该在调试器中打开“异常停止”功能,这样可以更容易地找到此类问题。此外,您可能希望对 all 数据库代码进行尝试捕获(您可能还需要一些 using 语句。
  • 我想你是在出错,并从你的捕获中返回空的 DataSet
  • 当我单步执行代码时,catch 语句并没有被执行……
  • 使用这个:this.cmbo_divisions.DataSource = ds.Tables[0];
  • 感谢电子蝙蝠!成功了!

标签: c# ms-access combobox oledbconnection


【解决方案1】:

我的最佳猜测是adapter.Fill 会引发异常或包含消息泵。所以首先测试这些场景。

【讨论】:

    【解决方案2】:

    你不需要使用数据集,数据表更适合这个:

    DataTable dt= new DataTable();
    ...
    adapter.Fill(dt); 
    

    并且绑定将直接到数据表,因此您可以尽可能避免使用数据集,因为它们是更重的对象:

    this.cmbo_divisions.DataSource = dt;
    

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多