Creating a Dynamic Checkbox List (Cont.)


Below shows the C# code of the file WebForm1.aspx.cs:
Line 31: protected void courseList_SelectedIndexChanged(
It executes when the event onselectedindexchanged occurs. The event is inherited from the ListControl class and occurs when the selection from the list control changes between posts to the server.

Line 34: for ( int i = 0; i < courseList.Items.Count; i++ )


Line 35: if ( courseList.Items[i].Selected )
Gets or sets a value indicating whether the item is selected.

Line 36: Result.Text += " " + courseList.Items[i].Value;
Gets or sets the text displayed in a list control for the item represented by the ListItem.
WebForm1.aspx.cs
using System;
using System.Data.OleDb;
namespace WebApplication3 {
  public partial class WebForm1 : System.Web.UI.Page {

    protected void Add_Click( object sender, EventArgs e ) {
      OleDbConnection conn = new OleDbConnection(
          @"Provider=Microsoft.ACE.OleDb.12.0;Data Source=" +
          Server.MapPath( "Access\\enrollment.mdb" ) );
      String sql = "INSERT INTO courses( title ) VALUES ( @title )";
      OleDbCommand cmd = new OleDbCommand( sql, conn );
      cmd.Parameters.AddWithValue( "@title", title.Text );
      conn.Open( );
      cmd.ExecuteNonQuery( );
      cmd.Dispose( );
      conn.Close( );
      Response.Redirect( "WebForm1.aspx" );
    }
    protected void Reset_Click( object sender, EventArgs e ) {
      OleDbConnection conn = new OleDbConnection(
          @"Provider=Microsoft.ACE.OleDb.12.0;Data Source=" +
          Server.MapPath( "Access\\enrollment.mdb" ) );
      String sql = "DELETE FROM courses";
      OleDbCommand cmd = new OleDbCommand( sql, conn );
      conn.Open( );
      cmd.ExecuteNonQuery( );
      cmd.Dispose( );
      conn.Close( );
      Response.Redirect( "WebForm1.aspx" );
    }
    protected void courseList_SelectedIndexChanged(
        object sender, EventArgs e ) {
      Result.Text = studentName.Text + " selected the course(s): ";
      for ( int i = 0; i < courseList.Items.Count; i++ )
        if ( courseList.Items[i].Selected )
          Result.Text += " " + courseList.Items[i].Value;
    }
  }
}