8
Reply

List Box Option Selection

Katie B

Katie B

Apr 15 2013 3:51 PM
1k
Sorry I know the subject isnt great, but it hard to get this question basis in a subject box. :D 

I have a list box called degree programme, once a selection is made in this listbox, I want the modules associated with selection to appear in my modules listbox. I'm doing this through an access database. I'll post the code below which i've pieced together from things ive read, but I dont know how right/wrong it is. 

private void lstboxDegreeProgramme_SelectedIndexChanged(object sender, EventArgs e)
        {
            String strItem;
            foreach (Object selecteditem in lstboxDegreeProgramme.SelectedItems)
            {
                strItem = Convert.ToString(lstboxDegreeProgramme.SelectedItem);

                string connectionString =
                   "provider=Microsoft.ACE.Oledb.12.0;" +
                   "data source=C:\\Users\Documents\\StudentRegistrationDatabase.accdb";

                OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
                OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
                myOleDbConnection.Open();
                myOleDbCommand.CommandText = "SELECT * FROM Modules WHERE CourseID = '" + strItem + "''";
                OleDbDataReader myOleDbDataReader = myOleDbCommand.ExecuteReader();

                while (myOleDbDataReader.Read())
                {
                    lstboxModules.Items.Add(myOleDbDataReader["ModuleID"].ToString() + myOleDbDataReader["ModuleName"].ToString());

                    myOleDbDataReader.Read();
                    
                }
I keep getting an error on the highlighted line saying Syntax error in string in query expression 'CourseID. But when i've put breaks in it runs up until that and i've been re-writing the code for the best part of today. Any help (as normal) is appreciated :D 

Answers (8)