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