c# - Fill column in DataTable with output from SQL query -
i have datatable structure:
number amount destroyed 1 19 3 22 2 20 3 23 3 11 0 11
the value in destroyed
column manually inserted user. however, i've created table in sql user can add value destroyed
, want take value table. have proper sql query this.
the following example demonstrate.
here output query :
number destroyed type 1 3 papper 2 1 papper
according structure of datatable should insert value destroyed
sql query datatable when
query.number = datatable.number
so according example should like:
number amount destroyed 1 19 3 22 2 20 1 21 3 11 0 11
how accomplish this?
you haven't posted how you're connecting , executing sql statement. using sqlconnection
, friends execute statement:
// each row in datatable... (int = 0; < datatable.rows.count; i++) { // record number equals datatable's "number" column row // select destroyed value: string sql = string.format("select * table number='{0}' destroyed", datatable.rows[i]["number"].tostring()); int destroyedcount = 0; // execute sql query, return value `destroyedcount` using (sqlconnection conn = new sqlconnection(connstring)) { sqlcommand cmd = new sqlcommand(sql); try { conn.open(); destroyedcount = (int)cmd.executescalar(); } catch (exception ex) { console.writeline(ex.message); } } // set table value sql command's returned value datatable.rows[i]["destroyed"] = destroyedcount; // assuming want amount + destroyed = int amountcount = 0; // parse table's current value `amount` try { amountcount = (int)datatable.rows[i]["amount"]; } catch (argumentnullexception argex) { // handle exception } catch (formatexception formatex) { // handle exception } // set `together` column `amount` + `destroyed` datatable.rows[i]["together"] = (amountcount + destroyedcount).tostring(); }
Comments
Post a Comment