0

I have a GridView with two Date columns which are EditTemplates. How do I compare the 2 dates?

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
Don
  • 1
  • 4
  • What have you tried? Just trying to figure out how much help you need. Do you already know how to compare dates? Get the values from the cells? Where, exactly, are you having difficulty, or do you not even know where to start? – David Nov 19 '11 at 09:34
  • I know how to compare the dates. I'm having problems getting the date values. I have start and end DateTime columns in a gridview, so when I'm editing a row I want to compare the values so that the end DateTime is not less than the start date. I've tried to use the CompareValidator in the EditItem Template, but I can only access the dateTime value for the one cell. – Don Nov 21 '11 at 21:55

2 Answers2

0

Normally I think I would do something like this:

if (Convert.ToDateTime(GridView1.Rows[1].Cells[1].Text) > DateTime.Now)....

You could use DateDiff() to find the difference between the dates if DateTime.Compare() does not work for you.

What have you tried?

Community
  • 1
  • 1
Eystein Bye
  • 5,016
  • 2
  • 20
  • 18
0

try like this..

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
        <Columns>
          <asp:TemplateField HeaderText="Start Date">
            <ItemTemplate>
              <asp:Label runat="server" ID="Label1" Text='<%# Eval("StartDate") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:TextBox runat="server" ID="TextBox1" Text='<%# Eval("StartDate","{0:d}")  %>'></asp:TextBox>
            </EditItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField HeaderText="End Date">
            <ItemTemplate>
              <asp:Label runat="server" ID="Label2" Text='<%# Eval("EndDate") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
              <asp:TextBox runat="server" ID="TextBox2" Text='<%# Eval("EndDate","{0:d}") %>'></asp:TextBox>
            </EditItemTemplate>
          </asp:TemplateField>
          <asp:CommandField ShowEditButton="true" />
        </Columns>
</asp:GridView>  

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If (e.Row.RowState = DataControlRowState.Edit) Then
            Dim cv As CompareValidator = New CompareValidator
            e.Row.Cells(1).Controls.Add(cv)
            cv.ControlToValidate = "TextBox2"
            cv.Type = ValidationDataType.Date
            cv.Operator = ValidationCompareOperator.GreaterThan
            cv.ErrorMessage = "End date should be later than start date!"
            cv.ValueToCompare = CType(e.Row.FindControl("TextBox1"),TextBox).Text
        End If
    End Sub

You can change index or anything as your real situation.

I hope it will helps you....

Glory Raj
  • 17,397
  • 27
  • 100
  • 203