我有来自database(int)的测试变量。我需要在DateTime.AddHours上使用这个变量。
我试过了:
DateTime.Now.AddHours(-<%#test%>)
从数据库测试= 100
所以它必须像:
DateTime.Now.AddHours(-100)
但是编译器会收到错误:
CS1040: Preprocessor directives must appear as the first non-whitespace character on a line
我该如何解决?
从公共页面加载测试:
OleDbConnection Connection;
Connection = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" +
Server.MapPath("~/db.mdb"));
OleDbCommand Command1,
Command1 = new OleDbCommand("SELECT FTPTARIHARALIGI FROM Table1 WHERE ID = 1", Connection);
Connection.Open();
int test = (int)Command1.ExecuteScalar();
我需要在其他类(gridview行)中使用此变量
public void GridView2_RowDataBound(Object sender, GridViewRowEventArgs e)
{
DateTime dt;
if (DateTime.TryParseExact(e.Row.Cells[2].Text, "yyyyMMddHHmm",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
if (dt <= DateTime.Now.AddHours(test * -1))
{
// ...
答案 0 :(得分:1)
如果test
的类型为int
,则可以这样做:
DateTime.Now.AddHours(test * -1);
或:
DateTime.Now.AddHours(0 - test);
您的问题是test
是Page_load
方法中的局部变量。
将其设为全局,并在Page_Load
之外声明:
YourClass
{
int test = 0;
PageLoad Method
{
// set test here
test = (int)Command1.ExecuteScalar();
}
GirdDataRowBound Event
{
// use it here now accessible as it is global
if (dt <= DateTime.Now.AddHours(test * -1))
}
}
答案 1 :(得分:1)
您缺少=
尝试:
DateTime.Now.AddHours(-<%=test%>)
<%# is a data binding syntax for use in databound controls.
<%= is a short cut for Response.Write.
<%@ is a directive to include a namespace, page directives, etc.