【问题标题】:Accessing User's specific data ASPX / .MDF table访问用户的特定数据 ASPX / .MDF 表
【发布时间】:2012-08-14 02:05:24
【问题描述】:

我正在使用 Visual Studio,并且在我的 Default.aspx Web 表单上具有以下 page_load 功能:

if (IsPostBack == false)
        {
            //Display all records on the form load
            DisplayCars("");

我有一个用户,我可以在其中获取他们的用户名(我曾经将其添加为特定数据记录的“创建者”)。我想使用此用户名仅显示用户名 = ACar.Creator 的汽车

我该怎么做呢?为了做到这一点,我已经完成了所有设置。

我需要类似以下的东西:

if (User.Identity.Name == ACar.Creator) {
show this record
}

但我不知道 aspx/sql 中的语法

谢谢

【问题讨论】:

    标签: asp.net sql database mdf


    【解决方案1】:

    您实际上应该通过传递用户名在数据库中执行此操作

    public DataTable GetUserRecord(string userName)
    {
        DataTable dt = new DataTable();
        SqlConnection conn = new SqlConnection("connection string to database");
    
        using(conn)
        {
        string sql = "SELECT car.CarName, car.Model FROM car WHERE car.Creator = @UserName";
        SqlCommand comm = new SqlCommand(sql, conn);
        comm.Parameters.AddWithValue("@UserName", userName);
    
        dt.Load(comm.ExecuteReader());
        }
        return dt;
    }
    

    来自您的页面

    protected void Page_Load(object sender, Eventargs e)
    {
       DataTable dt = GetUserRecord(User.Identity.Name);
       if(dt.Rows.Count > 0)
       {
          string firstRowCarName = dt.Rows[0]["CarName"];
          //etc
       }
    }
    

    【讨论】:

    • 好的,谢谢,这背后的逻辑似乎很好。但是什么是数据表?我以为这是一个可以识别的表函数,但我不知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多