簡體   English   中英

如何將列表框中的數據插入數據庫?

[英]How to insert data from listbox into database?

我有一個帶有兩個按鈕的列表框。 將文件添加到列表框中的第一個按鈕。 第二個按鈕可將其從列表框中刪除。

我要使用第三個按鈕將文件從列表框中插入到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
 }

在此處輸入圖片說明

尚未測試,但這應該可以助您一臂之力:假設列表框為每個文件提供了完整的路徑名。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM