c# - Datareader, not all paths returns a value -
i want make function returns string:
public string lienbasedeconnaissance(string entreprise) { sqlconnection cnx = new sqlconnection("/* connection string */"); cnx.open(); sqlcommand requeteexiste = new sqlcommand("sp_sel_lien_baseconnaissance_extranet_client", cnx); requeteexiste.commandtype = commandtype.storedprocedure; sqlparameter parameter = requeteexiste.parameters.add("@nom_entreprise", sqldbtype.nvarchar, 15); parameter.value = entreprise; string lienbaseconnaissance; sqldatareader _readerlines = requeteexiste.executereader(); while (_readerlines.read()) { if (_readerlines["parstrp1"].tostring() != null) { lienbaseconnaissance = _readerlines["parstrp1"].tostring(); return lienbaseconnaissance; } else { return null; } } cnx.close(); }
i select data stored procedure , return string
. problem if don't put return after while ()
, code doesn't return value. need variable lienbaseconnaissance
contains data , out of while()
, variable in question doesn't have anymore value i'm looking for.
the problem while
-loop. it's not if
, possible loop never entered if there no rows.
the simplest solution assign default value return variable:
string lienbaseconnaissance = null; // .... @ end of method: return lienbaseconnaissance;
since (i assume that) reading single value possible:
if(_readerlines.read()) { if (!_readerlines.isdbnull("parstrp1")) { lienbaseconnaissance = _readerlines.getstring("parstrp1"); return lienbaseconnaissance; } else { return null; } } else return null;
note should use using
-statement ensure unmanaged resources disposed (e.g. connection gets closed). use implements idisposable
, connection, command , reader.
Comments
Post a Comment