【问题标题】:How do I use variable on DateTime.AddHours()如何在 DateTime.AddHours() 上使用变量
【发布时间】:2014-11-28 12:09:21
【问题描述】:

我有来自数据库(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))
        {
            // ...

【问题讨论】:

  • 什么是-&lt;%#test%&gt;??如果是 ASP.NET,则添加该标记并显示更多上下文。
  • 目前还不清楚你在哪里使用代码DateTime.Now.AddHours(-&lt;%#test%&gt;)
  • 但是仍然在顶部的代码在哪里:DateTime.Now.AddHours(-&lt;%#test%&gt;)?现在看来您实际上正在使用DateTime.Now.AddHours(test * -1)。此外,如果您从 Page_Load 初始化 局部变量 test,您将无法从 RowDataBound 访问它。请改用字段/属性。
  • 问题是 test 是局部变量
  • 你必须在你的数据库操作类中创建一个属性或者通过返回类型为int的方法返回它,如果它在同一个类但不同的方法,那么请看我更新的帖子

标签: c# asp.net datetime


【解决方案1】:

如果test 的类型为int,您可以这样做:

DateTime.Now.AddHours(test * -1);

或:

DateTime.Now.AddHours(0 - test);

更新:

您的问题是testPage_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))
  }

}

【讨论】:

  • 你也可以-test
  • 不确定@musefan
  • 甚至不需要0...DateTime.Now.AddHours(-test);
  • 页面加载中的测试变量。我需要使用其他类并收到错误 CS0103:当前上下文中不存在名称“test”。页面加载是公开的,其他类也是如此。如何在页面上的任何位置使用此变量?
  • 但是当我这样使用时,GridDataRowBound 读数为 0,而不是 pageload 值。我错过了什么吗?
【解决方案2】:

你不见了=

试试:

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.

【讨论】:

    猜你喜欢
    • 2021-07-28
    • 2014-05-10
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多