Update paneel blocks execution of some error messages - asp.net

I ave an asp page with 1 update panels with 2 panels which are controlled by 2 buttons if you click in first button first panel appears and second becomes hidden and if you click second button the same thing happens for the second panel. It's working ok and no problem about that.
The problem begins in the second panel where I have another update panel which is in charge of printing error messages. The messages which just check the length of input are working ok, but those messages which involve querying the database to check the validity of id are not being printed .
I thought the querying are the problem and I've tried them in a separated page without update panels and they are working ok. The problem lays somewhere with Update panels. And I really can't understand where. I would be most grateful if you can help me.
This is front end code(i omit some insignificant details):
<asp:Button ID="Button1" runat="server" Text="[Input your Id?]" />
<asp:Button ID="Button2" runat="server" Text="[Aditional info]" />
.....
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
< asp:Panel ID="Panel1" runat="server">
some code here
</asp:Panel>
<asp:Panel ID="Panel2" runat="server">
<b>*ID Number: </b>
<asp:TextBox ID="IdNo" runat="server" ></asp:TextBox><font size='2'>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" class="errorMess" ErrorMessage="Letters are not Allowed!!" ControlToValidate="IdNumb" ValidationExpression="\d+"
runat="server" />
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:Label ID="errorEm" class="errorMess" runat="server" Text="Please fill in the required fields"></asp:Label>
<asp:Label ID="errorLenght" class="errorMess" runat="server" Text="Id is too long!!!"></asp:Label>
<asp:Label ID="errorUser" class="errorMess" runat="server" Text="Id is not valid!!!"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button5" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button5" runat="server" Text="Generate" /></td></tr>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
and this is backend VB code:
Protected Sub Button5_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button5.Click
If IdNo.Text = "" Then
Panel1.Visible = False
Panel2.Visible = True
errorEm.Visible = True
ElseIf IdNo.Text.Length > 9 Then
Panel1.Visible = False
Panel2.Visible = True
errorLenght.Visible = True
Else
Try 'everything that comes here does not work'
myconn.Open()
Dim stquery As String = "SELECT * from account WHERE user_id= #id"
Dim smd = New MySqlCommand(stquery, myconn)
smd.Parameters.AddWithValue("#id", Convert.ToInt32(IdNo.Text))
Dim myreader = smd.ExecuteReader()
If Not myreader.HasRows Then
Panel1.Visible = False
Panel2.Visible = True
errorUser.Visible = True
myconn.Close()
Return
Else
Panel1.Visible = False
Panel2.Visible = True
myreader.Read()
Dim ErrorMessage As String = "alert('User has been found');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
End If
End Sub

When you want to execute script from inside of Update panel - don't use
Page.ClientScript.RegisterStartupScript
Use
ClientScriptManager.RegisterStartupScript
instead.
Ref: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

Related

Upload files in vb.net

