2016-09-05 101 views
1

我有一个带有两个按钮的列表框。第一个将文件添加到列表框的按钮。第二个按钮将其从列表框中删除。如何将数据从列表框插入数据库?

还有第三个按钮我想用它来将列表框中的文件插入到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

+0

到目前为止,您对此有何研究?你的数据库是什么?你的桌子怎么样?你如何连接到你的数据库?您需要告诉我们一些我们可以使用的其他人无法帮助您 – GuidoG

+0

谢谢@GuidoG 我正在使用sql server ..我有一个数据库DB.mdf 我想将这些文件保存到一个表中包含3列的文件: number_file(AUTO_INCREMENT) name_file path_file –

+0

我认为一个简单的ADO.Net搜索将足以解决这个 提示:使用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(); 
     } 
    } 
} 
相关问题