在网格中按日期显示数据中的错误

时间:2012-07-18 11:09:49

标签: c#

我试图按日期显示数据,但我没有得到答案,请帮助我..

public void gettoday()
    {
        con.Open();
        {
            string strview = @"select MRNO,MaterialCode,Description,Specification,
                              Category as Cat,Source as Sor,Population as Pop, StockInStores as Stock, MRRating as Rating,PreparedBy,PreparedDate,CheckedBy,CheckedDate,ApprovedBy,ApprovedDate  
                         from tbl_KKSMaterialRaise 
                         where PreparedDate between (getdate()-1) and (getdate()+1)";
            SqlCommand cd = new SqlCommand(strview, con);
            SqlDataReader reader = cd.ExecuteReader();

            GridView1.DataSource = reader;
            GridView1.DataBind();
        }
        con.Close();


    }

1 个答案:

答案 0 :(得分:1)

您的SQL查询似乎不正确。所以你想在昨天和明天之间选择记录。

然后这应该有效(假设SQL-Server,因为您使用GetDate):

WHERE PreparedDate BETWEEN DateAdd(d,-1,GetDate()) AND DateAdd(d,+1,GetDate())

编辑:除此之外,您应该始终使用using-statement(对于任何实现IDisposable的对象),以确保即使出现异常也会关闭连接:< / p>

const string strview = @"select MRNO,MaterialCode,Description,Specification, Category as Cat,Source as Sor,Population as Pop, StockInStores as Stock, MRRating as Rating,PreparedBy,PreparedDate,CheckedBy,CheckedDate,ApprovedBy,ApprovedDate  
                         FROM tbl_KKSMaterialRaise 
                         WHERE PreparedDate BETWEEN DateAdd(d,-1,GetDate()) AND DateAdd(d,+1,GetDate())";
// don't use global connection objects
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(strview, con))
{
    con.Open();
    GridView1.DataSource = cmd.ExecuteReader();
    GridView1.DataBind();
}