I have a code in vb.net (as shown below) in which it ask to upload a file after the selection of yes button. On checking No button, it doesn't ask us to upload a file as shown below in the images.
************************************************VB Code******************************************************
Protected Sub rblOrgChart_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rblOrgChart.SelectedIndexChanged
ruOrgChart.Visible = False
hlOrgChart.Visible = False
' btnOrgChart.Visible = rblOrgChart.SelectedValue And bolHasWritePermission
hlOrgChart.Visible = rblOrgChart.SelectedValue
If CBool(rblOrgChart.SelectedValue) Then
ruOrgChart.Visible = True
Dim dtFile As DataTable
dtFile = dalClientProfile.GetFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART)
If dtFile.Rows.Count > 0 Then
Dim dr As DataRow = dtFile.Rows(0)
hlOrgChart.NavigateUrl = ruOrgChart.TargetFolder & "/" & dr.Item("FileName")
hlOrgChart.Text = dr.Item("FileName")
hlOrgChart.Visible = True
End If
Else
' If Me.lblOrgChartMissing2.Visible Then Me.lblOrgChartMissing2.Visible = False
End If
End Sub
The code inside the method btnOrgChart_Click is:
Protected Sub btnOrgChart_Click(sender As Object, e As System.EventArgs) Handles btnOrgChart.Click
Try
'If ruOrgChart.InvalidFiles.Count > 0 Then
' lblOrgChartNotPDF.Visible = True
'Else
' lblOrgChartNotPDF.Visible = False
'End If
'------------------------------------------------------------------
' Q07. HAS WRITTEN ORG. CHART [IAPData..tblReadinessProfile_Question ID=9 ]
'------------------------------------------------------------------
If (rblOrgChart.SelectedValue = 1 And ruOrgChart.UploadedFiles.Count > 0) Then
hlOrgChart.Visible = True
'' ''======' BEGIN NEW CODE --- to upload file to virtual directory
Dim sufile As Telerik.Web.UI.UploadedFile = Nothing
For Each sufile In Me.ruOrgChart.UploadedFiles
' for now upload files on webserver
'If AppSettings.Item("Environment") <> "Prod" Then
remoteName = Request.PhysicalApplicationPath
'Else
'remoteName = AppSettings.Item("UploadRootPath").ToString.Trim()
'End If
Dim strPhysicalFilePath As String = remoteName & AppSettings.Item("FileUploadRootPath").ToString & "\" & dtLicensee.Rows(0).Item("UniqueIdentifier").ToString & "\" & dtOrg.Rows(0).Item("OrgCode").ToString & "\"
CreateFileUploaderLink(remoteName)
If Not Directory.Exists(strPhysicalFilePath) Then
Directory.CreateDirectory(strPhysicalFilePath)
End If
hlOrgChart.NavigateUrl = AppSettings.Item("FileUploadRootPath").ToString & "/" & dtLicensee.Rows(0).Item("UniqueIdentifier").ToString & "/" & dtOrg.Rows(0).Item("OrgCode").ToString & "/" & ruOrgChart.UploadedFiles(0).GetName()
dalClientProfile.SaveFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART, ruOrgChart.UploadedFiles(0).GetName(), strPhysicalFilePath, True)
hlOrgChart.Text = ruOrgChart.UploadedFiles(0).GetName()
Dim NewFileName As String
NewFileName = sufile.GetName()
'If File.Exists(strPhysicalFilePath & NewFileName) Then
' Dim script As String = "alert('" + Me.GetLocalResourceObject("err.fileuploaded.text") + "');"
' ScriptManager.RegisterStartupScript(ruOrgChart, ruOrgChart.GetType(), "clientscript", script, True)
' Exit Sub
'End If
sufile.SaveAs(strPhysicalFilePath & NewFileName, True)
' Cancel the connection
RemoveFileUploaderLink(remoteName)
Next
End If
Catch ex As Exception
Dim oErr As New ErrorLog(ex, "Error in btnOrgChart_Click")
Response.Redirect("~/Error/ErrorPage.aspx?type=Err&ui=" & Request.QueryString("ui"), True)
Exit Sub
End Try
End Sub
**********************************************Images*******************************************************
As shown above in the images, on selection of yes it ask us to upload a file.
By default, it always remains No as the value of HasOrgChart is always 0.
rblOrgChart.SelectedValue = IIf(CBool(dtOrg.Rows(0).Item("HasOrgChart")), 1, 0)
******************************************************HTML*************************************************
The .aspx code belonging to the above images and to the above vb codes are:
<div class="grid-c2">
<div>
<asp:UpdatePanel runat="server" ID="Updatepanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="rblOrgChart" EventName="SelectedIndexChanged"/>
</Triggers>
<ContentTemplate>
<asp:RadioButtonList ID="rblOrgChart" runat="server" AutoPostBack="True">
<asp:ListItem ID="rblOrgChartY" runat="server" Value="1" Text="Yes (Please upload the organizational chart as a PDF file)"></asp:ListItem>
<asp:ListItem ID="rblOrgChartN" runat="server" Value="0" Text="No" ></asp:ListItem>
</asp:RadioButtonList>
<div>
<br />
<telerik:RadAsyncUpload ID="ruOrgChart" runat="server" AutoPostBack="true"
HideFileInput="True"
AllowedFileExtensions=".pdf"
OnClientValidationFailed="validationFailed"
onclientfileuploaded="ruOrgChart_Fileuploaded"
MaxFileInputsCount="1"
InitialFileInputsCount="1"
MaxFileSize="5000000"
/>
<div class="fileLink">
<asp:HyperLink runat="server" ID="hlOrgChart" Target="_blank" Visible="false"
Text=""></asp:HyperLink>
</div>
</div>
<br />
<div style="display:none">
<asp:linkButton ID="btnOrgChart" CssClass="btnUpload" runat="server" Text="" />
</div>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
I am wondering what changes do I need to make in the vb.net and .aspx codes so that instead of Yes and No radio button, there is only select button which ask us directly to upload a file with no yes/no options.
You already have a select button on your form. Why not bypass the Yes/No and just use that?
You should have a Sub btnOrgChart_Click code somewhere. Your variable names don't match with your intended actions, but I think that under the Click code, you might want this somewhere:
ruOrgChart.Visible = True
Dim dtFile As DataTable
dtFile = dalClientProfile.GetFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART)
If dtFile.Rows.Count > 0 Then
Dim dr As DataRow = dtFile.Rows(0)
hlOrgChart.NavigateUrl = ruOrgChart.TargetFolder & "/" & dr.Item("FileName")
hlOrgChart.Text = dr.Item("FileName")
hlOrgChart.Visible = True
End If
EDIT: I believe, to remove the radio button section, remove:
<asp:RadioButtonList ID="rblOrgChart" runat="server" AutoPostBack="True">
<asp:ListItem ID="rblOrgChartY" runat="server" Value="1" Text="Yes (Please upload the organizational chart as a PDF file)"></asp:ListItem>
<asp:ListItem ID="rblOrgChartN" runat="server" Value="0" Text="No" ></asp:ListItem>
</asp:RadioButtonList>
and
<Triggers>
<asp:AsyncPostBackTrigger controlid="rblOrgChart" EventName="SelectedIndexChanged"/>
</Triggers>

