winforms - C# Windows Forms, Combobox MouseClick event getting fired multiple times -
i have windows form many controls. tiny part of logging in sql server , fetching list of database names , assigning collection combobox.
private void initializecomponent() { //... //... this.servertb = new system.windows.forms.textbox(); this.usernametb = new system.windows.forms.textbox(); this.passwordtb = new system.windows.forms.textbox(); //... //... this.servertb.textchanged += new system.eventhandler(this.onsqlserverchanged); this.usernametb.textchanged += new system.eventhandler(this.onsqlserverchanged); this.passwordtb.textchanged += new system.eventhandler(this.onsqlserverchanged); this.databasecmbbox = new system.windows.forms.combobox(); //... //... this.databasecmbbox.mouseclick += new system.windows.forms.mouseeventhandler(this.databasecmbbox_click); //.... } private void databasecmbbox_click(object sender, mouseeventargs e) { messagebox.show(sender.gettype().tostring()); this.cursor = cursors.ibeam; list<string> dblist = new list<string>(); dblist = getdatabaselist(); databasecmbbox.datasource = dblist; databasecmbbox.selectedindex = -1; if (dblist.count > 0) { databasecmbbox.mouseclick -= databasecmbbox_click; } databasecmbbox.focus(); this.cursor = cursors.default; } protected list<string> getdatabaselist() { list<string> list = new list<string>(); string constring = "server=" + servertb.text + ";uid=" + usernametb.text + ";pwd=" + passwordtb.text + "; database=master"; try { using (sqlconnection con = new sqlconnection(constring)) { con.open(); using (sqlcommand cmd = new sqlcommand("select name sys.databases name not in ('master', 'model', 'tempdb', 'msdb') ", con)) { using (idatareader dr = cmd.executereader()) { while (dr.read()) { list.add(dr[0].tostring()); } dr.close(); } cmd.dispose(); } con.close(); } } catch(sqlexception ex) { databasecmbbox.mouseclick -= databasecmbbox_click; messagebox.show(ex.message); servertb.focus(); } return list; } private void onsqlserverchanged(object sender, eventargs e) { databasecmbbox.mouseclick += databasecmbbox_click; }
i don't have problem in fetching list of databases. takes 10 seconds so. messagebox in event handler, found out mouseclick event, no apparent reason, gets fired 38 times. same thing happens if use enter event or click event, instead of mouseclick event.
why happen, , how 1 go using these kind of events?
thanks in advance, rps.
if want list of databases, why don't on combobox value changed event?
anyways,i see doing
private void onsqlserverchanged(object sender, eventargs e) { databasecmbbox.mouseclick += databasecmbbox_click; }
this should solve problem
private void onsqlserverchanged(object sender, eventargs e) { databasecmbbox.mouseclick -= databasecmbbox_click; databasecmbbox.mouseclick += databasecmbbox_click; }
Comments
Post a Comment