Windows Form Combobox DropDown event causing dialog form to lose focus
I'm creating a settings form that is quite similar to the Visual Studio 2008 "开发者_开发知识库Connect To Database" form in the Server Explorer.
The settings form is opened as a modal dialog from the parent form as follows:
private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
{
var SettingsForm = new frmSettings();
SettingsForm.ShowDialog(this);
}
On the SettingsForm, I have a ComboBox that will populate its list with the SQLServer instance names available on the network through the following code in the DropDown event:
private void cboTrackingServerName_DropDown(object sender, EventArgs e)
{
DataTable dt = SmoApplication.EnumAvailableSqlServers(false);
if (dt.Rows.Count > 0)
{
cboTrackingServerName.Items.Clear();
foreach (DataRow row in dt.Rows)
{
cboTrackingServerName.Items.Add(
row["Server"] + "\\" + row["Instance"]);
}
}
}
The problem is that whenever the user clicks the DropDown arrow on the ComboBox, the SettingsForm loses focus to its parent form for a quick second, the SettingsForm appears to redraw itself, and then the SettingsForm regains focus. This also causes the actual DropDown list not to appear until the user clicks it again.
Any helpful thoughts on the matter?
You should probably do this earlier in the dialog life cycle, like Form_Load. Also, even if you needed to do it here, don't keep reloading the list. Check to see if the list is already loaded. Otherwise you will wipe out the current selection everytime the user opens the dropdown.
Instead of using the DropDown event for fetching Available Server Instances the best approach would be to use the Form.Load
Event.
But if for some reason you want to fill the list when user opens the drop down then the you should use ComboBox.Click
Event.
In latter approach when you click on combo-box to open its dropdown, first the click event will be raised and then DropDown Event and hence no refreshing and lost of dropdown. However there will still be a little lag in clicking and opening of dropdown. For quick and perfect solution go with form load event.
精彩评论