Below is my code. I get my dates from two DatePicker
s in a Windows Form. I am trying to get the rows in Excel that are in between those two dates and do a SqlBulkCopy
to SQL Server. I am getting the wrong dates as a result.
I have tried using a TextBox
instead of DatePicker
but that doesn't work either.
using (SqlConnection strConnection = new SqlConnection(Connection))
{
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
var buttons = (new[] { groupBox1 }
.SelectMany(g => g.Controls.OfType<RadioButton>()
.Where(r => r.Checked)))
.ToList();
SqlCommand query = new SqlCommand();
if (buttons[0].Text == "Date Range")
{
query.CommandText = "Select * from [Sheet0$] where [ChangedDate] between @date1 and @date2;";
}
else
{
query.CommandText = "Select * from [Sheet0$]";
}
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand(query.CommandText, excelConnection))
{
if (buttons[0].Text == "Date Range")
{
string fromDate = this.fromDate.Value.Date.ToString("MM/dd/yyyy");
string toDate = this.toDate.Value.Date.ToString("MM/dd/yyyy");
cmd.Parameters.AddWithValue("@date1", fromDate);
cmd.Parameters.AddWithValue("@date2", toDate);
}
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection, SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null))
{
e.Result = 0;
sqlBulk.DestinationTableName = "tblCMHC";
while (dReader.Read())
{
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
}