简体   繁体   English

无法将参数值从DateTime转换为Byte []

[英]Failed to convert parameter value from a DateTime to a Byte[]

I'm getting error converting parameters from DateTime to Byte[]. 我将参数从DateTime转换为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. 想法是显示在两个指定日期之间的数据,这些日期通过控件输入并显示在GridView上,并使用存储过程访问数据。 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);

You've defined the SqlParameter as a Timestamp data type (which is a byte array) rather than a DateTime. 您已将SqlParameter定义为Timestamp数据类型(它是字节数组),而不是DateTime。 Given you're representing a date range it sounds like you should change the parameter data type to DateTime. 给定您要表示的日期范围,这听起来应该将参数数据类型更改为DateTime。

The error occurred because Convert.ToDateTime tries to do an implicit conversion from any object to a DateTime. 发生错误是因为Convert.ToDateTime试图将任何对象隐式转换为DateTime。 The object coming from the control is a string, but not one that could be cast to a DateTime object. 来自控件的对象是一个字符串,但是不能转换为DateTime对象。 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对象的正确方法是使用

DateTime.Parse(string input)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM