如何将 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();
}