【发布时间】:2011-05-29 22:38:49
【问题描述】:
您好,我有一个存储过程和一个到数据库的连接。我的网站上有其他类似的代码可以正常工作,但对于我的生活,我无法让它工作。我希望将登录人的用户名作为参数传递。我可以将它存储在会话变量中。 我不确定如何将它从会话变量传输到参数,所以我将它放入标签并以这种方式发送。它表明它已经走得那么远了,但每次我只收到“没有找到”的消息 我已经检查了存储过程,这对我来说似乎很好。下面是代码和存储过程!请帮忙!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class RescueOnlyPages_EditRescueDetails : System.Web.UI.Page
{
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser user;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
user = Membership.GetUser(User.Identity.Name);
Session["user"] = user;
}
}
catch (Exception ex)
{
string msg = ex.Message;
//Log error here
// We have set theme in web.config to Neutral so if there is
// an error with setting themes, an incorrect theme wont be displayed to a customer
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["user"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("@user", userLabel.Text.Trim());
}
try
{
MyConnection.Open();
command.CommandType = CommandType.StoredProcedure;
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
存储过程
ALTER PROC [dbo].[sp_EditRescueDetails]
(
@user nvarchar(50)
)
AS
BEGIN
SELECT [PostalAddress], [Telephone_No], [Website], [Email]
FROM [RescueDetails]
Where [UserName] = @user
End
编辑 * 如果我更改存储过程并删除 ' 其中 [用户名] = @user ' 这条线它毫无问题地带来了每个用户细节,所以我认为这可能与这条线或 command.Parameters.AddWithValue("@user", userLabel.Text.Trim()); 导致我出现问题的行
【问题讨论】:
-
请把您的
MyConnection.Close()呼叫放在finally块中 - 更好的是,将连接包装在using语句中。 :) 除此之外,您能否在调试器中单步执行您的代码并确保某个值肯定会添加到参数中?另外 - 您不需要使用标签来存储用户,您应该使用 local variable -
是的,我在其他代码段中有 finally 块,但我一直在删除和更改此代码以尝试使其正常工作。有什么想法有什么问题吗?它让我发疯!
-
@David Neale 我将它添加到标签中,看看是否有帮助。我已经完成了它,正确的用户名显示在'command.Parameters.AddWithValue("@user", userLabel.Text.Trim());'行在用户标签上。
标签: c# asp.net sql-server-2008 stored-procedures