繁体   English   中英

如何检查用户名是否存在于数据库的特定列中

[英]How to check if Username exists in specific column of database

我正在将C#与ASP.Net表一起使用。 我正在尝试检查用户何时访问我的Web应用程序,该用户ID是否列在该Web应用程序中显示的表格中名为UserID的列中。 如果不是,那么我想将它们重定向到错误页面。

我需要它来检查何时加载页面,因此很明显它需要位于Page_Load 我只是不知道如何在我的表中调用该列并使其检查用户ID。

这是我到目前为止的内容:

protected void Page_Load(object sender, EventArgs e)
{            
    if (!Page.IsPostBack)
    {
        string UserID = HttpContext.Current.Request.LogonUserIdentity.Name.Substring(4);
        SQLUserID();

        if (UserID != //'Whatever values are in the UserID column'//)
        {
            Server.Transfer("ErrorPage.aspx");
        }

        SQLCmd = SqlDataSource1.SelectCommand;
        GridView1.DataBind();
    }
}

字符串UserID给我用户的用户ID。 SQLUserID() = SELECT UserId FROM Info. 我知道我所说的方式不正确,但是我不确定该怎么做。

它可以帮助您:

SqlConnection conn = new SqlConnection(connectionString); 
SqlCommand check_User_Name ("SELECT COUNT(*) FROM tblUser WHERE (UserID=@UserID)",conn);
check_User_Name.Parameters.AddWithValue("@UserID,UserID);
int userExist=(int)check_User_Name.ExecuteScalar();
if(userExist>0)
{
    //Login
}
else
{
   Server.Transfer("ErrorPage.aspx");
}

只需编写您的连接字符串即可。

所以这就是我如何使其在Page_Load下工作

{
string connectionString = "Data Source=###;Initial Catalog=###;Integrated Security=True";
        if (!Page.IsPostBack)                
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();

                using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(UserID) from Info WHERE UserID like @UserID", sqlConnection))
                {
                    string UserID = HttpContext.Current.Request.LogonUserIdentity.Name.Substring(4);                        
                    sqlCommand.Parameters.AddWithValue("@UserID", UserID);
                    int userCount = (int)sqlCommand.ExecuteScalar();
                    if (userCount == 0)
                    {
                        Server.Transfer("ErrorPage.aspx");
                    }

                    SQLCmd = SqlDataSource1.SelectCommand;
                    GridView1.DataBind();
                }
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM