使用列表框将数据添加到数据库 [英] Add data to a database using a listbox

查看:136
本文介绍了使用列表框将数据添加到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作Windows窗体,该窗体允许人们从不同类型的电影中选择电影.我使用列表框来显示电影和流派的列表.当用户选择一种流派时,该流派的电影将显示在另一个列表框中.

用户从该列表框中选择影片,然后将影片中的图片显示在图片框中,并将有关该影片的信息显示在文本框中.我还添加了一个按钮,用户单击该按钮后,一旦他们选择了电影,就会显示一个带有按钮的消息框,询问他们是否确定要选择这部电影.

如果用户单击是",则电影的图片和信息仍将像以前一样显示在屏幕上.如果用户单击否",则会从屏幕上清除图片和信息,并且用户可以选择另一部电影.

现在,我要做的是将用户选择的电影选择存储到数据库中.因此,我可以记录用户选择的电影.问题是我不知道如何基于列表框中的选择将数据发送到数据库中.

这是我用来发送数据的代码,但是它不起作用,任何人都知道为什么它不起作用?

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.

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();
            }
        
        }
    }
}

推荐答案

如果您可以从列表框中读取信息(您的问题暗示),那么假设您已经建立了数据库,这将非常容易.我假设您正在使用SQL Server?
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();
      }
   }

您可以在VS的服务器资源管理器中获取连接字符串,突出显示数据库并查看属性窗格.


这不起作用,我创建了一个单独的按钮,然后将代码放入其中,以设置数据库和您提供给我的代码,但仍然无法正常工作.我已将代码放入问题中,因此您可以检查其是否正确与否."

您提供的代码有两件事:第一部分从数据库中读取数据,第二部分向数据库中写入数据.
一旦第一部分从数据库中读取,该信息就会被丢弃,因为所有信息都超出了范围.

假设"lbxFilms"是字符串或类似字符,则第二个命令应该可以工作.

当您说它不起作用"时,会发生什么?不应发生或不应该发生的情况是什么?收到错误消息吗?如果是这样,怎么办?

程序正在运行,但是当我按下按钮时,它不会将数据保存到数据库中.lbx电影是列表框的名称."

然后,我并不感到惊讶:如果"lbxFilms"是一个完整的列表框,那么您希望如何将其保存到数据库中?
获取当前的用户选择,然后插入...

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...


对于初学者,请不要混淆您的逻辑.将您要在UI中执行的操作与您要在应用程序逻辑中执行的操作分开.我的意思是,您应该将是"或否"单击逻辑以及表单上发生的事情与用于将信息写入db的逻辑分开对待.这将使您为完成此任务而付出的努力变得更加容易.
在是"的按钮单击处理程序中,您只需要处理将listbox.SelectedItem信息写入数据库.要写数据库,以防万一,请使用代码项目文章,以了解如何以相关方式完成此操作.完成所有这些操作后,只需不清除用户选择,用户选择将在表单上保持不变.
如果用户单击否",则只需重置表单并清除用户选择.
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.


这篇关于使用列表框将数据添加到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