Click here to Skip to main content
15,885,872 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I'm making a Windows form which allows people to select a film from different genres. I've used list boxes to display the list of films and genres. When a user selects a genre, the films from that genre are displayed in another list box.

The user selects a film from that list box, then a picture from the film is displayed in a picture box and informtion for the film is displayed in a text box. I have also added a button which the user clicks, once they have selected the film, a message box is displayed with buttons, that asks if they're sure they want to choose this film.

If the user clicks "Yes", the picture and info for the film are still displayed on screen as before. If user clicks "No", then the picture and info are cleared from the screen and the user can select another film.

Now what I want to do is to store the film choice that the user has made into a database. So I can keep a record of the films chosen by the user. The problem is that I don't know how to send data into a database based on a selection from a listbox.

EDIT: This is the code i'm using to send the data, but it isnt working, anyone have any ideas why it isnt working?

private void btnSave_Click(object sender, EventArgs e)
        {


try
            {
                // set up data connection
                string cs = "Data Source=MASTER\\MASTER;Initial Catalog=FilmDB;Integrated Security=True;Pooling=False";
                SqlConnection cn = new SqlConnection(cs);
                // Set up adapter manager
                SqlDataAdapter da = new SqlDataAdapter();
                //Set dataset for results
                DataSet ds = new DataSet();
                ds.Clear();
                //Open Connection to database
                cn.Open();
                //Ask adapter to transfer data from table to dataset
                da.Fill(ds, "Films");
                //Set up data table
                DataTable dt = ds.Tables["Films"];
                // INSERT listbox selection into database

                using (SqlConnection con = new SqlConnection(cs)) 
                
              
              using (SqlCommand com = new SqlCommand("INSERT INTO Films (FilmName) VALUES (@FilmName)", con)) 
              
              {
                com.Parameters.AddWithValue("@FilmName", lbxFilms);
                
                com.ExecuteNonQuery();
                //Close connection to database
                cn.Close();
              }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
            finally
            {
                //cn.close();
            }
        
        }
    }
}
Posted
Updated 10-Mar-11 1:51am
v4

If you can read the info from the listbox - which your question implies, then it is pretty easy, assuming you have set up the database already. I assume you are using SQL Server?
using (SqlConnection con = new SqlConnection(strConnect))
   {
   using (SqlCommand com = new SqlCommand("INSERT INTO MyTable (MyColumn1, MyColumn2) VALUES (@VAL1, @VAL2)", con))
      {
      com.Paramaters.AddWithValue("@VAL1", valueFromListBox1);
      com.Paramaters.AddWithValue("@VAL2", valueFromListBox2);
      com.ExecuteNonQuery();
      }
   }
You can get the connection string in the Server Explorer of VS, highlight the database and look at the properties pane.


"It isnt working I created a seperate button and put the code in that sets up the database and the code you gave me but it still isnt working. I've put the code in the question so you can check if its right or not."

The code you have provided does two things: The first section reads from the database and the second writes to it.
Once the first section has read from the database, the information is thrown away, because it all goes out of scope.

The second should work, assuming that "lbxFilms" is a string or similar.

When you say "It doesn't work" what does happen? What happens that shouldn't, or doesn't happen that should? Do you get an error? If so, what?

"The program runs, but when I press the button it doesnt save that data into the database. lbx films is the name of the listbox."

Then I am not surprised: if "lbxFilms" is a whole list box, how do you expect that to be saved to a database?
Get the current user selection, and insert that instead...
 
Share this answer
 
v3
Comments
programmer1234 10-Mar-11 7:49am    
It isnt working I created a seperate button and put the code in that sets up the database and the code you gave me but it still isnt working. I've put the code in the question so you can check if its right or not.
OriginalGriff 10-Mar-11 8:23am    
Answer updated.
programmer1234 10-Mar-11 8:28am    
The program runs, but when I press the button it doesnt save that data into the database. lbx films is the name of the listbox.
programmer1234 10-Mar-11 8:40am    
I changed it to com.Parameters.AddWithValue("@FilmName", lbxFilms.SelectedItem); but it still wont save the data.
OriginalGriff 10-Mar-11 8:49am    
Hang on a moment: Are you trying to write the film name back to the same database table you got it out of originally?
For starters, don't try to mix up your logic. Separate what you want to do in your UI from what you want to do in your application logic. What I mean is that you should treat your "Yes" or "No" click logic and what happens on the form separately from the logic that you use to write information to the db. This will make your struggles to get this done much easier.
In the button click handler for "Yes", you just need to handle writing the listbox.SelectedItem information to your database. To write to a database, in case you haven't gotten that far, you can use this code project article to see how this is done in a relevant way. Just don't clear the user selections after all this is done and the user selection will remain intact on the form.
If the user clicks no, you just have to reset the form and clear user selections.
 
Share this answer
 
Comments
Manfred Rudolf Bihy 10-Mar-11 8:11am    
Good advice! 5+
Espen Harlinn 11-Mar-11 13:58pm    
I agree, my 5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900