【发布时间】:2019-04-06 14:00:26
【问题描述】:
我希望从列表框更改为 DataGridView。
从列表框中,我可以查看数据并使用查看/下载 varbinary 选择项目。
我可以用 DataGridView 做同样的事情吗?
这是我的代码:
Dim sqlcon As New SqlConnection("Data Source=DESKTOP-U7KC2PG\SQLEXPRESS;Initial Catalog=kankon;Integrated Security=True")
Dim cmd As SqlCommand
Dim adapter As SqlDataAdapter
Dim ofd As New OpenFileDialog
Dim Dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
adapter = New SqlDataAdapter("select ID, Label + Extension as 'FileName', [Filesys] from TBL_FILES", sqlcon)
adapter.Fill(Dt)
Me.ListBox1.DataSource = Dt
Me.ListBox1.DisplayMember = "FileName"
Me.ListBox1.ValueMember = "ID"
Me.Dt.Constraints.Add("Primary", Dt.Columns("ID"), True)
Catch ex As Exception
End Try
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Try
Dim FileName As String = Me.ListBox1.Text
Dim row As DataRow = Dt.Rows.Find(ListBox1.SelectedValue)
Dim file_data() As Byte = CType(row(2), Byte())
Dim fs As New FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write)
fs.Write(file_data, 0, file_data.Length)
Process.Start(FileName)
Catch ex As Exception
End Try
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Try
ofd.Filter = "All File (*.*) |*.*"
If ofd.ShowDialog = DialogResult.OK Then
Label1.Text = ofd.FileName
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
cmd = New SqlCommand("Insert into TBL_FILES (Label, Filesys,Extension) values (@Label, @Filesys, @Extension)", sqlcon)
sqlcon.Open()
cmd.Parameters.Add(New SqlParameter("@Label", SqlDbType.NVarChar, 50)).Value = TextBox1.Text
cmd.Parameters.Add(New SqlParameter("@Extension", SqlDbType.NVarChar, 50)).Value = TextBox1.Text
Dim fs As New FileStream(ofd.FileName, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fs)
Dim file() As Byte = br.ReadBytes(br.BaseStream.Length)
cmd.Parameters.Add(New SqlParameter("Filesys", SqlDbType.VarBinary)).Value = file
cmd.ExecuteNonQuery()
sqlcon.Close()
MsgBox(" file saved ", MsgBoxStyle.Information, "info")
Catch ex As Exception
End Try
End Sub
【问题讨论】:
-
将您的
DataTable绑定到BindingSource,然后将其绑定到DataGridView。当用户选择一行时,您可以从BindingSource的Current属性中获取底层DataRowView。你可以对ListBox做同样的事情。 -
对不起,我是初学者编码,您能帮我编写新代码吗?我的 DataGridView 名称是 TBL_FILESDataGridView ,数据集是 TBL_FILES 谢谢
-
作为初学者并不意味着等待别人为你编写代码。这意味着研究适当的主题以找到您可以使用的信息。我为您提供了可用于进行该研究的关键字。现在你需要这样做。
-
永远不要使用空的 try-catch。您总是想知道异常是什么,以便修复它。