从现有代码,当前日期绑定网格视图数据

时间:2015-06-12 03:03:46

标签: c# asp.net gridview

我想使用下面的代码并在GridView中显示。 情况是,当用户单击GET CURRENT DATE TRANS时,GridView将显示今天的日期作为结果。我已经将GridView id插入为GridView1

string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        string sql = null;

        connetionString = "Data Source=AXSQL;Initial Catalog=UniKL;User ID=aten;Password=pass@WORD1";
        sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";

        GridView1.DataBind();

        connection = new SqlConnection(connetionString);

        connection.Open();
        command = new SqlCommand(sql, connection);
        command.ExecuteNonQuery();
        command.Dispose();
        connection.Close();  

3 个答案:

答案 0 :(得分:1)

我想您的专栏SubmittedDateTime在sql中的类型为DateTime,因此您还需要在castdate这一列与此当前日期相匹配

cast([SubmmitedDateTime] as Date) = cast(getdate() as date);

所以你的查询将会是这样的

sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE cast([SubmmitedDateTime] as Date) = cast(getdate() as date)";

答案 1 :(得分:0)

一个建议是改变:

sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";

类似于:

sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = " + DateTime.Now.toShortDateString();

sql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = " + DateTime.Now.toString("yyyy-MM-dd");

答案 2 :(得分:0)

您没有为GridView1分配数据源。请使用以下代码:

id  pos_datetime
1   2015-05-05 12:04:50
4   2015-05-05 12:03:40
8   2015-05-05 12:02:42
10  2015-05-05 12:01:30