How to enable and disable buttons in a gridview in asp.net

I currently have a GridView with two buttons that I have added using the following code;
<asp:GridView ID="gvResults" AutoGenerateColumns="False" runat="server" Font-Size="small"
DataKeyNames="BeachHutID" OnRowDataBound="gvResults_RowDataBound" CssClass="BBCSearch">
<Columns>
<asp:BoundField DataField="BeachHutID" SortExpression="BeachHutID" Visible="false">
</asp:BoundField>
<asp:ImageField DataImageUrlField="HutImage" ItemStyle-Width="1%" ReadOnly="true" />
<asp:BoundField HeaderText="Facilities" DataField="Facilities" Visible="false"></asp:BoundField>
<asp:BoundField HeaderText="Info" DataField="Info" Visible="false"></asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="lblHolder" runat="server"></asp:PlaceHolder>
<br />
<asp:PlaceHolder ID="imgHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnHire" CommandArgument='<%# Eval("BeachHutID") %>' runat="server"
Text="Hire Beach Hut" OnClick="Hire_Click" />
<asp:Button ID="ButtonLogin" CommandArgument='<%# Eval("BeachHutID") %>' runat="server"
Text="Login to Hire Beach Hut" OnClick="Login_Redirect" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
What I want to happen is if the user is logged in, the btnHire button should be enabled and showing and if they're not logged in, ButtonLoggedIn is showing and btnHire is hidden. This is the code I have at the moment;
Public Sub PopulateGrid()
Dim AvailableHuts As New DataTable
AvailableHuts = GetData()
gvResults.DataSource = AvailableHuts
gvResults.DataBind()
gvResults.Enabled = True
'If statement controlling the enabling and disabling of the Beach Hut booking button
If Session("LoginID") = "" Then
For Each rowItem As GridViewRow In gvResults.Rows
rowItem.Cells(5).Enabled = True
Next
End If
lblCaption.Text = "Your search returned " + CStr(AvailableHuts.Rows.Count) + " results"
End Sub
At the moment both buttons are enabled at all times and I'm not sure what I need to add/changed to get the desired result.
From the answer posted by #Andrei, I have added the following to to this Sub;
Protected Sub gvResults_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles gvResults.RowDataBound
Dim URL(), Text() As String
Dim img As Image
Dim lbl As Label
Dim FacilitiesImg As PlaceHolder = e.Row.FindControl("imgHolder")
Dim Infolbl As PlaceHolder = e.Row.FindControl("lblHolder")
'Added Code from answer
Dim hireBtn As Button = CType(e.Row.FindControl("btnHire"), Button)
hireBtn.Visible = Not String.IsNullOrEmpty(Session("LoginID"))
'Added Code from answer
Dim LoginBtn As Button = CType(e.Row.FindControl("ButtonLogin"), Button)
LoginBtn.Visible = String.IsNullOrEmpty(Session("LoginID"))
If e.Row.RowType = DataControlRowType.DataRow Then
URL = e.Row.DataItem(3).Split(",")
Text = e.Row.DataItem(2).Split(",")
'Add the Facilities Images to the grid Row
For Each item In URL
If item.ToString <> "" Then
img = New Image
img.ImageUrl = item.ToString
FacilitiesImg.Controls.Add(img)
End If
Next
'Add the information to the grid row
'convert # into a carriage return and * into £
For Each item In Text
If item.ToString <> "" Then
lbl = New Label
lbl.Text = Replace(Replace(item.ToString, "#", "<br />"), "*", "£")
Infolbl.Controls.Add(lbl)
End If
Next
End If
End Sub
However I'm receiving the following error when trying to run the program;
Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class
Any assistance would be much appreciated.
Thanks
Not sure how is your authentication implemented, but let's assume you use HttpContext.Current.Request.IsAuthenticated. Then you can just manipulate Visible property of the buttons in code behind:
btnHire.Visible = HttpContext.Current.Request.IsAuthenticated
ButtonLoggedIn.Visible = Not HttpContext.Current.Request.IsAuthenticated
Update.
Sorry, somehow missed from the post the fact that you seems to be using Session("LoginID") to decide if the use is logged in. The you can do this:
btnHire.Visible = Not String.IsNullOrEmpty(Session("LoginID"))
ButtonLoggedIn.Visible = String.IsNullOrEmpty(Session("LoginID"))
Update 2.
As it turns out, buttons are a part of GridView row. As they are inside the template, you cannot really reach them in the code behind. So you can take two options.
First, you can subscribe to RowDataBound event (which you already did), and inside it do FindControl in the current row to find the necessary button:
Sub gvResults_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
...
Button hireBtn = CType(e.Row.FindControl("btnHire"), Button);
hireBtn.Visible = Not String.IsNullOrEmpty(Session("LoginID"))
and likewise for the second button.
Second, you can try doing it in the markup:
<asp:Button ID="btnHire" CommandArgument='<%# Eval("BeachHutID") %>'
runat="server" Text="Hire Beach Hut" OnClick="Hire_Click"
Visible=<%# String.IsNullOrEmpty(Session("LoginID")) %> />
try
<asp:Button ID="btnHire" CommandArgument='<%# Eval("BeachHutID") %>' runat="server" Visible='<%# islogin()?true:false %>' Text="Hire Beach Hut" OnClick="Hire_Click" />
<asp:Button ID="ButtonLoggedIn" CommandArgument='<%# Eval("BeachHutID") %>' runat="server" Visible='<%# islogin()?false:true %>' Text="Login to Hire Beach Hut" OnClick="Login_Redirect" />
paste this code to aspx.cs page:
Public Shared Function isLogin() As Boolean
Dim stat As Boolean = False
Try
If Session("LoginID") IsNot Nothing AndAlso Session("LoginID") <> "" Then
stat = True
End If
Catch e1 As Exception
stat = False
End Try
Return stat
End Function
Edit2:
Visible='<%# islogin()?false:true %> this means if isLogin() return true then Visible property set to false else it's visible property set to true.

