我有以下C#
protected void sprint_availability_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
string sprintid = "";
Label lbl = (sprint_availability.Items[e.ItemIndex].FindControl("sprint_id_lbl")) as Label;
if (lbl != null)
sprintid = lbl.Text;
string projectid = "";
Label pid = (sprint_availability.Items[e.ItemIndex].FindControl("project_id_lbl")) as Label;
if (pid != null)
projectid = pid.Text;
string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(ConnectionString);
myConnection.Open();
String query = "DELETE FROM sprints WHERE [sprint_id] = '" + sprintid + "'";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("project.aspx?project_id="+ pid);
}
SQL查询工作正常,因为删除行没有任何问题,但重定向重定向到http://project.aspx?project_id=System.Web.UI.WebControls.Label
这是asp代码的一部分,显示我试图调用的标签
<asp:Label Text='<%# Eval("project_id") %>' runat="server" ID="project_id_lbl" Visible="false"/><br />
答案 0 :(得分:2)
Pid是Label
,将其添加到字符串中,就像在重定向调用中一样,调用类方法ToString(),如果是Label,则此方法会打印出类名。
您需要使用
Response.Redirect("project.aspx?project_id="+ pid.Text);
但是,在您的代码中,有一个潜在的错误需要尽快修复。不要使用字符串连接来构建SQL查询。使用参数化查询
string query = "DELETE FROM sprints WHERE [sprint_id] = @id";
string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using(SqlConnection myConnection = new SqlConnection(ConnectionString))
using(SqlCommand myCommand(query, myConnection))
{
myConnection.Open();
myCommand.Parameters.Add("@id", SqlDbType.NVarWChar).Value = sprintid;
myCommand.ExecuteNonQuery();
}
字符串连接会导致Sql注入和解析问题。虽然。在你的情况下,这似乎是不可能的,每次使用这种方法更好,以避免任何陷阱。在using语句中包含诸如连接和命令之类的一次性对象可确保正确关闭和处理这些对象