c# - Method error, with mysql -
this question has answer here:
- what nullreferenceexception, , how fix it? 29 answers
i have coded function following, , getting error, trying items details db method returns string.
public static string getitemdetails(int i_id, string i_name) { mysqlconnection sql_con = new mysqlconnection(vpconfig.sql_conns); string[] itemdata = null; i_name = i_name == null ? string.empty : i_name; i_id = i_id == 0 ? 0 : i_id; try { if(i_id != 0) { //get item details id string query = "select * items id="+i_id; mysqlcommand xv = new mysqlcommand(query, sql_con); sql_con.open(); mysqldatareader rdr = xv.executereader(); while(rdr.read()) { itemdata[0] = rdr.getstring("id"); itemdata[1] = rdr.getstring("iname"); itemdata[2] = rdr.getstring("iprice"); } sql_con.close(); string master = itemdata[0] +"*"+ itemdata[1] +"*"+ itemdata[2]; return master;//return format id*name*price } else if(i_name != string.empty) { //get item details name string query = "select * items iname=" + i_name; mysqlcommand xv = new mysqlcommand(query, sql_con); sql_con.open(); mysqldatareader rdr = xv.executereader(); while (rdr.read()) { itemdata[0] = rdr.getstring("id"); itemdata[1] = rdr.getstring("iname"); itemdata[2] = rdr.getstring("iprice"); } sql_con.close(); string master = itemdata[0] + "*" + itemdata[1] + "*" + itemdata[2]; return master;//return format id*name*price } else { messagebox.show("no items! found id/name: " + i_id + i_name); } //if nothing return null; } catch(exception ex) { messagebox.show("error code: 17 "+ex.message); //if nothing return null; }
now, if pass following argument showing error "error code :17 object reference not set instance of object." catch,
string xv = vpfunctions.getitemdetails(5, string.empty); ta.text = xv;
thank you.
the exception thrown because declared string array null , assign value in datareader loop.
so, line:
string[] itemdata = null;
should changed this:
string[] itemdata = new string[5];
Comments
Post a Comment