Ajax Update Panel - What am I missing?

Problem: When suburb drop down list value is changed - Page is posting back.
Desired result: Changing value in drop down list updates post code text box value without a page post back (post code text box is normally hidden)
Page code:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:DropDownList ID="Suburb" runat="server" DataTextField="LocalityPhrase"
DataValueField="Locality" AutoPostBack="true" class="DropDown" OnSelectedIndexChanged="Suburb_SelectedIndexChanged"/>
<asp:UpdatePanel runat="server" id="UpdatePanelPostCode" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="Postcode" runat="server" Visible="true"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Suburb" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
Code behind:
Protected Sub Suburb_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Suburb.SelectedIndexChanged
'get postcode from suburb drop down
Dim pCode As String = ""
If Suburb.SelectedValue <> "" Then
pCode = Suburb.SelectedItem.Text.Substring(Len(Suburb.SelectedItem.Text) - 5, 4)
End If
Postcode.Text = pCode
End Sub
It appears there was something wrong with my install of the AJAX toolkit. Removed and reloaded it in Visual Studio (2008) and all is well.

Update panel automatically clears textboxes

I'm trying to combine an event of automatic printing of messages in case the passwords will not match. For that purpose I'm using an Update panel.
The Error message prints perfectly My problem is that both text-boxes automatically created after it. even thought I don't specify it in the code. I can't understand what have I done wrong.
This is the code for front end:
<asp:TextBox ID="NonPass1" runat="server" TextMode="Password"></asp:TextBox>
<asp:TextBox ID="NonPass2" runat="server" TextMode="Password" autopostback="True"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanel6" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel6" runat="server">
<asp:Label ID="Label1" class="errorMess" runat="server" Text="The Passwords do not match!!!"></asp:Label>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="NonPass2" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
this is the back end code(I'm using VB):
Protected Sub NonPass2_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles NonPass2.TextChanged
If NonPass1.Text <> NonPass2.Text Then
Panel3.Visible = False
Panel6.Visible = True
Else
Panel3.Visible = False
Panel6.Visible = False
End If
End Sub
maybe you can use javascript functions.
<script>
var t1 = false; // textbox1 onfocus triggered = true;
var t2 = false; // textbox2 onfocus triggered = true;
function clearTBox() {
if (t1 && t2) {
if (document.getElementById("textbox1Name").value != document.getElementById("textbox1Name2").value) {
alert("Insert your code here");
}
}
}
</script>
Heres what i use in c# for this, maybe you can inherit the technique
private void ClearTextBoxes()
{
Action<Control.ControlCollection> func = null;
func = (controls) =>
{
foreach (Control control in controls)
if (control is TextBox)
(control as TextBox).Clear();
else
func(control.Controls);
};
func(Controls);
}
then call cleartextboxes();
Hope that helped :)
what do you mean :
My problem is that both text-boxes automatically created after it
please, make your question more clearance
Try not to use updatepanel,
try this
<asp:TextBox ID="NonPass1" runat="server" TextMode="Password"></asp:TextBox>
<asp:TextBox ID="NonPass2" runat="server" TextMode="Password" autopostback="True"></asp:TextBox>
<div id="Div_Error" runat="server" visible="false" style="width:100%">
<asp:Label ID="Label1" class="errorMess" runat="server" Text="The Passwords do not match!!!"></asp:Label>
and use this in the code behind:
Protected Sub NonPass2_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles NonPass2.TextChanged
If NonPass1.Text <> NonPass2.Text Then
Div_Error.visible=true;
Else
Div_Error.visible=false;
End If
End Sub
The only logical reason for the behavior as you described is perhaps, you put the above password boxes inside another UpdatePanel.
Therefore, the password boxes will be reloaded on postbacks (textchanged event), and TextBox of type Password do not retain its value after postbacks for security reason.
Though, if security is not a concern for you, there is a workaround to 'avoid' the password textboxes from being cleared on postbacks, by reassigning their values every time postbacks occur. Just include the following codes in the page Load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
NonPass1.Attributes.Add("value", NonPass1.Text)
NonPass2.Attributes.Add("value", NonPass2.Text)
End Sub
this is a simple example:
<table class="mytable" cellspacing="0" style="width: 100%">
<tr>
<td>
<asp:TextBox ID="Txt_Pass" runat="server" ></asp:TextBox>
</td>
<td>
<asp:TextBox ID="Txt_Re_Pass" runat="server" ></asp:TextBox>
</td>
<td width="66%" align="left">
<asp:Button ID="Btn_Filter" runat="server" Text="" Height="22px" />
</td>
</tr>
</table>
<br />
<div id="Div_Error" runat="server" visible="false" style="width:100%">
<asp:Label ID="lbl_Error" runat="server" class="msg">
</asp:Label>
</div>
and in the code behind , use this:
Protected Sub Btn_Filter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Btn_Filter.Click
If Trim(Txt_Re_Pass.Text) <> "" Then
Div_Error.Visible = False
if Txt_Pass.Text <> Txt_Re_Pass.Text then
Div_Error.Visible = True
lbl_Error.text="The Passwords do not match!!!""
else
Div_Error.Visible = False
End if
Else
Div_Error.Visible = True
lbl_Error.text="Please re enter your password"
End If
End Sub

