如何将数据从列表框插入数据库?

时间:2016-09-05 11:14:15

标签: c# sql-server winforms listbox

我有一个带有两个按钮的列表框。将文件添加到列表框的第一个按钮。第二个按钮,用于从列表框中删除它。

我想用第三个按钮将文件从列表框插入SQL Server数据库。

例如,如果我在列表框中添加了两个文件,我想在点击插入按钮后将它们保存在我的数据库中。

抱歉我的英语不好;我希望有人可以帮助我

// this button for adding files to listbox
private void add_Click(object sender, EventArgs e)
{
        OpenFileDialog parcourir = new OpenFileDialog();
        parcourir.Filter = "XML Files (.xml)|*.xml|All Files (*.*)|*.*";

        if (parcourir.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            listBox1.Items.Add(parcourir.SafeFileName);
        }
}

//this button for deleting selected file in listbox
private void delete_Click(object sender, EventArgs e)
{
        if (listBox1.Items.Count > 0)
        {
            if (listBox1.SelectedIndex < 0)
            {
                MessageBox.Show("select a file first", "error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            }
        }
        else
        {  
            MessageBox.Show("listbox empty", "error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
        }
 }

 private void insert_Click(object sender, EventArgs e)
 {
    //save files from listbox to sql database
 }

enter image description here

1 个答案:

答案 0 :(得分:2)

没有经过测试,但是这应该可以帮到你: 这假设列表框具有每个文件的完整路径+名称。

using(SqlConnection connection = new SqlConnection(yourconnectionstring))
{
    connection.Open();
    foreach (string item in yourListBox.Items)
    {
        string fileName = System.IO.Path.GetFileName(item);
        string filePath = System.IO.Path.GetDirectoryName(item); 

        using (SqlCommand cmd = new SqlCommand("INSERT INTO FILE (name_file, path_file) VALUES (@fileName, @filePath)", connection))
        {
             cmd.Parameters.AddWithValue("@fileName", fileName);
             cmd.Parameters.AddWithValue("@filePath", filePath);
             cmd.ExecuteNonQuery();
        }
    }
}
相关问题