.net - System index out range exception C# -


i have following code:

using mysql.data.mysqlclient; using system; using system.collections.generic; using system.data; using system.linq; using system.text; using system.threading.tasks;  namespace timeclock {     class company     {         datatable rows = new datatable();          public company()         {             mysqlconnection connection = null;             try             {                  string connectionstring = timeclock.properties.settings.default.timeclockconnectionstring;                 connection = new mysqlconnection(connectionstring);                 connection.open();                 mysqlcommand command = new mysqlcommand("select * companies id = @id  limit 1", connection);                 command.parameters.addwithvalue("@id", timeclock.properties.settings.default.companyid);                 mysqldataadapter da = new mysqldataadapter(command);                 da.fill(rows);              }             catch (mysql.data.mysqlclient.mysqlexception ex)             {                 console.writeline(ex);             }                         {                 if (connection != null)                 {                     connection.close();                 }             }         }          public string getname()         {             datarow row = rows.rows[0];              return row["company_name"].tostring();         }     } } 

i know why i'm getting error: no records found in database, of course row[0] no exist, hence exception. how deal when there no records store in datatable? way, i'm quite new c# , input great; feel free criticize.

before access collection

datarow row = rows.rows[0]; 

you'll have make sure item exists:

if(rows.count > 0)     datarow row = rows.rows[0]; 

always


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

python - How to remove the Xframe Options header in django? -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -