asp.net C# - 无法从 sql 数据库中填充(预选择)下拉列表"选定值"



我刚刚开始学习编程。我遇到了一个我无法弄清楚的错误。我的代码隐藏如下。 我收到错误 CS1001(预期标识符(。我需要提取搜索记录的值并在下拉列表中预先选择它:

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();
}
}    

}

您需要删除 .在两条生产线中 待成为 SDR["Preg_TestToday"]。 另外,您不能直接与DataReader绑定,您需要执行以下操作:

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

您需要转换为数据表以使用索引器读取数据或先使用

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

相关内容

  • 没有找到相关文章

最新更新