c# - Add data to a table from database -
i new .net , c# , want perform update/delete. using e template has table. want data database , display in table , perform update.
protected void page_load(object sender, eventargs e) { sqlconnection connection = new sqlconnection(configurationmanager.connectionstrings["registrationconnectionstring"].connectionstring); sqldatareader rd; sqlcommand comand = new sqlcommand(); //open connection database connection.open(); //query select users given username comand.commandtext = "select * artikulli "; rd = comand.executereader(); if(rd.hasrows ) { while (rd.read()) { row1.items.add(rd[0].tostring()); } } connection.close(); }
row1
id of table row. know not best way , doesn't work.
i error:
cs0103: name 'row1' not exist in current context
my table row row1
declared below:
<td id="row1" style="width: 73px"> </td>
it's apparent, you've admitted, new c#, there number of things point out, have been addressed in comments.
- html elements not going visible code-behind without
runat="server"
attribute. (this attribute required asp elements.) - as marc_s pointed out, database communication produce run-time error,
sqlcommand
not given connection. - at point must familiarize the using statement.
to correct code-behind, should more following:
protected void page_load(object sender, eventargs e) { using (sqlconnection connection = new sqlconnection(configurationmanager.connectionstrings["registrationconnectionstring"].connectionstring)) { using (sqlcommand command = connection.createcommand()) { //open connection database connection.open(); //query select users given username command.commandtext = "select * artikulli "; list<object> users = new list<object>(); using (sqldatareader rd = command.executereader()) { if (rd.hasrows) { while (rd.read()) { users.add(rd[0].tostring()); } } } mygridview.datasource = users; mygridview.databind(); } } }
where mygridview
instance of gridview
created in aspx page. list users
should list of whatever class want create show user data, determine how gridview
instance formatted.
just point can see database query working @ can instead following query result (though recommend implementing gridview
eventually):
system.text.stringbuilder sb = new system.text.stringbuilder(); using (sqldatareader rd = command.executereader()) { if (rd.hasrows) { while (rd.read()) { sb.append(rd[0].tostring()); sb.append("<br />"); } } } row1.innerhtml = sb.tostring();
and have change row1
<td id="row1" style="width: 73px" runat="server"> </td>
Comments
Post a Comment