2016-09-05 11 views
1

私は2つのボタンを持つリストボックスを持っています。リストボックスにファイルを追加する最初のボタン。 2番目のボタンはリストボックスから削除します。リストボックスからデータベースにデータを挿入するには?

リストボックスからSQL Serverデータベースにファイルを挿入するために使用する3番目のボタンがあります。

たとえば、リストボックスに2つのファイルを追加した場合、挿入ボタンをクリックしてデータベースに保存します。

貧しい私の英語のために申し訳ありません。私は誰かが私が

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

+0

これまでのあなたの研究は何ですか?あなたのデータベースは何ですか?あなたのテーブルはどのように見えるのですか?どのようにデータベースに接続しますか?あなたは私たちに他に誰も助けることができるものを教えてください – GuidoG

+0

ありがとう@GuidoG 私はSQL Serverを使用しています。私はデータベースDB.mdfを持っています 3つの列を含むテーブルファイルにファイルを保存します: number_file(AUTO_INCREMENT) name_file path_file –

+0

は、私は、単純なADO.Net検索はこの TIPを解決するのに十分だろうと思う:BèlguesmiSé[email protected]使用CommandBuilder –

答えて

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(); 
     } 
    } 
} 
関連する問題