使用数据库数据预填充表单,对象返回null

时间:2015-03-16 05:21:04

标签: c# asp.net .net

背景:我有一个文件:Users.aspx包含一个datagrid,它从数据库中填充用户数据(id,name,email等)。 firstName字段是一个HyperLinkField,单击它时会将您带到User.aspx,这是一个用于编辑用户数据并将新用户插入数据库的页面。

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

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

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

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

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

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

以下是各自的相关代码:

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

1 个答案:

答案 0 :(得分: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