我尝试在我的网站上创建UPDATE功能,以便管理员可以创建/编辑产品类别。我遇到了数据库表不会更新的问题,我似乎无法找到问题的确切位置。我没有收到任何错误消息,它只是将我重定向到Default.aspx页面,这是预期的。
以下是.aspx文件中的代码
<asp:SqlDataSource ID="genrelist" runat="server"
ConnectionString='<%$ConnectionStrings:itemsconnection%>'
SelectCommand="SELECT [ID], [productname] FROM [producttype]">
</asp:SqlDataSource>
<p>Current Categories</p>
<asp:ListView ID="categorylist" runat="server" DataSourceID="genrelist"
DataKeyNames="ID">
<ItemTemplate>
<div class="form-horizontal">
<div class="form-group">
<asp:TextBox ID = "categoryedit"
CssClass="form-control" runat="server" Width="300px"
Text='<%# Eval("productname") %>'></asp:TextBox>
</div>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="updatecategories" CssClass="btn btn-default"
runat="server" OnClick="updatecategories_Click" Text="Save Changes"/>
以下是C#代码
int item = 0;
if (Request.QueryString["ID"] != null)
{
item = int.Parse(Request.QueryString["ID"]);
}
else
{
Response.Redirect("Default.aspx");
}
string connectionString = WebConfigurationManager.ConnectionStrings["itemsconnection"].ConnectionString;
//setup connection object called 'myConnection'
SqlConnection myConnection = new SqlConnection(connectionString);
//open database connection
myConnection.Open();
var ctrl = (Control)sender;
var lvi = (ListViewItem)ctrl.NamingContainer;
var txt = (TextBox)lvi.FindControl("categoryedit");
txt.Visible = false;
string cat = txt.Text;
//create the SQL statement
string query = "UPDATE producttype SET productname = @itemnamenew WHERE ID=@id";
//setup SQL command and use the SQL and myCconnection object
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@itemnamenew", cat);
myCommand.Parameters.AddWithValue("@id", item);
myCommand.ExecuteNonQuery();
我想为代码可能被进一步删除的长问题道歉,但我真的不确定问题出在哪里。感谢。