c# - SqlDataReader null exception -


i have sqldatareader fills multiple textboxes, issue when null exception dont know how handle.

 sqlcommand command = new sqlcommand("select * zajezd akce='" + akce + "' , rocnik='" + klientclass.rocnik() + "'", spojeni);                 spojeni.open();                 sqldatareader read= command .executereader();                  if (read.read())                 {                  s_ub_cen.text = read.getdecimal(59).tostring();                 object nulldate = (s_ub_dat.text = read.isdbnull(61) ?                     string.empty : read.getdatetime(61).toshortdatestring());  } 

exception: system.data.sqltypes.sqlnullvalueexception: data null.

i have 20 textboxes, there easy solution? leave textboxes empty when value null, working fine shortdatstring.

i need figure out how handle when value db null:

s_ub_cen.text = precti2.getdecimal(59).tostring(); 

thank much.

you need check isdbnull:

if(!precti2.isdbnull(59)) {     s_ub_cen.text = precti2.getdecimal(59).tostring(); } 

also, prevent sql-injection using sql-parameters, don't concatenate strings build sql query.

instead of:

sqlcommand command = new sqlcommand("select * zajezd akce='" + akce + "' , rocnik='" + klientclass.rocnik() + "'", spojeni); 

this:

using(var command = new sqlcommand("select * zajezd akce=@akce , rocnik=@rocnik", spojeni)) {     command.paramaters.addwithvalue("@akce", akce);     command.paramaters.addwithvalue("@rocnik", klientclass.rocnik());     // .... } 

edit

is there solution solve 20 textboxes ?

in general there no automatism. have provide sql-parameter every dynamic input.

however, if looking elegant way "safe-string" use extension:

public static class dataextensions {     public static string getsafestring(this sqldatareader reader, int colindex)     {         if (!reader.isdbnull(colindex))             return reader[colindex].tostring();         else             return string.empty;     } } 

you use method in way:

_ub_cen.text = reader.getsafestring(59); 

Comments

Popular posts from this blog

c++ - Linked List error when inserting for the last time -

java - activate/deactivate sonar maven plugin by profile? -

java - What is the difference between String. and String.this. ? -