c#两个日期之间的差异

时间:2014-08-29 13:20:55

标签: c# asp.net sql-server

在我的GridView中,我有一个方法调用DisplayWarning()

我想计算日期列(在我的SQL服务器中)和DateTime.Now之间的日差,并在GridView中显示我的一个StatusIMG,这是GridView的代码:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="InvoiceID" DataSourceID="SqlDataSource1" CssClass="table table-striped table-bordered" AllowPaging="True" AllowSorting="True">
<Columns>
    <asp:BoundField DataField="InvoiceID" HeaderText="Rechnung Identifikation" InsertVisible="False" ReadOnly="True" SortExpression="InvoiceID" />
    <asp:BoundField DataField="CustomerID" HeaderText="Kunde Identifikation" SortExpression="CustomerID" />
    <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
    <asp:BoundField DataField="Amount" HeaderText="Betrag" SortExpression="Amount" />
    <asp:BoundField DataField="Paid" HeaderText="Bezahlter Betrag" SortExpression="Paid" />
    <asp:BoundField DataField="Rest" HeaderText="Rest" SortExpression="Rest" />
    <asp:BoundField DataField="PaymentType" HeaderText="Zahlungsart" SortExpression="PaymentType" />
    <asp:CheckBoxField DataField="Shipped" HeaderText="erledigt" SortExpression="Shipped" />
    <asp:TemplateField>
    <ItemTemplate>
    <asp:Image runat="server" ImageUrl='<%# DisplayWarning() %>' Width="16" />     
    </ItemTemplate>
    </asp:TemplateField>

</Columns>

这是DisplayWarning()方法:

public string DisplayWarning()
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RechnungConnectionString"].ConnectionString);
    conn.Open();
    SqlCommand datecmd = new SqlCommand("Select DATEDIFF(day,Date,Getdate()) as DiffDate From Invoice", conn);
    SqlDataReader Reader = datecmd.ExecuteReader();
    int RegTime;
    Reader.Read();
    RegTime = Convert.ToInt32(Reader["DiffDate"]); 
    string StatusColor;
    if (RegTime < 7)
    {
        StatusColor = "Image/green-4040.jpg";
    }
    else if (RegTime >= 7 && RegTime < 14)
    {
        StatusColor = "Image/yellow-4040.jpg";
    }
    else if (RegTime >= 14 && RegTime < 21)
    {
        StatusColor = "Image/orange-4040.jpg";
    }
    else
    {
        StatusColor = "Image/red-4040.jpg";
    }
    conn.Close();
    return StatusColor;

}

但问题是当这段代码运行时,只计算数据库中的时间差1的行,而其他行放入相同的RegTime并且它失败

3 个答案:

答案 0 :(得分:0)

更新SqlDataSource1以将此计算作为结果集的一部分包含在内。除此之外,还使用sql CASE语句来返回整个图像字符串。然后,您可以将其直接绑定到图像控件。

答案 1 :(得分:0)

在数据源中添加此属性怎么样?会是更干净的解决方案。

答案 2 :(得分:0)

通常,最好将这些值加载到GridView的DataSource中。然后,您不必再为每一行访问数据库。

但是,根据DataReader的问题,您必须使用(while)-loop循环DataReader中的所有行,如下所示:

public string DisplayWarning()
{
    using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RechnungConnectionString"].ConnectionString))
    using (var datecmd = new SqlCommand("Select DATEDIFF(day,Date,Getdate()) as DiffDate From Invoice", conn))
    {
        conn.Open();
        using (var reader = datecmd.ExecuteReader())
        {
            if (reader.HasRows){
                while (reader.Read())
                {
                    int regTime = reader.GetInt32(0);
                    string statusColor;
                    if (regTime < 7)
                    {
                        statusColor = "Image/green-4040.jpg";
                    }
                    else if (regTime >= 7 && regTime < 14)
                    {
                        statusColor = "Image/yellow-4040.jpg";
                    }
                    else if (regTime >= 14 && regTime < 21)
                    {
                        StatusColor = "Image/orange-4040.jpg";
                    }
                    else
                    {
                        statusColor = "Image/red-4040.jpg";
                    }
                    returnstatusColor;
                }
            }
            else{ 
                // output, log, exception ?!
            }
        }
    }
}

请注意,我还更改了一些其他内容,例如使用using - 这些语句总是一个好主意,以确保f.e.连接关闭(即使出错)。

更新:但是你想为每一行调用这个方法,然后你需要将行的密钥传递给它,这样你就可以将它作为参数传递给sql-query:

<asp:Image runat="server" ImageUrl='<%# DisplayWarning(System.Convert.ToInt32(Eval("InvoiceID"))) %>' Width="16" />     

Codebehind(假设密钥是int):

public string DisplayWarning(int invoiceID)
{
    string sql = @"Select DATEDIFF(day,Date,Getdate()) as DiffDate 
                   From Invoice 
                   WHERE InvoiceID=@InvoiceID";
    using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RechnungConnectionString"].ConnectionString))
    using (var datecmd = new SqlCommand(sql, conn))
    {
        datecmd.Parameters.Add(new SqlParameter("@InvoiceID", SqlDbType.Int)).Value = invoiceID;
        // Here you don't need a loop since you only get one row back
        // ...
    }
}