从下拉菜单中选择一个选项以填充文本框

时间:2014-11-18 23:47:54

标签: c# asp.net sql-server

我在下拉菜单中填写了我的UserData数据库中的名字。我目前正在尝试选择用户名以使其用户详细信息显示在文本框中,但是当我尝试从下拉菜单中选择一个选项时,第一个选项始终显示在文本框中,我想知道是否有人可以看到问题我的代码?

protected void BtnSelect_Click(object sender, EventArgs e)
{
    SqlDataReader reader;
    String connString = ConfigurationManager
        .ConnectionStrings["RegistrationConnectionString"].ConnectionString;

    SqlConnection conn = new SqlConnection(connString);
    SqlCommand comm1 = new SqlCommand(
        "SELECT FirstName, LastName, Email FROM UserData " + 
        "WHERE TeacherID = @TeacherID", conn);

    comm1.Parameters.Add("@TeacherID", System.Data.SqlDbType.Int);
    comm1.Parameters["@TeacherID"].Value = DropDownList1.SelectedItem.Value;

    try
    {
        conn.Open();

        reader = comm1.ExecuteReader();

        if (reader.Read())
        {
            txtFirstName.Text = reader["FirstName"].ToString();
            txtLastName.Text = reader["LastName"].ToString();
            txtEmail.Text = reader["Email"].ToString();
        }

        reader.Close();         
    }
    catch (Exception ex)
    {
        dbErrorLabel.Text = ("Error in retrieval"+ ex.StackTrace);
    }
    finally
    {
        conn.Close();
    }
}

1 个答案:

答案 0 :(得分:0)

尝试稍微改变您的代码,然后您会发现它更容易调试。检查您为所选值获得的值(它是您所期望的)以及您获得的实际例外内容。

这可以帮助你弄清楚正在发生的事情。

protected void BtnSelect_Click(object sender, EventArgs e)
{
    SqlDataReader reader;
    String connString = ConfigurationManager
        .ConnectionStrings["RegistrationConnectionString"].ConnectionString;

    SqlConnection conn = new SqlConnection(connString);
    SqlCommand comm1 = new SqlCommand(
        "SELECT FirstName, LastName, Email FROM UserData " + 
        "WHERE TeacherID = @TeacherID", conn);

    var selectedValue = DropDownList1.SelectedItem.Value;
    var selected = int.Parse(selectedValue);                

    comm1.Parameters.Add("@TeacherID", System.Data.SqlDbType.Int);
    comm1.Parameters["@TeacherID"].Value = selected;

    try
    {
        conn.Open();

        reader = comm1.ExecuteReader();

        if (reader.Read())
        {
            txtFirstName.Text = reader["FirstName"].ToString();
            txtLastName.Text = reader["LastName"].ToString();
            txtEmail.Text = reader["Email"].ToString();
        }

        reader.Close();         
    }
    catch(Exception ex)
    {
        dbErrorLabel.Text = ("Error in retrieval " + ex.StackTrace );
    }
    finally
    {
        conn.Close();
    }
}