0

我已经在用例上苦苦挣扎了两天了。我只需要从患者就诊表中读取患者的就诊编号,并根据患者编号填充下拉列表。经过大量研究,这两个链接几乎解决了相同的问题。我做了此处描述了 stackover 站点上的示例,但我的仍然无法正常工作并且没有显示错误。此处描述了另一个示例!这是我的代码:HTML

  <li>
            <asp:Label runat="server" ID ="lblVisits">Visit Number</asp:Label>
            <asp:DropDownList ID="DropDownList2" runat="server" Height="16px" Width="174px" style="margin-left: 46px">
                <asp:ListItem Text=""></asp:ListItem>
                <asp:ListItem Value=""></asp:ListItem>
            </asp:DropDownList>
  </li>    

代码隐藏:

protected void btn_search_Click(object sender, EventArgs e)
    {
        string connect = System.Configuration.ConfigurationManager.ConnectionStrings["db_connection"].ToString();
        string num = txtPatientNumber.ToString();
        SqlConnection con = new SqlConnection(connect);
        string Statement = "SELECT Visit_Number FROM Visit "
          + "WHERE Patient_Number=@Patient_Number";
        SqlCommand cmd = new SqlCommand(Statement, con);
        cmd.Parameters.AddWithValue("@Patient_Number", num);

        SqlDataReader reader;

        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                DropDownList2.DataSource = reader;
                DropDownList2.DataTextField = reader["Visit_Number"].ToString();
                DropDownList2.DataValueField = reader["Visit_Number"].ToString();
                DropDownList2.DataBind();
            }
            reader.Close();
        }
        catch (SqlException excep)
        {
            //Response.Write("<script language=javascript>alert('Patient Number not Found.');</script>");
            ErrorMessage.Text = "Error Occurred" + excep.Message.ToString();
        }
        finally
        {
            con.Close();
        }

    }
4

1 回答 1

1

问题出在这里:

while (reader.Read())
{
   DropDownList2.DataSource = reader;
   DropDownList2.DataTextField = reader["Visit_Number"].ToString();
   DropDownList2.DataValueField = reader["Visit_Number"].ToString();
   DropDownList2.DataBind();
}

你用错了.DataTextField.DataValueField它应该是这样的:

DropDownList2.DataTextField = "Visit_Number";
DropDownList2.DataValueField ="Visit_Number";

此外,您不应为从 db 返回的每一行重新绑定 DropDownList。所以删除while (reader.Read()).

最终代码:

DropDownList2.DataSource = reader;
DropDownList2.DataTextField = "Visit_Number";
DropDownList2.DataValueField = "Visit_Number";
DropDownList2.DataBind();
于 2013-02-05T13:27:25.483 回答