如何从sql中创建一个下拉列表,以显示在asp.net c#的列表框中



这是我的代码,我是C#的新手,正在努力学习,基本上我有一个项目,使用fullcalendar安排专家的专业,但当我创建专业的下拉列表,然后为所选每个专业的专家制作列表框时,它一直说cmd上有错误。ExecuteScalar((;我做错了什么?

{
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
String CS = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT id, name, active, modifiedDate, note FROM sldb.dbo.Services", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.DropDownList1.SelectedItem.Value != "0")
{
String CS = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using(SqlCommand cmd = new SqlCommand("select firstName from sldb.dbo.Specilist where serviceID= @serviceID", con))
{
using(SqlDataAdapter da = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("@serviceID", this.DropDownList1.SelectedItem.Value);
con.Open();
object firstName = cmd.ExecuteScalar();
con.Close();
this.ListBox1.Text = firstName.ToString();
}
}
}
}
else
{
this.ListBox1.Text = "Please select name from list";
}
}```

如果错误在ExecuteScalar上,则表明您的查询有问题。我注意到Specialist在select语句中拼写错误。试着纠正一下,如果有帮助的话,请告诉我。

请注意,executeScalar返回数据集中第一行的第一列。试着将刽子手包裹在一个尝试捕获中

try
{
object firstName = cmd.ExecuteScalar();
}
catch(Exception error)
{
//display error message error.Message;
}

在代码中,我很想把值放在一个字符串中,看看Scalar返回了什么。

string strPeek = cmd.ExecuteScalar().ToString();

另外,单独运行SQL以确保查询没有错误。

最新更新