保存修改后的Datagridview [英] Saving a modified Datagridview

查看:69
本文介绍了保存修改后的Datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datagridview,其中我添加了4列到3列数据。

在添加的列中,1由一个复选框选项填充,2为空白用户输入,一个填充在DateTimePicker中选择的日期。



一切正常显示,就像我想要的那样,但当我将这些数据保存到New / Different表时,它只保存了从我的select语句中提取的信息,而不是4个添加的列(将它们保留为NULL)。



我相信它在我的计数器中的保存按钮(Button2)上SqlBulkCopy的。但是我不能把手放在它上面。



 进口系统。 Data.SqlClient 
Imports System.Windows.Forms
Imports System.Windows。 Forms.DataGridView
Imports System.Windows.Forms.CheckBox
Imports System。 Windows.Forms.DateTimePicker

公共 Form5

公共 Sub Form5_Load(发件人作为 System。 Object ,e As System.EventArgs) Handles MyBase .Load
Dim CheckBox1 正如 CheckBox
Dim CheckBox2 As CheckBox
Dim CheckBox3 As CheckBox
Dim DateTimePicker1 As DateTimePicker
结束 Sub

私有 Sub Button1_Click(发件人 As System。 Object ,e As System.EventArgs)句柄 Button1.Click
Dim sql As S饰ng
Dim datepicked 作为 日期
datepicked = DateTimePicker1.Text
' 复选框检查循环
如果 CheckBox1.CheckState = False CheckBox2.CheckState = False CheckBox3.CheckState = False 然后
MessageBox.Show( 请选择Shift
退出 Sub
结束 如果
如果 CheckBox1.Checked = True CheckBox2.Checked = True 然后
MessageBox.Show( 请选择仅限一班
退出 Sub
结束 如果
如果 CheckBox2.Checked = True CheckBox3.Checked = True 然后
MessageBox.Show( 请选择仅限一班
退出 Sub
结束 如果
如果 CheckBox1 .Checked = True CheckBox3.Checked = True 然后
MessageBox.Show( 请选择仅限一班
退出 Sub
结束 如果

' Shift的选择
如果 CheckBox1.Checked = True 然后
sql = SELECT MACHINENUMBER,ST YLEWIDTH,来自Loomset的空间WHERE RunFlag1 = 1
ElseIf CheckBox2.Checked = True 然后
sql = SELECT MACHINENUMBER ,STYLEWIDTH,来自Loomset的空间WHERE RunFlag2 = 1
ElseIf CheckBox3.Checked = True 然后
sql = SELECT MACHINENUMBER,STYLEWIDTH,来自Loomset的空间WHERE RunFlag3 = 1
结束 如果

' SQL数据连接
Dim sqlCon1 As SqlConnection( 数据源= SERVER1 \ DEV01;数据库=生产; uid = sa ; pwd = passwordhere
Dim daSWC1 As SqlDataAdapter(sql,sqlCon1)
Dim SQLcmdBuilder1 As SqlCommandBuilder(daSWC1)
Dim ds1 正如 DataSet

' 添加列Picks,Runtime和Date。
Dim AddCol1 As DataGridViewTextBoxColumn
Dim AddCol2 作为 DataGridViewTextBoxColumn
Dim AddCol3 < span class =code-keyword> As New DataGridViewTextBoxColumn
Dim AddCol4 作为 DataGridViewTextBoxColumn

AddCol1.DataPropertyName = Shift
AddCol1.HeaderText = Shift
AddCol1.Name = Shift
AddCol2.DataPropertyName = Picks
AddCol2.HeaderText = < span class =code-string> PICKS
AddCol2.Name = PICKS
AddCol3.DataPropertyName = RunTime
AddCol3.HeaderText = RunTime
AddCol3.Name = RunTime
AddCol4.DataPropertyName = 日期
AddCol4.HeaderText = 日期
AddCol4.Name = 日期
AddCol4.DefaultCellStyle.Format = MM / dd / yyyy

daSWC1.Fill(ds1, MACHINENUMBER
DataGridView1.DataSourc e = ds1.Tables( 0
DataGridView1.Columns.Add(AddCol1)
For 每个 dgvr 作为 DataGridViewRow DataGridView1.Rows
如果 CheckBox1.Checked 那么
dgvr.Cells( Shift)。值= 1
ElseIf CheckBox2.Checked 然后
dgvr.Cells( Shift)。值= 2
ElseIf CheckBox3.Checked 然后
dgvr.Cells( Shift)。值= 3
结束 如果
下一步
DataGridView1.Columns。添加(AddCol2)
DataGridView1.Columns.Add(AddCol3)
DataGridView1.Columns.Add(AddCol4)
对于 每个 dgvr As DataGridViewRow In DataGridView1.Rows
dgvr.Cells( Date)。Value = datepicked
下一步

结束 Sub

私有 Sub Button2_Click(发件人 As S. ystem。 Object ,e As System.EventArgs) Handles Button2.Click
Dim dt As DataTable
dt = DataGridView1.DataSource

Dim objSQLCon 正如 SqlConnection( 数据源= SERVER1 \DEV01; database = Production; uid = sa; pwd = passwordhere
Dim TableName 作为 字符串 = ProdEnter_SAVE
Dim strErrorMessage As St ring =

尝试
如果 objSQLCon.State = ConnectionState.Open 那么
objSQLCon.Close()
结束 如果

objSQLCon.Open()

尝试
' 执行从DataTable到SQL表的复制数据的批量复制
如果 dt.Rows.Count> 0 然后
使用 Sqlbcp As SqlBulkCopy = SqlBulkCopy(objSQLCon)
Sqlbcp.DestinationTableName = [dbo]。[& TableName& ]
Sqlbcp.WriteToServer(dt)
结束 使用
结束 如果

Catch sqlEx As SqlException
strErrorMessage = SqlException:& sqlEx.Message&环境。新浪潮& 错误代码:& sqlEx.ErrorCode
Catch ex As 异常
strErrorMessage = ex.Message
结束 尝试

Catch ex As 异常
strErrorMessage = 打开SQL连接失败& ex.Message
结束 尝试
结束 Sub

私有 Sub Button3_Click(发件人作为系统。对象,e As System.EventArgs)句柄 Button3.Click
.Close()
结束 Sub

结束

解决方案

< blockquote>你的代码几乎是正确的只需将它添加到你的button2_click()事件

 私有  Sub  Button2_Click(发件人 As  System。 Object ,e  As  System.EventArgs) 句柄 Button2.Click 
Dim dt As DataTable
Dim ds As System.Data.DataSet
ds = DatagridviewToDataset(DataGridView1)' < span class =code-comment>这是返回datagridview数据集的函数
dt = ds.Tables( 0
' 其余代码

添加此功能到你的程序

 公共 功能 Datagrid viewToDataset( ByVal  dgv  As  DataGridView) As  System.Data.DataSet 
Dim ds As System.Data.DataSet

' 从中获取数据和结构datagridview并将其作为数据集返回。您可以在项目顶部使用
Imports System.Data声明/从该函数的各个部分中分类并删除system.data
'

尝试
' 向数据集添加新表
ds.Tables.Add(

' 添加列
Dim col As System.Data.DataColumn

' 对于datagridveiw中的每个列,向表中添加一个新列
对于 每个 dgvCol 作为 DataGridViewColumn dgv.Columns
col = System.Data.DataColumn(dgvCol.Name)
ds.Tables( Main)。Columns.Add(col)
下一步

' 从中添加行datagridview
Dim As System.Data.DataRow
< span class =code-keyword> Dim colcount As Integer = dgv.Columns。计数 - 1

对于 i 正如 整数 = 0 dgv.Rows.Count - 1
row = ds.Tables( Main)。Rows.Add

对于 每个作为 DataGridViewColumn dgv.Columns
row.Item( column.Index)= dgv.Rows.Item(i).Cells(column.Index).Value
Next
下一步
返回 ds
Catch ex As 异常
' 抓住任何潜在的错误, DISP将它们放到用户
MessageBox.Show( 从DataGridView转换的错误& ex.InnerException.ToString,_
从DataGridView转换错误,MessageBoxButtons.OK, MessageBoxIcon。错误
返回 Nothing
结束 尝试
结束 功能


I have a datagridview where i added 4 columns to 3 columns of data.
Of the added columns, 1 is filled by a checkbox selection, 2 are blank for User Entry and one is filled with a Date Selected in a DateTimePicker.

Everything displays correctly, just like I want it, but when I save this data to a New/Different table, it only saves the information pulled from my select statement, not the 4 added columns (leaves them as NULL).

I believe its in my counter in my save button (Button2) on the SQLBulkCopy. But cant put my finger on on it.

Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Windows.Forms.DataGridView
Imports System.Windows.Forms.CheckBox
Imports System.Windows.Forms.DateTimePicker

Public Class Form5

    Public Sub Form5_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim CheckBox1 As New CheckBox
        Dim CheckBox2 As New CheckBox
        Dim CheckBox3 As New CheckBox
        Dim DateTimePicker1 As New DateTimePicker
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim sql As String
        Dim datepicked As Date
        datepicked = DateTimePicker1.Text
        'Checkbox Check Loop
        If CheckBox1.CheckState = False And CheckBox2.CheckState = False And CheckBox3.CheckState = False Then
            MessageBox.Show("Please select a Shift")
            Exit Sub
        End If
        If CheckBox1.Checked = True And CheckBox2.Checked = True Then
            MessageBox.Show("Please select a One Shift Only")
            Exit Sub
        End If
        If CheckBox2.Checked = True And CheckBox3.Checked = True Then
            MessageBox.Show("Please select a One Shift Only")
            Exit Sub
        End If
        If CheckBox1.Checked = True And CheckBox3.Checked = True Then
            MessageBox.Show("Please select a One Shift Only")
            Exit Sub
        End If

        'Selection of Shift 
        If CheckBox1.Checked = True Then
            sql = "SELECT MACHINENUMBER, STYLEWIDTH, SPACES FROM Loomset WHERE RunFlag1 = 1"
        ElseIf CheckBox2.Checked = True Then
            sql = "SELECT MACHINENUMBER, STYLEWIDTH, SPACES FROM Loomset WHERE RunFlag2 = 1"
        ElseIf CheckBox3.Checked = True Then
            sql = "SELECT MACHINENUMBER, STYLEWIDTH, SPACES FROM Loomset WHERE RunFlag3 = 1"
        End If

        'SQL Data connection
        Dim sqlCon1 As New SqlConnection("Data Source=SERVER1\DEV01;database=Production;uid=sa;pwd=passwordhere")
        Dim daSWC1 As New SqlDataAdapter(sql, sqlCon1)
        Dim SQLcmdBuilder1 As New SqlCommandBuilder(daSWC1)
        Dim ds1 As New DataSet

        'Adds the columns Picks, Runtime and Date.
        Dim AddCol1 As New DataGridViewTextBoxColumn
        Dim AddCol2 As New DataGridViewTextBoxColumn
        Dim AddCol3 As New DataGridViewTextBoxColumn
        Dim AddCol4 As New DataGridViewTextBoxColumn

        AddCol1.DataPropertyName = "Shift"
        AddCol1.HeaderText = "Shift"
        AddCol1.Name = "Shift"
        AddCol2.DataPropertyName = "Picks"
        AddCol2.HeaderText = "PICKS"
        AddCol2.Name = "PICKS"
        AddCol3.DataPropertyName = "RunTime"
        AddCol3.HeaderText = "RunTime"
        AddCol3.Name = "RunTime"
        AddCol4.DataPropertyName = "Date"
        AddCol4.HeaderText = "Date"
        AddCol4.Name = "Date"
        AddCol4.DefaultCellStyle.Format = "MM/dd/yyyy"

        daSWC1.Fill(ds1, "MACHINENUMBER")
        DataGridView1.DataSource = ds1.Tables(0)
        DataGridView1.Columns.Add(AddCol1)
        For Each dgvr As DataGridViewRow In DataGridView1.Rows
            If CheckBox1.Checked Then
                dgvr.Cells("Shift").Value = 1
            ElseIf CheckBox2.Checked Then
                dgvr.Cells("Shift").Value = 2
            ElseIf CheckBox3.Checked Then
                dgvr.Cells("Shift").Value = 3
            End If
        Next
        DataGridView1.Columns.Add(AddCol2)
        DataGridView1.Columns.Add(AddCol3)
        DataGridView1.Columns.Add(AddCol4)
        For Each dgvr As DataGridViewRow In DataGridView1.Rows
            dgvr.Cells("Date").Value = datepicked
        Next

    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Dim dt As New DataTable
        dt = DataGridView1.DataSource

        Dim objSQLCon As New SqlConnection("Data Source=SERVER1\DEV01;database=Production;uid=sa;pwd=passwordhere")
        Dim TableName As String = "ProdEnter_SAVE"
        Dim strErrorMessage As String = ""

        Try
            If objSQLCon.State = ConnectionState.Open Then
                objSQLCon.Close()
            End If

            objSQLCon.Open()

            Try
                'To Perform Bulk Copy for copy data from DataTable to SQL Table
                If dt.Rows.Count > 0 Then
                    Using Sqlbcp As SqlBulkCopy = New SqlBulkCopy(objSQLCon)
                        Sqlbcp.DestinationTableName = "[dbo].[" & TableName & "]"
                        Sqlbcp.WriteToServer(dt)
                    End Using
                End If

            Catch sqlEx As SqlException
                strErrorMessage = "SqlException: " & sqlEx.Message & Environment.NewLine & "Error Code: " & sqlEx.ErrorCode
            Catch ex As Exception
                strErrorMessage = ex.Message
            End Try

        Catch ex As Exception
            strErrorMessage = "Open SQL connection failed" & ex.Message
        End Try
    End Sub

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
        Me.Close()
    End Sub

End Class

解决方案

your code is almost correct just add this to your button2_click() event

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Dim dt As New DataTable
        Dim ds As New System.Data.DataSet
        ds = DatagridviewToDataset(DataGridView1) 'This is the function which return you the dataset of your datagridview
        dt = ds.Tables(0)
        'And the rest of your code

Add this Function to your program

Public Function DatagridviewToDataset(ByVal dgv As DataGridView) As System.Data.DataSet
        Dim ds As New System.Data.DataSet

        'Take the data and structure from the datagridview and return it as a dataset.  You can use 
        '"Imports System.Data" declaration at the top of your project/class and remove the system.data 
        'from the various parts of this function.

        Try
            'Add a new table to the dataset
            ds.Tables.Add("Main")

            'Add the columns
            Dim col As System.Data.DataColumn

            'For each colum in the datagridveiw add a new column to your table
            For Each dgvCol As DataGridViewColumn In dgv.Columns
                col = New System.Data.DataColumn(dgvCol.Name)
                ds.Tables("Main").Columns.Add(col)
            Next

            'Add the rows from the datagridview
            Dim row As System.Data.DataRow
            Dim colcount As Integer = dgv.Columns.Count - 1

            For i As Integer = 0 To dgv.Rows.Count - 1
                row = ds.Tables("Main").Rows.Add

                For Each column As DataGridViewColumn In dgv.Columns
                    row.Item(column.Index) = dgv.Rows.Item(i).Cells(column.Index).Value
                Next
            Next
            Return ds
        Catch ex As Exception
            'Catch any potential errors and display them to the user
            MessageBox.Show("Error Converting from DataGridView" & ex.InnerException.ToString, _
            "Error Converting from DataGridView", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return Nothing
        End Try
    End Function


这篇关于保存修改后的Datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