c# - List<T> overwrites all the items inside a foreach loop to the last value -
i'm trying build windows application in there combo box , during load(), i'm population combo box connection strings availabe in app.config file.
here app.config snippet:
<!-- adding multiple servers in connection string--> <connectionstrings> <add name="sqlconnect-1" connectionstring="data source=sahil; initial catalog=recordcomparisontool; integrated security=sspi" providername="system.data.sqlclient"/> <add name="sqlconnect-2" connectionstring="data source=sahil; initial catalog=recordcomparisontool; user id=test; password=12123; integrated security=sspi" providername="system.data.sqlclient"/> <add name="sqlconnect-3" connectionstring="data source=sahil; initial catalog=recordcomparisontool; user id=test; password=32315; integrated security=true" providername="system.data.sqlclient"/> </connectionstrings>
i have created class compareresult in i'm trying values app.config , displaying combo box.
namespace recordcomparisontool_win { public class connectionstring { public string name { get; set; } public string constring { get; set; } public string provider { get; set; } } public class compareresult { public list<connectionstring> getconnection() { list<connectionstring> constr = new list<connectionstring>(); connectionstring conn = new connectionstring(); foreach (connectionstringsettings css in configurationmanager.connectionstrings) { if (!(css.name == "localsqlserver" || css.name == "localmysqlserver")) { conn.name = css.name; conn.constring = css.connectionstring; conn.provider = css.providername; constr.add(conn); } } return constr; } } }
the problem when i'm trying bind combo box, showing 3 records per app.config file, records have same value "sqlconnect-3". i'm unable find reason why list got updated "sqlconnect-3" records. please fix error. here snippet i'm binding list combobox
protected void loadconnection() { compareresult compareresult = new compareresult(); list<connectionstring> connectionstring = new list<connectionstring>(); connectionstring = compareresult.getconnection(); cbtokenleft.datasource = connectionstring; cbtokenleft.displaymember = "name"; cbtokenleft.valuemember = "constring"; }
this:
conn.name = css.name; conn.constring = css.connectionstring; conn.provider = css.providername; constr.add(conn);
overwrites connectionstring
reference each iteration. need allocate new connectionstring
within each loop:
foreach (connectionstringsettings css in configurationmanager.connectionstrings) { if (!(css.name == "localsqlserver" || css.name == "localmysqlserver")) { var conn = new connectionstring { name = css.name; constring = css.connectionstring; provider = css.providername; } constr.add(conn); } }
Comments
Post a Comment