我是.net的新手。我有以下代码,我知道它是不正确的:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection conn = new SqlConnection("Connection");
SqlCommand cmd = new SqlCommand("SELECT * FROM Users ORDER BY FirstName", conn);
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
ddlUsers.DataValueField = "ID";
ddlUsers.DataTextField = "FirstName";
ddlUsers.DataSource = rd;
ddlUsers.DataBind();
rd.Close();
SqlCommand cmd1 = new SqlCommand("SELECT [LastName], [Email], [Phone] FROM [Users] WHERE ([FirstName] = @FirstName)", conn);
cmd1.Parameters.AddWithValue("@FirstName", ddlUsers.SelectedItem.ToString());
SqlDataReader rd1 = cmd1.ExecuteReader();
while (rd1.Read())
{
lblPhoneShow.Text = rd1["Phone"].ToString();
lblEmailShow.Text = rd1["Email"].ToString();
lblLNShow.Text = rd1["LastName"].ToString();
}
conn.Close();
}
}
将数据绑定到下拉列表效果很好,但是当我选择某个名称时,标签不会显示任何内容。谁能解释一下我做错了什么? 谢谢!
答案 0 :(得分:1)
您似乎没有执行查询。
试试这个:
SqlCommand cmd1 = new SqlCommand("Select (Phone, LastName, Email) from users where FirstName = @FirstName", conn);
cmd.Parameters.AddWithValue("@FirstName", ddlUsers.SelectedValue.ToString());
rd = cmd.ExecuteReader()
<强>更新强>
下拉列表的值是ID。您正在将数据库中的FirstName与此值进行比较。名字永远不会与ID匹配。