How to assign value to the DropBox text propery?

I'm writing a program where user has 3 drop boxes to input date, month and a year. after user selects the values I concatenate them and check for valid By default when a page loads I need to assign a current day, month and year to each drop box accordingly. Then I check validity of the date and pass value to the database.
My problem is that when I assign the values to the text of DropBoxes upon the loading of the page they are becoming permanent. even if the index is changed the values which are passed to the database are the ones which assigned to them when the page is loaded.
I can't actually understand what am I doing wrong:
these are the code samples which I've used:
I populate them with a current date values using folowing code(on the page Load event):
Dim CurYear As Integer = DatePart("yyyy", Now)
Dim CurDate As Integer = DatePart("d", Now)
Dim CurMonth As String = Format(Today.Date, "MMMM")
Dim CurDate2 As Integer = DatePart("d", Now)
Dim CurMonth2 As String = Format(Now, "MM")
Dates.Text = CurDate
Monthe.Text = CurMonth
years.Text = CurYear
Month2.Text = CurMonth2
Dates2.Text = CurDate2
Than I had to synchronize the selected index of 2 the dropboxes which contain numerical value of the month and 2 digit format of the day, to to form the proper string for checking of the date
Protected Sub Months_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Months.SelectedIndexChanged
Month2.SelectedIndex = Months.SelectedIndex
TextBox3.Text = years.Text & "-" & Monthes.Text & "-" & Dates.Text
End Sub
Protected Sub Dates_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Dates.SelectedIndexChanged
Dates2.SelectedIndex = Dates.SelectedIndex
TextBox3.Text = years.Text & "-" & Monthes.Text & "-" & Dates.Text
End Sub
And this is front end ASP code:
<asp:DropDownList ID="Dates" runat="server" autopostback="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem>1</asp:ListItem>
...
<asp:ListItem>26</asp:ListItem>
<asp:ListItem>27</asp:ListItem>
<asp:ListItem>28</asp:ListItem>
<asp:ListItem>29</asp:ListItem>
<asp:ListItem>30</asp:ListItem>
<asp:ListItem>31</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Months" runat="server" autopostback="true" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>January</asp:ListItem>
...
<asp:ListItem>November</asp:ListItem>
<asp:ListItem>December</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="years" runat="server" autopostback="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Dates2" runat="server" AutoPostBack="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem>01</asp:ListItem>
<asp:ListItem>02</asp:ListItem>
....
<asp:ListItem>29</asp:ListItem>
<asp:ListItem>30</asp:ListItem>
<asp:ListItem>31</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Month2" runat="server" AutoPostBack="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem>01</asp:ListItem>
....
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
</asp:DropDownList>
Again, if I don't assign the default values to the boxes upon loading of the page it works perfectly. if i do, those values are fixed no mater what you choose
The comparevalidator:
<asp:UpdatePanel ID="UpdatePanel19" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox3" ValidationGroup="CompareValidatorDateTest" runat="server"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Dates" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="Monthes" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="years" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:CompareValidator ID="CompareValidator3" Display="dynamic" ControlToValidate="TextBox3"
Type="Date" Operator="LessThanEqual" Text="Please enter a valid date" runat="server"
ValidationGroup="CompareValidatorDateTest"
I suppose you didnt use IsPostBack property while binding the dropdown with values on page load.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
// Bind your dropdown here here
End If

Resources