locked
listbox does not show the data RRS feed

  • Question

  • User34732094 posted

       public DataTable getCourses()
            {
                string CS = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(CS))
                {

                    SqlCommand cmd = new SqlCommand("select * from course", con);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    return dt;
                }
            }

    public void ListBoxData()
            {
              
                ListBox1.DataSource = getCourses();
                ListBox1.DataTextField = "id";
                ListBox1.DataValueField = "label";

                  }

    On page_load i am trying to call this method but listbox doesn't display any data.

    Monday, May 31, 2021 7:12 PM

Answers

  • User-1330468790 posted

    Hi entrylevel,

     

    The reason why you cannot make the list box work is that you should call another method - "DataBind()" after set "DataSource".

    Change the codes as below:

    public void ListBoxData()
    {
        ListBox1.DataSource = getCourses();
        ListBox1.DataTextField = "id";
        ListBox1.DataValueField = "label";
        ListBox1.DataBind();
    }

     

    You can refer to the example codes on documentation.

    ListBox Class: Examples

     

    Hope helps.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 1, 2021 1:58 AM