将值与下拉列表绑定时出错

本文关键字:定时 出错 绑定 下拉列表 | 更新日期: 2023-09-27 18:08:22

创建了一个下拉列表。我的数据库表包含2个表

Studentregtable :  ID int,FullName varchar,UserName varchar,department varchar.
facultyregtable1 : ID int,FacultyName varchar,DeptName varchar.

我的aspx代码:

<asp:DropDownList ID="DropDownList1" runat="server" Height="20px" Width="147px">
            </asp:DropDownList>

我的c#代码:

public partial class studentfeedbackarea : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Database1ConnectionString1"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            con.Open();
           SqlCommand cmd = new SqlCommand("select FacultyName from facultyregtable1 where DeptName=(select department from Studentregtable where UserName=' " + Session["new"].ToString() + " ')", con);
           SqlDataAdapter da = new SqlDataAdapter(cmd);
           DataTable dt = new DataTable();
           da.Fill(dt);
           con.Close();
           DropDownList1.DataSource = dt;
           DropDownList1.DataTextField = "FacultyName";
           DropDownList1.DataValueField = "FacultyName";
           DropDownList1.DataBind();
        }
    }

下拉列表中未显示任何值。为什么?我的代码有错误吗?

将值与下拉列表绑定时出错

我在代码上没有发现任何问题。。但在查询中发现一些问题。。

确认您的子查询只返回一个值。。。

如果返回多个值,则在查询中将DeptName =(更改为DeptName in(

此外,我注意到这里有一个空格->' " + Session["new"].ToString() + " '将该空格删除到'" + Session["new"].ToString() + "'

更正的查询:

select FacultyName from facultyregtable1 where DeptName in(select department from
Studentregtable where UserName='" + Session["new"].ToString() + "')"

也许它会帮助你。。。

在aspx页面中尝试此操作。。。。。。。。。。。。。。

<asp:DropDownList ID="DropDownList1" runat="server" datatextfield="FacultyName" datavaluefield="FacultyName" Height="20px" Width="147px">
            </asp:DropDownList>
select FacultyName from facultyregtable1 where DeptName=(select department from Studentregtable where UserName=' " + Session["new"].ToString() + " '

在上面的查询中,我认为您在DeptName='//应该是返回一个值的子查询的位置附近缺少引号'