Search code examples
c#asp.netdrop-down-menuselectedvalue

asp.net C# - unable to get populate (preselect) the dropdownlist SelectedValue from sql database


I am just beginning to learn programming. I'm running into an error that I cannot figure out. My code-behind is below. I am receiving Error CS1001 (Identifier expected). I need to pull the value for the searched record and pre-select it on the dropdownlist:

protected void DetailsView1_DataBound(object sender, EventArgs e)
{
    DataTable dvt = new DataTable();
    using (SqlConnection sqlconn = new SqlConnection(mainconn))
    {

        sqlconn.Open();
        SqlCommand sqlcomm = new SqlCommand();
        string sqlquery = "SELECT distinct [EncounterID], pd.[MRN], [VisitDate], FirstName, LastName, DOB, Gender,[BMI_Category], [Asthma_IDDate], [Tobacco_Counsel], [EC_ImmediateType], [BCM_ImplantDisp], [BCM_CondomDisp], [BCM_IUDDisp], [BCM_DepoDisp], [BCM_NuvaRingDisp], [BCM_PatchDisp], [Preg_TestToday], [Preg_TestResults], [EC_AdvanceType], [EC_Immediate], [EC_Advance], [BCM_FemaleCondomDisp], [BCM_LatexDamDisp], [NoBCM_PartnerMethod], [NoBCM_SeekingPreg], [NoBCM_Abst], [NoBCM_Preg], [NoBCM_SameSex], [NoBCM_Undecided], [NoBCM_Refused], [NoBCM_LarcAppt], [NoBCM_Other], [NoBCM_OtherReason], [NoBCM_AlreadyUsing], [BCMAlready_Patch], [BCMAlready_Depo], [BCMAlready_Condom], [BCMAlready_Implant], [BCMAlready_IUD], [BCMAlready_FemaleCondom], [BCMAlready_ECOnly] FROM [OSCRMedicalData] md INNER JOIN OSCRPersonData pd on md.MRN=pd.MRN WHERE ([EncounterID] = @EncounterID)";
        sqlcomm.CommandText = sqlquery;
        sqlcomm.Connection = sqlconn;
        sqlcomm.Parameters.AddWithValue("@EncounterId", Txtsearch.Text);
        SqlDataReader sdr = sqlcomm.ExecuteReader();



        DropDownList ddl = (DropDownList)DetailsView1.FindControl("Preg_TestToday");
        if (ddl != null)
        {
            ddl.DataSource = sdr;
            ddl.SelectedValue = sdr.["Preg_TestToday"].ToString();
            ddl.DataBind();

           ddl.SelectedValue = sdr.["Preg_TestToday"].ToString();

        }

    }    



}

Solution

  • You need to remove the . In both lines To be sdr["Preg_TestToday"]. Plus you cant directly bind with DataReader you need to do as below :

    DataTable dt = new DataTable();
    dt.Load(sdr);
    

    You need to convert to datatable to read the data using indexers or use first

    If(sdr.Read())
    {
        var selectedValue = sdr["YourColumnName"];
    }