We can set the ValueToCompare
in code behind
if (!Page.IsPostBack)
{
string currentDate = DateTime.Today.ToShortDateString();
Comparevalidator1.ValueToCompare = currentDate;
}
for the compare validator:
<asp:CompareValidator ID="Comparevalidator1" runat="server" ErrorMessage="The date must be greater than today"
Operator="GreaterThan" ControlToValidate="txtDate1" Type="date" Display="Dynamic" />
Why not use Page.DataBind?
Consider the following scenario. I need to display the gridview only on the click of the Action button. The datasource is defined declaratively. But, if I use Page.DataBind() it will show the grid even on the page load.
<form id="form1" runat="server">
<asp:TextBox ID="txtDate1" CssClass="firstBox" runat="server" Text=""></asp:TextBox>
<asp:CompareValidator ID="Comparevalidator1" runat="server" ErrorMessage="The date must be greater than today"
Operator="GreaterThan" ControlToValidate="txtDate1" Type="date" Display="Dynamic" />
<asp:Button ID="btnAction" class="submitButton" runat="server" Text="Action" OnClick="btnAction_Click" />
<asp:Button ID="btnDummy" class="submitButton" runat="server" Text="Dummy" OnClick="btnDummy_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" DataSource="<%# EmployeesResult %>">
</asp:GridView>
</form>
Code behind
public partial class ThirdTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Page.DataBind();
if (!Page.IsPostBack)
{
string currentDate = DateTime.Today.ToShortDateString();
txtDate1.Text = currentDate;
Comparevalidator1.ValueToCompare = currentDate;
}
}
protected void btnAction_Click(object sender, EventArgs e)
{
GridView1.DataBind();
string value = GridView1.DataSource.ToString();
}
protected void btnDummy_Click(object sender, EventArgs e)
{
}
//Propertry
public List<Employee> EmployeesResult
{
get
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee { EmpID = 1, EmpName = "Emp1" });
employees.Add(new Employee { EmpID = 2, EmpName = "Emp2" });
return employees;
}
}
}