【问题标题】:My code is jumping to a function when it shouldn't be我的代码不应该跳转到一个函数
【发布时间】:2014-07-07 22:27:53
【问题描述】:

以下是我跟踪志愿者的程序。我的问题是,对于下面的两个函数,当调用fillListBoxData() 时,大约在中途跳转到fillDataGridView 函数。在第 15 行,dataAda1.Fill(datTab3); 程序立即跳转到fillDataGridView(string fullName)。我不知道为什么。

谁能帮助我,让这个程序停止这样做。

public void fillListBoxData()
    {
        //Open connection
        //found in app.config
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Database1ConnectionString))//database ONE
        {
            //open the connection
            conn.Open();

            // Create new DataAdapter
            using (SqlDataAdapter dataAda1 = new SqlDataAdapter("SELECT (firstName + ' ' + lastName) AS NAME FROM dbo.VolunteerContactInfo", conn))
            {
                // Use DataAdapter to fill DataTable
                DataTable datTab3 = new DataTable();
                dataAda1.Fill(datTab3);                

                //assign the dataTable as the dataSource for the listbox
                volList.DataSource = datTab3;
                //display member needed to show text
                volList.DisplayMember = "NAME";
                conn.Close();

            }
        }
    }

void fillDataGridView(string fullName)
    {
        string tableName = "dbo." + fullName;
        // Open connection
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Database2ConnectionString))//database TWO
        {
            //open the connection
            conn.Open();

            // Create new DataAdapter
            using (SqlDataAdapter dataAda = new SqlDataAdapter("SELECT * FROM " + @tableName, conn))
            {
                // Use DataAdapter to fill DataTable
                DataTable datTab = new DataTable();
                dataAda.Fill(datTab);

                volWorkDataGrid.DataSource = datTab;

            }
            conn.Close();
        }
    }

【问题讨论】:

  • 你怎么知道它跳转到fillDataGridView
  • 您的方法fillDataGridView 可能被注册为网格的事件处理程序,并且在填充期间被网格调用。您需要删除该事件处理程序以防止它被调用。
  • 也有可能在调试时调试器在线程之间跳转。
  • @Kevin 我知道它正在跳转到 fillDataGridView,因为我是在 Visual Studio 的调试模式下观看的。该函数正在使我的程序崩溃,因为它没有让 fillListBoxData() 完成。
  • fillDataGridView 中查看您的堆栈跟踪以了解调用的原因。

标签: c# sql sql-server windows winforms


【解决方案1】:

在“初始化”数据时使用临时标志来抑制事件处理程序。

bool _suppressEvent = false;

public void fillListBoxData() 
{
    try
    {
         _suppressEvent = true;

         ...Do whatever you want here
    }
    finally
    {
        _suppressEvent = false;
    }
}

void volList_SelectedIndexChanged(object sender, EventArgs e)
{
    if( _suppressEvent ) return;

    ...
}

try/finally 确保无论 try 子句中发生什么(异常、返回等),您的抑制标志将始终关闭。否则,您可能会遇到一些难以追踪的奇怪行为。

【讨论】:

  • 我的程序仍然没有按预期工作,但这会让我朝着正确的方向前进。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2016-05-26
相关资源
最近更新 更多