将DataGridViewImageColumn中的图像添加到Windows应用程序中的数据库

时间:2014-01-20 10:23:45

标签: c# vb.net winforms datagridview

我正在使用vb.net windows应用程序..我正在填充我的DataGridView,就像这样。我在我的load形式的代码中编写代码:

Dim cd As SqlCommandBuilder = New SqlCommandBuilder(adapter)
        adapter = New SqlDataAdapter("select c.cid,c.CompanyName,d.dtId,d.dtName as Department,d.dtPhone as Phone,d.dtEmail as Email from CompanyMaster_tbl c join  DepartmentMaster_tbl d on c.Cid=d.cId order by cid", con.connect)
        dt1 = New DataTable
        bSource = New BindingSource
        adapter.Fill(dt1) 'Filling dt with the information from the DB
        bSource.DataSource = dt1
        gv.DataSource = bSource
        gv.Columns("cid").Visible = False
        gv.Columns("dtId").Visible = False
        Dim img As New DataGridViewImageColumn
        img.HeaderText = "image"
        gv.Columns.Insert(6, img)

然后在单元格内容中单击我为此上传图像编写了这样的代码:

If e.ColumnIndex = 6 Then
            Dim OFDLogo As New OpenFileDialog()
            OFDLogo.Filter = "JPEG(*.jpg)|*.jpg|BMP(*.bmp)|*.bmp"
            If OFDLogo.ShowDialog() = DialogResult.OK Then
                gv.Rows(e.RowIndex).Cells(6).Value = Image.FromFile(OFDLogo.FileName)
            End If
        End If

在保存按钮中我保存我的部门详细信息:

For i As Integer = 0 To gv.RowCount - 2
    sqlInsertT2 = "Insert Into DepartmentMaster_tbl(dtname,dtphone,dtEmail,Cid) Values ('" + myTI.ToTitleCase(gv.Rows(i).Cells(3).Value) + "','" + gv.Rows(i).Cells(4).Value + "','" + gv.Rows(i).Cells(5).Value + "'," & Ccid & ");"
Next

我在Department master table中还有一个字段..field名称:empimage和datatype image ..我想将相应的图像保存到此table.how我可以从我的数据网格中保存图像查看图像列到数据库 我的DataGridView看起来像这样:enter image description here

1 个答案:

答案 0 :(得分:0)

尝试这样的事情

    Dim sql As String = "INSERT INTO Information VALUES(@name,@photo)"
    Dim cmd As New SqlCommand(sql, con)
    cmd.Parameters.AddWithValue("@name", "DepartmentName")
    Dim ms As New MemoryStream()
    Dim imgCon As New ImageConverter
    ms.Read(imgCon.ConvertTo(DataGridView1.Rows(0).Cells(4).Value, GetType(Byte())), 0, 1024)
    Dim data As Byte() = ms.GetBuffer()
    Dim p As New SqlParameter("@photo", SqlDbType.Image)
    p.Value = data
    cmd.Parameters.Add(p)
    cmd.ExecuteNonQuery()
    MessageBox.Show("Name & Image has been saved", "Save", MessageBoxButtons.OK)