以下是我跟踪志愿者的计划。我的问题是,使用下面的两个函数,当调用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();
}
}
答案 0 :(得分:2)
使用临时标志来抑制事件处理程序,同时初始化"你的数据。
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子句中发生什么(例外,返回等),您的抑制标志将始终关闭。否则,您可能会遇到一些难以追踪的奇怪行为。