Reputation:
I am new to .net and C# and I want to perform update/delete. I am using e template which has a table. I want to get data from database and display in that table and then 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 with database
connection.Open();
//query to select all users with the given username
comand.CommandText = "select * from artikulli ";
rd = comand.ExecuteReader();
if(rd.HasRows )
{
while (rd.Read())
{
Row1.Items.Add(rd[0].ToString());
}
}
connection.Close();
}
Row1
is the id of table row. I know that this is not the best way and it doesn't work.
I get this error:
CS0103: The name 'Row1' does not exist in the current context
My table row Row1
is declared as below:
<td id="Row1" style="width: 73px"> </td>
Upvotes: 0
Views: 75
Reputation: 4059
It's apparent, as you've admitted, you are new to C#, so there are a number of things to point out, as have been addressed in the comments.
runat="server"
attribute. (This attribute is required for ASP elements.)SqlCommand
was not given a connection.To correct your code-behind, it should be more like the 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 with database
connection.Open();
//query to select all users with the given username
command.CommandText = "select * from 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
is an instance of a GridView
created in the aspx page. The list users
should be a list of whatever class you want to create to show user data, which will determine how your GridView
instance will be formatted.
Just to get you to the point where you can see your database query working at all you can instead do the following from your query result (though I definitely recommend implementing the 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 you will have to change your Row1
to
<td id="Row1" style="width: 73px" runat="server"> </td>
Upvotes: 1
Reputation: 13157
Per the error, you'll need to bring your Row1 variable into scope
TableRow Row1 = new TableRow();
while (rd.Read())
{
Row1.Items.Add(rd[0].ToString());
Table1.Rows.Add(Row1);
}
Upvotes: 0