【问题标题】:Pre-populating a form using database data, object coming back null使用数据库数据预填充表单,对象返回 null
【发布时间】:2015-03-16 05:21:04
【问题描述】:

背景:我有一个文件:Users.aspx 包含一个数据网格,其中填充了来自数据库的用户数据(ID、姓名、电子邮件等)。 firstName 字段是一个 HyperLinkField,单击它会转到 User.aspx,该页面旨在编辑用户数据并将新用户插入数据库。

如果用户 ID 存在,则 User.aspx 上的表单将预先填充用户信息(如果不存在,则为空白,以便创建新用户)。

我有三个涉及此功能的 .cs 文件:

  • User.aspx.cs - 检查回发,确定是否需要创建新用户或根据用户 ID 填充表单。

  • User.cs - 包含构造函数的业务类,该构造函数填充用于在 User.aspx.cs 中使用的对象

  • UserDataService.cs - 包含连接/sqlcommands/sqldataadapter 功能

通过调试,在我看来,User 对象正在 User.aspx.cs 中初始化,然后移至 User.cs,并由那里的构造函数成功填充。所有值都正确添加到对象中。然后调试器将我带回 User.aspx.cs,突然间一切都变为空了。显然,因此,我的表单控件没有填充数据。我觉得我可能忽略了一些非常简单的东西,只需要另一双眼睛看着它。

以下是每个的相关代码:

User.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (RouteData.Values["id"] != null)
                {
                    if (RouteData.Values["id"] == "-1")
                    {
                        BuildNew();
                    }
                    else
                    {
                        GetUser(Convert.ToInt32(RouteData.Values["id"]));
                    } // end else
                }
                else
                {
                    BuildNew();
                } // end else
            } // end if
        } // end page_load

        private void BuildNew()
        {
            lblID.Text = "";
        } // end BuildNew()

        private void GetUser(int id)
        {
            // ** PROBLEM - this method is initially creating the User object based on the id parameter (using User.cs's User(int id) constructor.  The fields are all being filled in over there and then once it comes back to here, all of the values become null.**

            User u = new User(id);
s            lblID.Text = u.UserId.ToString();
            txtUserFirstName.Text = u.First;
            txtUserLastName.Text = u.Last;
            txtUserEmail.Text = u.Email;
            txtUserPassword.Text = u.Password;
            rblUserRole.SelectedValue = u.Role;
            txtUserLastLogin.Text = u.Lastlogin.ToShortDateString();
            rblUserRole.SelectedValue = u.IsActive.ToString();
}

User.cs:

public User(int id) //WORKING
        {
            DataTable dt = UsersDataService.GetByID(id);
            User u = new User();
            int rowcount = dt.Rows.Count;
            if (dt.Rows.Count > 0)
            {
                u.UserId = (Int32)dt.Rows[0]["UserID"];
                u.First = (string)dt.Rows[0]["First"];
                u.Last = (string)dt.Rows[0]["Last"];
                u.Email = (string)dt.Rows[0]["Email"];
                u.Password = (string)dt.Rows[0]["Password"];
                u.Role = (string)dt.Rows[0]["Role"];
                u.Lastlogin = (DateTime)dt.Rows[0]["LastLogin"];
                u.Created = (DateTime)dt.Rows[0]["Created"];
                u.Updated = (DateTime)dt.Rows[0]["Updated"];
                u.IsActive = (bool)dt.Rows[0]["Active"];
            }
            else
            {
                u = null;
            }
        } // end User

UsersDataService.cs:

public static DataTable GetByID(int id) // WORKING
        {

            DataTable dt = new DataTable();

            SqlConnection cn =
                new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString.ToString());
            // sqlcommand using the stored procedure, connection
            SqlCommand cmd = new SqlCommand("SP_GetUsersByID", cn);
            // add the id parameter
            cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = id;
            // declare the commandtype as a stored procedure
            cmd.CommandType = CommandType.StoredProcedure;
            try
            {
                // open the connection
                cn.Open();
                // declare a data adapter
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                // fill the datatable
                da.Fill(dt);
            }
            catch (Exception ex)
            {
                DataExceptions.Add(ex.ToString());
            }
            finally
            {
                cn.Close();
            }
            return dt;
        } // end GetByID

【问题讨论】:

  • 为什么要在构造函数中使用`User u = new User();`创建自引用对象,不要这样做,而是直接分配使用this的属性值。
  • 不要在构造函数中创建用户对象,只需像这样使用this.UserId

标签: c# asp.net .net


【解决方案1】:

您正在使用User u = new User(); 在构造函数中创建自引用对象。您需要像这样在构造函数中进行更改,并且需要阅读大量有关构造函数的工作原理,

public User(int id) //WORKING
        {
            DataTable dt = UsersDataService.GetByID(id);
            if (dt.Rows.Count > 0)
            {
                this.UserId = (Int32)dt.Rows[0]["UserID"];
                this.First = (string)dt.Rows[0]["First"];
                this.Last = (string)dt.Rows[0]["Last"];
                this.Email = (string)dt.Rows[0]["Email"];
                this.Password = (string)dt.Rows[0]["Password"];
                this.Role = (string)dt.Rows[0]["Role"];
                this.Lastlogin = (DateTime)dt.Rows[0]["LastLogin"];
                this.Created = (DateTime)dt.Rows[0]["Created"];
                this.Updated = (DateTime)dt.Rows[0]["Updated"];
                this.IsActive = (bool)dt.Rows[0]["Active"];
            }
        } 

为了更好地使用,您可以创建Object 列表from the datatable

【讨论】:

  • 谢谢。你说得对,我还有很多东西要学。我还是比较缺乏经验。感谢您的快速帮助。
猜你喜欢
  • 1970-01-01
  • 2020-11-11
  • 2018-08-15
  • 1970-01-01
  • 2017-12-09
  • 2012-08-14
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
相关资源
最近更新 更多