0

如何将 DataGrid 中的列数据插入到 sql 表中。

        private void btUpload_Click(object sender, RoutedEventArgs e)
    {

        // Configure open file dialog box 
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        // Filter by Excel Worksheets
        dlg.Filter = "Excel Worksheets|*.xls";

        dlg.ShowDialog();

        // Show open file dialog box 
        Nullable<bool> result = dlg.ShowDialog();         

        // Process open file dialog box results 
        if (result == true)
        {

            // Create connection string variable. Modify the "Data Source"
            // parameter as appropriate for your environment.
            String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source=" + dlg.FileName+ ";" +
                "Extended Properties=Excel 8.0;";               

            // Create connection object by using the preceding connection string.
            OleDbConnection objConn = new OleDbConnection(sConnectionString);

            // Open connection with the database.
            objConn.Open();

SQL SELECT 命令显示工作表中的数据。

            // Create new OleDbCommand to return data from worksheet.
            OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [codereward$]", objConn);

            // Create new OleDbDataAdapter that is used to build a DataSet
            // based on the preceding SQL SELECT statement.
            OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();

            // Pass the Select command to the adapter.
            objAdapter1.SelectCommand = objCmdSelect;

            // Create new DataSet to hold information from the worksheet.
            DataSet objDataset1 = new DataSet();

使用工作表中的信息填充 DataSet。

            objAdapter1.Fill(objDataset1, "XLData");

            // Bind data to DataGrid control.
            dgCodeDisp.ItemsSource = objDataset1.Tables[0].DefaultView;

            // Clean up objects.
            objConn.Close();
        }

我的插入命令,在这里我想将 DataGrid 中代码中的数据插入到代码中。

        sc.Open();
        cmd = new SqlCommand("Insert into RewardCodes (Code, value1, value2, ID) values('" + dgCodeDisp + "','" + ckv1.IsChecked.ToString() + "','" + ckv2.IsChecked.ToString() + "', '" + txtId.Text + "')", sc);
        cmd.ExecuteNonQuery();
    }
4

1 回答 1

1

我认为您在实施过程中使事情复杂化。在您使用SQL Server表格的情况下,Bulkcopy, 是合适的工具。它会在你的桌子上做所有的插入。这是一个完整的教程

于 2013-10-01T16:40:32.323 回答