c# - The ConnectionString property has not been initialized sqlcommand yet code still works -
i've been fan of "if ain't broke dont fix it" code, although functioning, throwing the connectionstring property has not been initialized message. similar posts suggest conneciton string null--- added if isnullorempty
around connection open command. line throwing exception. note: connection string retreived database of connection strings. c# code behind file .aspx page. thank in advance suggestions regarding cause of exception.
the code:
using (sqlconnection sconn = new sqlconnection(someconnectionstring.value.tostring())) { using (sqlcommand scmd = new sqlcommand("mydb.[dbo].[mystoredproc]", sconn)) { scmd.commandtype = commandtype.storedprocedure; scmd.parameters.add("@valuex", sqldbtype.varchar).value = 2; scmd.parameters.add("@returnvalue", sqldbtype.int); scmd.parameters["@returnvalue"].direction = parameterdirection.output; //testing null suggested... if (!string.isnullorempty(sconn.tostring()) || sconn.tostring() != "") //the || != "" may double work.. not sure { sconn.open(); //code throw exception here continues work. sqldatareader adar = scmd.executereader(); if (adar.hasrows) { while (adar.read()) { hiddenfieldx.value = adar["valuex"].tostring(); ... } sconn.close(); } } } } } catch (sqlexception er) { //the connectionstring property has not been initialized thrown here }
as mates stated, connection string may null or not formed.
1- check connection string if correct (you can post , can check)
2- code better if looks this:
string someconnectionstring = "yourconnectionstring"; if (!string.isnullorempty(someconnectionstring)) { using (sqlconnection sconn = new sqlconnection(someconnectionstring)) { using (sqlcommand scmd = new sqlcommand("mydb.[dbo].[mystoredproc]", sconn)) { scmd.commandtype = commandtype.storedprocedure; scmd.parameters.add("@valuex", sqldbtype.varchar).value = 2; scmd.parameters.add("@returnvalue", sqldbtype.int); scmd.parameters["@returnvalue"].direction = parameterdirection.output; sconn.open(); //code throw exception here continues work. sqldatareader adar = scmd.executereader(); if (adar.hasrows) { while (adar.read()) { //... } } sconn.close(); } } }
Comments
Post a Comment