我的代码中的错误或我做得不对

时间:2013-02-05 13:17:44

标签: asp.net webforms

我一直在努力使用该药箱两天了。我需要的是从患者就诊表中阅读患者的访问号码并填写患者编号的下拉列表。经过一些研究后,这两个链接解决了几乎相同的问题。我按照此处的描述进行了sample on stackover site,但仍然没有工作,也没有显示错误。 Another sample is described here! 这是我的代码: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();
        }

    }

1 个答案:

答案 0 :(得分: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();