【问题标题】:Issue with method方法问题
【发布时间】:2011-04-21 22:44:44
【问题描述】:

我还有一个问题。我的方法:

public StudentProfile GetFullStudentProfile(int userID)
{
    SqlConnection conn = new SqlConnection(Config.DbConnectionString);
    SqlCommand cmd = new SqlCommand("GetFullUserProfile", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Add(new SqlParameter("@UserID", SqlDbType.Int));
    cmd.Parameters["@UserID"].Value = userID;
    StudentProfile sp = null;
    try
    {
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

        if (reader.Read())
        {
            sp = new StudentProfile((int)reader["UserID"], (string)reader["UserName"], (string)reader["UserFamilyName"], (DateTime)reader["UserBirthDay"], (string)reader["UserTelephone"], (string)reader["UserEmail"], (DateTime)reader["UserRegDate"], (string)reader["UserComment"], (bool)reader["UserActive"]);
        }

        reader.Close();

    }
    catch (Exception ex)
    {
        //lbl.Text = ex.Message;
    }
    finally
    {
        conn.Close();
    }
    return sp;
}

WebUserControl 中的代码:

protected void ddlStudents_SelectedIndexChanged(object sender, EventArgs e)
{
    CatalogAccess ca=new CatalogAccess();
    lblEmail.Visible = true;
    lblName.Visible = true;

    lblTelephone.Visible = true;
    HiddenID.Value = ddlStudents.SelectedValue;
    lblName.Text = HiddenID.Value;
    lblEmail.Text = ca.GetFullStudentProfile(ddlStudents.SelectedIndex).UserEmail;
    lblFamilyName.Visible = true;
    lblBirth.Visible = true;
    ddlStudents.Items.Clear();
    PopulateStudentsDDL();

}

当我运行代码时出现异常

我是否正确理解问题出在方法 GetFullStudentProfile() 中?如果是这样,如何解决?

我认为问题是:

StudentProfile sp = null;

所以它说变量 sp 没有用 try 块中的数据填充。是吗?

现在添加 StudentProfile.cs 类列表:

public class StudentProfile

{ public StudentProfile(int userID, string userName, string userFamilyName, DateTime userBirthDay, string userTelephone, string userEmail,DateTime userRegDate, string userComment, bool userActive) { 用户 ID = 用户 ID; 用户名 = 用户名; 用户家庭名称 = 用户家庭名称; 用户生日 = 用户生日; 用户电话 = 用户电话; 用户邮箱 = 用户邮箱; 用户注册日期 = 用户注册日期; 用户评论 = 用户评论; 用户活动 = 用户活动; }

public int UserID
{
    get;
    set;
}

public string UserName
{
    get;
    set;
}

public string UserFamilyName
{
    get;
    set;
}

public DateTime UserBirthDay
{
    get;
    set;
}

public string UserTelephone
{
    get;
    set;
}

public string UserEmail
{
    get;
    set;
}

public DateTime UserRegdate
{
    get;
    set;
}

public string UserComment
{
    get;
    set;
}

public bool UserActive
{
    get;
    set;
}

}

【问题讨论】:

  • 在该行设置断点并进入 getfullstudentprofile 方法。这会让你更好地了解失败的地方
  • 我做到了。如何逐步获取完整的学生档案?
  • 我截取了 IDE 的屏幕截图,但忘记了不能将屏幕截图放在 cmets 中。如果您没有修改您的快捷方式,它将是 F11。如果有,请单击 Debug -> Step Into

标签: asp.net c#-4.0


【解决方案1】:

究竟什么是空?我打赌GetFullStudentProfile 方法返回null。

【讨论】:

  • 您确定需要将选定索引指定为 GetFullStudentProfile 方法的参数吗?也许它应该是一些学生证。无论如何,在使用 UserEmail 属性之前,您需要检查 null 调用的结果。
【解决方案2】:

是的,这正是发生的事情。未找到与通过 ID 匹配的学生。我会在您的客户端代码中执行以下操作:

StudentProfile sp=ca.GetFullStudentProfile(ddlStudents.SelectedIndex);
lblEmail.Text = sp != null ? sp.UserEmail : string.Empty;

另外我会将GetFullStudentProfile 方法的阅读器操作改写成这样:

conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

if (reader.Read())
{
    sp = new StudentProfile((int)reader["UserID"], (string)reader["UserName"], (string)reader["UserFamilyName"], (DateTime)reader["UserBirthDay"], (string)reader["UserTelephone"], (string)reader["UserEmail"], (DateTime)reader["UserRegDate"], (string)reader["UserComment"], (bool)reader["UserActive"]);
}

reader.Close();

这只是日常的改头换面,看起来更好恕我直言

【讨论】:

  • @Dimitri Id 已找到。问题是 sp 没有被填充,结果返回 null。
  • @Nathan 调试器显示 userID 值的事实并不意味着数据库中有与该 ID 匹配的记录。试试这个:SELECT * FROM YourUsersTable WHERE ID=2。如果有记录,那么您在 StudentProfile 类的构造函数中做错了。
  • select * from dbo.Users where UserID=3 返回了我的记录。这个说法有效。
  • 您是否尝试过将 userID=3 传递给上述方法?如果是这样,它会返回任何东西吗?如果没有,请向我们展示 StudentProfile 类的定义及其构造函数和字段/属性
  • @Dimitri 你好,我试过了:StudentProfile student = ca.GetFullStudentProfile(3); if (student != null) { lblName.Text = student.UserName; lblEmail.Text = 学生.UserEmail; } else { lblName.Text = "空"; lblEmail.Text = "空"; }。结果为空。所以它说问题出在 StudentProfile 类中。我在我的问题中添加了类列表。请调查一下。
【解决方案3】:

还有:

HiddenID.Value = ddlStudents.SelectedValue;
lblName.Text = HiddenID.Value;

我注意到在您的 Autos 中将名称设置为 1。所以我认为您实际上是将其设置为:

lblName.Text = ddlStudents.SelectedValue;

我不认为将值设置为等于自身会以任何方式使您受益。检查您的数据库,UserEmail 的列是否允许为空?

另外,在您的数据库中,我相信 UserID 从 1 开始递增,对吗?我相信 SelectedIndex 从 0 开始。您可能需要将 selectedvalue 项增加 1。

我刚刚查看了您的另一个问题 (http://stackoverflow.com/questions/5745820/assign-list-member-to-label),我觉得这里有更多信息。

如果您的数据库不允许可空类型,我会更改:

CatalogAccess ca=new CatalogAccess();
lblEmail.Visible = true;
lblName.Visible = true;

lblTelephone.Visible = true;
HiddenID.Value = ddlStudents.SelectedValue;
lblName.Text = HiddenID.Value;
lblEmail.Text = ca.GetFullStudentProfile(ddlStudents.SelectedIndex).UserEmail;
lblFamilyName.Visible = true;
lblBirth.Visible = true;
ddlStudents.Items.Clear();
PopulateStudentsDDL();

到:

CatalogAccess ca=new CatalogAccess();
lblEmail.Visible = true;
lblName.Visible = true;

lblTelephone.Visible = true;

// if your table's ID increments starting at 0, otherwise ddlStudents.SelectedIndex + 1
StudentProfile student = GetFullStudentProfile(ddlStudents.SelectedIndex);

if (student != null)
{
    lblName.Text = student.UserName;
    lblEmail.Text = student.UserEmail;
    //rest of the labels going here (I only see Name and Email)
}

...

您还可以考虑将您的调用设置为在 sp != null 条件内显示标签,这样只有当一个有效的人显示时,它才会真正显示这些标签。否则就把它们放在前面。

否则我会像 Dimitri 那样说

lblName.Text = student.UserName != null ? student.UserName : String.Empty;
lblEmail.Text = student.UserEmail != null ? student.UserEmail : String.Empty;
// etc.

如果可以为空,则可以实际分配学生对象,但属性可能不会,这可能会导致您的应用程序在运行时出现问题。

【讨论】:

  • HiddenID.Value = ddlStudents.SelectedValue; lblName.Text = HiddenID.Value; //这里我刚刚检查了下拉列表是否有效。
  • 早上好!我做了一个测试。明确输入用户 ID:StudentProfile student = ca.GetFullStudentProfile(2); if (student != null) { lblName.Text = student.UserName; lblEmail.Text = 学生.UserEmail; //其余的标签在这里(我只看到名称和电子邮件)} else { lblName.Text =“它是空的”;并得到名称标签说“它是空的”。所以问题是该方法没有获取用户ID
  • 我认为问题出在 GetFullStudentProfile() 方法中。唉,我看不到。
  • 在这一行 lblEmail.Text = ca.GetFullStudentProfile(ddlStudents.SelectedIndex).UserEmail;右键单击 GetFullStudentProfile 并转到定义。在返回 sp 行上设置断点。在调试中运行它。当它到达返回 sp 线时,将鼠标悬停在 sp。如果它为空,则在获取学生资料对象时会出现问题,在这种情况下,我会在 GetFullStudentProfile 对象中设置一个断点,然后单步执行,直到(如果)它进入您的 catch (Exception ex) 块。如果它不为 null 并将其自身列为 Student Profile 对象,请单击工具提示中的 + 号...
  • 弹出窗口,查看您要检索的所有属性(电子邮件、姓名等)显示的内容。从那里你会知道你的采集功能是如何为你工作的。另外,我相信我在另一篇文章中看到您正在使用 SQL Server 2005 或 2008。ADO 是要求还是偏好?因为如果没有,您可能有兴趣阅读 LINQ。设置好dbml后,你的获取函数基本上就是创建一个db对象,创建一个sp对象设置为=(from c in db_object.GetFullStudentProfiles where c.UserId == userId select c).FirstOrDefault();跨度>
【解决方案4】:

好的。我做了一个新方法:

public UserDetails GetUser(int userID)
{
    SqlConnection conn = new SqlConnection(Config.DbConnectionString);
    SqlCommand cmd = new SqlCommand("GetFullUserProfile", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new SqlParameter("@UserID", SqlDbType.Int, 4));
    cmd.Parameters["@UserID"].Value = userID;
    try
    {
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
        // Check if the query returned a record.
        if (!reader.HasRows) return null;
        // Get the first row.
        reader.Read();
        UserDetails emp = new UserDetails((int)reader["UserID"], (string)reader["UserName"], (string)reader["UserFamilyName"], (DateTime)reader["UserBirthDate"], (string)reader["UserTelephone"], (string)reader["UserEmail"], (DateTime)reader["RegDate"], (string)reader["UserComment"], (int)reader["UserActive"]);
        reader.Close();
        return emp;
    }
    catch (SqlException err)
    {
        throw new ApplicationException("Data error.");
    }
    finally
    {
        conn.Close();
    }
}

新课程:

using System;

public class UserDetails
{
    public UserDetails(int userID, string userName, string userFamilyName, DateTime userBirthDate, string userTelephone, string userEmail, DateTime regDate, string userComment, int userActive)
    {
        UserID = userID;
        UserName = userName;
        UserFamilyName = userFamilyName;
        UserBirthDay = userBirthDate;
        UserTelephone = userTelephone;
        UserEmail = userEmail;
        RegDate = regDate;
        UserComment = userComment;
        userActive = UserActive;
    }

    public int UserID
    { get; set; }

    public string UserName
    { get; set; }

    public string UserFamilyName
    { get; set; }

    public DateTime UserBirthDay
    { get; set; }

    public string UserTelephone
    { get; set; }

    public string UserEmail
    { get; set; }

    public DateTime RegDate
    { get; set; }

    public string UserComment
    { get; set; }

    public int UserActive
    { get; set; }
}

之后在我的 WebUserControl 后台代码中:

UserDetails ud = ca.GetUser(24);
    //HiddenID.Value = String.Format(ud.UserID);
    lblName.Text = ud.UserName;
    lblEmail.Text = ud.UserEmail;
    lblFamilyName.Text = ud.UserFamilyName;
    lblBirth.Text=String.Format("{0:dd/MM/yyy}",ud.UserBirthDay);
    lblTelephone.Text = ud.UserTelephone;

并且让方法奏效了。所以,这个阶段已经准备好了。感谢所有帮助过我的人。线程已关闭。

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2015-06-23
    • 2019-09-07
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多