C# 从数据库向表中添加数据
我是.net和C#的新手,我想执行更新/删除。我使用的e模板有一个表。我想从数据库中获取数据并显示在该表中,然后执行更新C# 从数据库向表中添加数据,c#,.net,sql-server,C#,.net,Sql Server,我是.net和C#的新手,我想执行更新/删除。我使用的e模板有一个表。我想从数据库中获取数据并显示在该表中,然后执行更新 protected void Page_Load(object sender, EventArgs e) { SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionStr
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
是表行的id。我知道这不是最好的方法,也不管用
我得到这个错误:
CS0103:名称“Row1”在当前上下文中不存在
我的表行Row1
声明如下:
<td id="Row1" style="width: 73px"> </td>
根据错误,您需要将Row1变量引入范围
TableRow Row1 = new TableRow();
while (rd.Read())
{
Row1.Items.Add(rd[0].ToString());
Table1.Rows.Add(Row1);
}
很明显,正如你所承认的,你是C#的新手,因此有许多事情需要指出,正如在评论中提到的那样
- 如果没有
属性,HTML元素将对代码隐藏不可见。(ASP元素需要此属性。)runat=“server”
- 正如marc_s指出的,您的数据库通信当前会产生运行时错误,因为
没有连接SqlCommand
- 在某个时候,你必须真正熟悉自己
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();
}
}
}
您必须将行1
更改为
<td id="Row1" style="width: 73px" runat="server"> </td>
您的表行Row1
在哪里声明?您能给我们看一下该代码吗?Row1
在哪里创建和设置?代码块中没有任何内容表明Row1
应该在上下文中。您不能在C#codeWell中使用html标记,原因之一是:您正在创建一个SqlConnection
和一个SqlCommand
——但您永远不会将该命令与连接相关联!使用command.Connection=conn
或为SqlCommand
(command-with twom
)使用一个构造函数,该构造函数允许您指定要使用的连接…CommandType。默认值为Text
,不需要显式设置。@marc_--谢谢--没有意识到--我主要使用存储过程。
<td id="Row1" style="width: 73px" runat="server"> </td>