问题
I'm getting error converting parameters from DateTime to Byte[]. The idea is to show data between 2 specified dates that are entered via controls and displayed on GridView, and using a stored procedure to access data. I don't understand the error, but I'm guessing that all the data is put in an Array and passed on to stored procedure:
string sDateBegin = Request.Form["fromDate"];
DateTime dtDateBegin = Convert.ToDateTime(sDateBegin);
SqlParameter prmDateBegin = new SqlParameter("datebegin", SqlDbType.Timestamp);
prmDateBegin.Value = dtDateBegin;
cmdProc.Parameters.Add(prmDateBegin);
//same code for DateEnd
// data table
DataTable dataTable = new DataTable();
AGridView.DataSourceID = null;
// data adapter
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmdProc);
AGridView.DataSource = dataTable;
//fill datatable
dataAdapter.Fill(dataTable);
回答1:
You've defined the SqlParameter as a Timestamp data type (which is a byte array) rather than a DateTime. Given you're representing a date range it sounds like you should change the parameter data type to DateTime.
回答2:
The error occurred because Convert.ToDateTime tries to do an implicit conversion from any object to a DateTime. The object coming from the control is a string, but not one that could be cast to a DateTime object. It is in fact a date and time represented by a string.
The correct way to construct a DateTime
object is by parsing the string with
DateTime.Parse(string input)
来源:https://stackoverflow.com/questions/9364319/failed-to-convert-parameter-value-from-a-datetime-to-a-byte