I have been struggling with the usecase for two days now.All i need was to read Patient’S VisitNumber from the patient visit table and populate the dropdownlist given the Patient Number.After some much research these two links address almost the same issue.I did as described here sample on stackover site but still mine is not working and no error is displayed. Another sample is described here!
Here is my codes: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>
CodeBehind:
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();
}
}
Problem lies here:
Your are using
.DataTextFieldand.DataValueFieldwrong. This is how it should look like:Also you should not rebind DropDownList for every row returned from db. So remove
while (reader.Read()).Final code: