Search code examples
c#vb.nettimespancode-translation

How to translate this code from VB.NET to C#? (translators are not working)


I'm having problems translating this code to C# from VB.NET. This code is supposed to take a value from each cell of a column in a database (let's call it column1, it's data type is datetime, so, the format is like this: 12/19/2011 7:42:30 PM), and find the timespan between the Datetime.Now and that value of column1 for each row in a gridview control. Some guy gave me this code that works perfectly in VB.NET:

<asp:TemplateField HeaderText="TimeSpan"> 
            <ItemTemplate> 
                <asp:Label ID="Label1" runat="server" Text='<%# TimeSpan(IIf(IsDBNull(Eval("column1")), DateTime.Now,Eval("column1"))) %>'></asp:Label> 
            </ItemTemplate> 
 </asp:TemplateField>

And for the codebehind:

Protected Function TimeSpan(ByVal Duration As DateTime) As TimeSpan
        Dim date1 As DateTime = Duration
        Dim date2 As DateTime = DateTime.Now
        Dim ts As TimeSpan = (date2 - date1)
        Return ts
    End Function

And in VB.NET it works, but when I try to translate it to C#, and run my application, I get these two errors:

-The best overloaded method match for '_Default.TimeSpan(System.DateTime)' has some invalid argument -Argument 1: cannot convert from 'object' to 'System.DateTime'

Can someone please help me with this? A translation that works for the code? Or even another way of doing what I want to do? Thanks

Edited: This is the code (in C#, which I get using translators), which is actually the code that gives me the exceptions that I mentioned before:

<asp:TemplateField HeaderText="TimeSpan"> 
            <ItemTemplate> 
                <asp:Label ID="Label1" runat="server" Text='<%# TimeSpan((Information.IsDBNull(Eval("column1")) ? DateTime.Now : Eval("column1")))
 %>'></asp:Label> 
            </ItemTemplate> 
 </asp:TemplateField>

And for the code behind:

protected TimeSpan TimeSpan(DateTime Duration)
{
    DateTime date1 = Duration;
    DateTime date2 = DateTime.Now;
    TimeSpan ts = (date2 - date1);
    return ts;
}

Solution

  • You seem to have a problem with the calling code not woth the function itself.

    The error says that you try to pass a value of type object to your function TimeSpan. But the only parameter of that function is of type DateTime.

    When you show the code calling the function TimeSpan i can give you advice what to change.

    But as others suggested, the naming of your function and the parameter is very missleading.

    EDIT

    Ok, now i see your calling code. You have to cast the value of Eval("column1") to DateTime:

    <%# TimeSpan(Eval("column1") == System.DBNull.Value 
                         ? DateTime.Now
                         : (DateTime)Eval("column1")) %>