我正在尝试从下拉列表值更改中的数据库表中获取值并将其显示在文本框中。从下拉列表中选择任何值时,页面会刷新,但文本框中没有显示任何值,以下是代码:
Default.aspx的
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
Default.aspx.cs
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string ddl2value = DropDownList1.SelectedValue.ToString();
// fillDropdown3(ddl3, ddl2value);
SqlConnection objConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand objCmd2;
SqlDataReader objRdr2;
// String strCmd2;
objConn2.Open();
objCmd2 = new SqlCommand("SELECT code, rank, address FROM agen_mast WHERE name = " +
"'" + ddl2value.ToString() + "'", objConn2);
objRdr2 = objCmd2.ExecuteReader();
while (objRdr2.Read())
{
TextBox9.Text = (string)objRdr2["code"].ToString();
TextBox8.Text = (string)objRdr2["address"].ToString().ToUpper();
TextBox10.Text = (string)objRdr2["rank"].ToString().ToUpper();
}
objRdr2.Close();
objConn2.Close();
// Response.Write(ddl2value.ToString());
}
答案 0 :(得分:0)
您可以尝试这样的事情:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(DropDownList1.SelectedValue !="-1"){
string ddl2value = DropDownList1.SelectedValue.ToString();
SqlConnection objConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand objCmd2;
SqlDataReader objRdr2;
objConn2.Open();
objCmd2 = new SqlCommand("SELECT code, rank, address FROM agen_mast WHERE name = " +
"'" + ddl2value + "'", objConn2);
objRdr2 = objCmd2.ExecuteReader();
while (objRdr2.Read())
{
TextBox9.Text = (string)objRdr2["code"].ToString();
TextBox8.Text = (string)objRdr2["address"].ToString().ToUpper();
TextBox10.Text = (string)objRdr2["rank"].ToString().ToUpper();
}
objRdr2.Close();
objConn2.Close();
}
}
并添加一个假ListItem
Value
-1
作为DropDownList1
中.aspx
的第一项。顺便说一句,确保您将正确的参数发送到SqlCommand
。现在,您正在寻找Name
= 0
的记录。此外,ddl2Value
已经是string
类型,因此您无需在ToString()
内调用SqlCommand