asp.net DropDownList在ASPNET 4.5中不起作用

时间:2013-12-19 04:35:06

标签: c# asp.net forms class web

的DropDownList:

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

        string sqlCoursesList = "SELECT sno,subject_lbl FROM courses WHERE sub_status = 1";

        this.course_sno.DataSource = gm.dataTable(sqlCoursesList);
        this.course_sno.DataTextField = "subject_lbl";
        this.course_sno.DataValueField = "sno";
        this.course_sno.DataBind();
    }
    catch (Exception exc) {
        gm.catchError(exc);
    }

}
我的班级

中的

方法

public DataTable dataTable(string sql) {
    try {
        connect();
        dt = new DataTable();
        oda = new MySqlDataAdapter(sql, con);
        oda.Fill(dt);
    }
    catch (Exception exc) {
        catchError(exc);
    }
    finally {
        try {
            closeCon();
        }
        catch (Exception excf) {
            catchError(excf);
        }
    }
    return dt;
}

按下按钮上的代码:

protected void btnSearch_Click(object sender, EventArgs e)
{
    try
    {
        string year = this.adm_year.Text;
        string course_sno = this.course_sno.SelectedIndex.ToString();
        //this.searchTxt.Text = "Year: "+year+" Course Sno : "+course_sno;
        if (year.Equals("") || course_sno.Equals(""))
        {
            this.searchTxt.Text = gm.errorMsg("Error", "Session year and Course Must be selected in the fields", "../../images/error.png");
        }
        else
        {
            string sqlList = "SELECT sno,std_sno,opt_sno,course_sno,chosen_faculty,date_application,is_active " +
                             "FROM apply_for_course " +
                             "WHERE course_sno = '" + course_sno + "' AND " +
                             "YEAR(date_application) = '" + year + "'";
            if (gm.search(sqlList))
            {
                mdr = gm.getRecordSet(sqlList).ExecuteReader();
                if (mdr.HasRows)

                  }
........

}

现在,问题在于,当我更改下拉选项并按下提交按钮时,它只获得第一个索引:

 string course_sno = this.course_sno.SelectedIndex.ToString();

我做错了什么?

2 个答案:

答案 0 :(得分:8)

您正在绑定/重新绑定每个页面加载的下拉列表,这会将下拉列表的选定索引重置为列表中的第一个项目。只在第一次绑定下​​拉列表,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        try
        {
            string sqlCoursesList = "SELECT sno,subject_lbl FROM courses WHERE sub_status = 1";

            this.course_sno.DataSource = gm.dataTable(sqlCoursesList);
            this.course_sno.DataTextField = "subject_lbl";
            this.course_sno.DataValueField = "sno";
            this.course_sno.DataBind();
        }
        catch (Exception exc) {
            gm.catchError(exc);
        }
    }
}

答案 1 :(得分:1)

不要在页面加载时绑定Dropdown。在代码中绑定一次