sql - How to retrieve row values from a DataTable in c# -
i trying execute sql query in c# , store result in datatable
variable. , want values particular row. here code.
string query = "select * deptment dname=@dname"; con.open(); sqlcommand cmd = new sqlcommand(query, con); cmd.parameters.addwithvalue("@dname", combobox1.selectedtext); sqldatareader dr = cmd.executereader(); datatable dt = new datatable(); dt.load(dr); textbox2.text = dt.rows[0][0].tostring(); dept_name.text = dt.rows[0][1].tostring(); textbox1.text = dt.rows[0][2].tostring(); no_of_employees.text = dt.rows[0][3].tostring(); dept_discription.text = dt.rows[0][4].tostring(); con.close();
but getting error:
there no row @ position 0.
obviously no result. avoid exception add check
if (dt.rows.count > 0) { textbox2.text = dt.rows[0][0].tostring(); dept_name.text = dt.rows[0][1].tostring(); textbox1.text = dt.rows[0][2].tostring(); no_of_employees.text = dt.rows[0][3].tostring(); dept_discription.text = dt.rows[0][4].tostring(); }
and work column names instead if index values dt.rows[0]["name"]
. leads errors when change table structure.
Comments
Post a Comment