Dynamic required validator and textboxes not firing inside panel - asp.net

I am having a problem with validation. I created a dynamic textboxes with corresponding dynamic numeric validator but it's not firing....
Here is my code
code behind on_load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
For i = 0 To AssetByDimension(oVal).Rows.Count - 1
Dim lt As New Literal()
Dim label As New Label()
Dim count As Integer = pnlDimension.Controls.OfType(Of Label)().ToList().Count
label.Text = "<b>" + AssetByDimension(oVal).Rows(i)("Dimension_Type") + " (" + AssetByDimension(oVal).Rows(i)("Unit_Of_Measure_Code") + "): </b>"
pnlDimension.Controls.Add(label)
Dim textbox As New TextBox()
count = pnlDimension.Controls.OfType(Of TextBox)().ToList().Count
textbox.ID = "txtDimension" & i
pnlDimension.Controls.Add(textbox)
Dim vdr As New RegularExpressionValidator
vdr.ControlToValidate = "txtDimension" & i
vdr.ValidationExpression = "\d+"
vdr.ErrorMessage = "Numbers only"
vdr.BorderColor = Drawing.Color.Red
vdr.ForeColor = Drawing.Color.Red
vdr.SetFocusOnError = True
pnlDimension.Controls.Add(vdr)
lt.Text = "<br /><br />"
pnlDimension.Controls.Add(lt)
Next
End Sub
and here's the button event handler
Protected Sub btnSaveDim_Click(sender As Object, e As EventArgs)
if Page.isvalid then
Response.Redirect("AddAsset.aspx")
else
'do nothing...
end
End Sub
What I have tried:
I tried to use Page.isValid but is not working...
Hoping for your kind

Related

How can I use AddHandler AddressOf

I'm working on a web app using Visual Studio VB.NET. I have a web form with two panels. I have the code below:
Protected Sub WebForm2_load(sender As Object, e As EventArgs) Handles Me.Load
Dim y As Integer = 1
Protected cr(100) As Button
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
Dim requ As String
requ = "SELECT DISTINCT ENSEIGNEMENTS.Code_Mat From ENSEIGNANT INNER Join ENSEIGNEMENTS On ENSEIGNANT.Code_Ens = ENSEIGNEMENTS.Code_Ens where NomUser='" + un + "' and Sem='S1'"
cmd = New SqlCommand(requ, con)
Dim rd As SqlDataReader = cmd.ExecuteReader()
While rd.Read()
cr(y) = New Button
cr(y).Text = rd("Code_Mat").ToString
cr(y).ID = "btn" & y.ToString
Panel1.Controls.Add(cr(y))
AddHandler cr(y).Click, AddressOf btnc
y = y + 1
End While
End Sub
Protected Sub btnc(ByVal sender As Object, ByVal e As System.EventArgs)
Protected cr1(100) As Button
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
Dim btn As Button()
Dim x As Integer = 1
Dim requete As String
cdmat = CType(sender, Button).Text
'Response.Redirect("TestGroupes.aspx")
requete = "SELECT ENSEIGNEMENTS.Gr FROM ENSEIGNANT INNER JOIN ENSEIGNEMENTS ON ENSEIGNANT.Code_Ens = ENSEIGNEMENTS.Code_Ens WHERE (((ENSEIGNEMENTS.Code_Mat)='" + cdmat + "') AND ((ENSEIGNANT.[NomUser])='" + un + "') AND ((ENSEIGNEMENTS.[Sem])='S1'))"
Dim commande As New SqlCommand
commande = New SqlCommand(requete, con)
Dim reader As SqlDataReader = commande.ExecuteReader()
While reader.Read()
cr1(x) = New Button()
cr1(x).Text = reader("Gr").ToString
cr1(x).ID = "bt" & x.ToString
Panel2.Controls.Add(cr1(x))
AddHandler cr1(x).Click, AddressOf Groupe
x = x + 1
End While
End Sub
Protected Sub Groupe(sender As Object, e As EventArgs)
MsgBox("hhhhh")
End Sub
My problem is that AddHandler cr(y).Click, AdressOf btnc and WenForm2_load work well but AddHandler cr1(x).Click, AdressOf Groupe does not: when I click on a button in Panel2 nothing happens.
You always create the primary buttons (Code_Mat), but you also need to re-create the secondary buttons (Gr) when it posts back, so you'll need to save the variable(s) used to create those secondary buttons.
As a demonstration, I created a new Web Forms project named "testing" with one page named "index.aspx":
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="index.aspx.vb" Inherits="testing.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Panel ID="Panel2" runat="server"></asp:Panel>
</div>
<asp:Literal id="msg" runat="server">msg</asp:Literal>
</form>
</body>
</html>
Using this code-behind:
Public Class index
Inherits System.Web.UI.Page
Sub Groupe(sender As Object, e As EventArgs)
Dim bn = DirectCast(sender, Button)
msg.Text = bn.CommandArgument
End Sub
Sub CreateSecondaryButtonsHelper(codeMat As String)
Panel2.Controls.Clear()
For i = 1 To 3
Dim bn As New Button With {.Text = "Gr" & i & codeMat, .ID = "bnB" & i, .CommandArgument = "Hello from " & codeMat & i}
AddHandler bn.Click, AddressOf Groupe
Panel2.Controls.Add(bn)
Next
End Sub
Sub CreateSecondaryButtons(ByVal sender As Object, ByVal e As System.EventArgs)
Dim clickedButton = DirectCast(sender, Button)
CreateSecondaryButtonsHelper(clickedButton.Text)
Session("CodeMat") = clickedButton.Text
End Sub
Sub CreateMainButtons()
For i = 1 To 3
Dim bn As New Button With {.Text = "CodeMat" & i, .ID = "bnA" & i}
AddHandler bn.Click, AddressOf CreateSecondaryButtons
Panel1.Controls.Add(bn)
Next
If Session("CodeMat") IsNot Nothing Then
CreateSecondaryButtonsHelper(CStr(Session("CodeMat")))
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
CreateMainButtons()
End Sub
End Class
It is rather dull, but I think it shows what you want to do.
N.B. You should make a new SqlConnection each time you use it and call .Dispose() on it as soon as you've finished using it. Also, using SQL parameters to pass the values instead of making up a string with them will make it more reliable and avoid SQL injection attacks.

Dynamic Controls with radio buttons

I want to create a dynamic Website. I created a RadioButton List with four radio buttons. I also created a loop where I created 11 textboxes and then I made an "If" function. I did the same loop with 6 other textboxes. My goal is to display the 11 textboxes when I click on one radio button and the 6 other textboxes when I click on an other radio button. But instead, everything appears when I click on each radio button. My question is : what should I do when I click on one radio button the 11 textboxes appears, and when I click on an other radio button the 6 other textboxes appears ?
The code below:
Public Class WebForm1
Inherits System.Web.UI.Page
Protected MonRadioButton As New System.Web.UI.WebControls.RadioButtonList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
MonRadioButton.RepeatDirection = RepeatDirection.Horizontal
MonRadioButton.Width = Unit.Pixel(400)
MonRadioButton.DataSource = Split("Click,OnChanged,Clicked,Changed", ",")
MonRadioButton.DataBind()
MonRadioButton.SelectedIndex = 0
MonRadioButton.AutoPostBack = True
PlaceHolder1.Controls.Add(MonRadioButton)
Dim MonTextBox As TextBox
For i As Integer = 0 To 10
MonTextBox = New TextBox
MonTextBox.ID = "TonTextbox" & i
MonTextBox.Text = MonTextBox.ID
If MonRadioButton.SelectedValue = "OnChanged" Then
MonTextBox.AutoPostBack = True
AddHandler MonTextBox.TextChanged, AddressOf MonTextBox_TextChanged
End If
PlaceHolder1.Controls.Add(MonTextBox)
PlaceHolder1.Controls.Add(New LiteralControl("<br>"))
Next
MonTextBox.Dispose()
If MonRadioButton.SelectedValue = "Click" Then
Dim LeBouton As New Button
LeBouton.Text = "valider"
AddHandler LeBouton.Click, AddressOf LeBouton_Click
PlaceHolder1.Controls.Add(LeBouton)
End If
PlaceHolder1.Controls.Add(New LiteralControl("<br>"))
PlaceHolder1.Controls.Add(New LiteralControl("<br>"))
Dim MonTextBox1 As TextBox
For i As Integer = 0 To 5
MonTextBox1 = New TextBox
MonTextBox1.ID = "TxtBox" & i
MonTextBox1.Text = MonTextBox1.ID
If MonRadioButton.SelectedValue = "Clicked" Then
MonTextBox1.AutoPostBack = True
AddHandler MonTextBox1.TextChanged, AddressOf MonTextBox1_TextChanged
End If
PlaceHolder1.Controls.Add(MonTextBox1)
PlaceHolder1.Controls.Add(New LiteralControl("<br>"))
Next
MonTextBox1.Dispose()
If MonRadioButton.SelectedValue = "Changed" Then
End If
End Sub
Private Sub MonTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim LeTextBox As New TextBox
LeTextBox = CType(sender, TextBox)
Response.Write("Vous venez de modifié : " & LeTextBox.ID & " avec la valeure : " & LeTextBox.Text)
End Sub
Private Sub MonTextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim Txtbox As New TextBox
Txtbox = CType(sender, TextBox)
Response.Write("Vous venez de modifié : " & Txtbox.ID & " avec la valeure : " & Txtbox.Text())
End Sub
Private Sub LeBouton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim LeTextBox As TextBox
For i As Integer = 0 To 10
Try
LeTextBox = New TextBox
LeTextBox = CType(Page.FindControl("TonTextbox" & i), TextBox)
Response.Write("Texbox N°" & i & " : " & LeTextBox.Text & "<br>")
Catch ex As Exception
End Try
Next
End Sub
End Class
The if condition to check the selected value of your round button doesnt affect the creation of the textboxes, all you're doing with the roundbuttons its modifying the behaviour and propoerties of the textboxes. This is what you have
If roundbutton=something then
'Here you change the behaviour of the textbox(postback, text, etc.)
Else
For i = 0 to 5
'Here you add the textboxes
Next
As you see, you're not conditioning the creation to anything, so you need to place your for loop inside your if statement.
For example
If MonRadioButton.SelectedValue = "Clicked" Then
MonTextBox1.AutoPostBack = True
AddHandler MonTextBox1.TextChanged, AddressOf MonTextBox1_TextChanged
For i As Integer = 0 To 5
MonTextBox1 = New TextBox
MonTextBox1.ID = "TxtBox" & i
MonTextBox1.Text = MonTextBox1.ID
PlaceHolder1.Controls.Add(MonTextBox1)
PlaceHolder1.Controls.Add(New LiteralControl("<br>"))
Next
End If

Gridview format issue after show message

I have a Gridview, and one button.
when i click button then show message, but after that my Gridview's format is not correct as before.
please view more in below picture:
Gridview incorrect format after close message
I using this code below to show message:
HttpContext.Current.Response.Write("<script>alert('Đã tồn tại nguồn đơn " & name & ". Bạn không thể tạo thêm được nguồn đơn này nữa')</script>")
Return
=> How to keep previos format?
This code below i using:
Private Sub grvData_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvData.RowCommand
lblError.Text = String.Empty
Dim commandNameType As String = String.Empty
Try
If e.CommandName = "Insert" Then
commandNameType = "thêm"
Dim txtName As TextBox = DirectCast(grvData.FooterRow.FindControl("txtNewName"), TextBox)
Dim cboStatus As DropDownList = DirectCast(grvData.FooterRow.FindControl("ddlNewStatus"), DropDownList)
lblError.Text = String.Empty
Try
If String.IsNullOrEmpty(txtName.Text) Then
Return
End If
Dim pSource As New TblPetitionSource
pSource.Name = txtName.Text
pSource.Lastupdate = Now.ToString("yyyy/MM/dd HH:mm:ss")
pSource.StatusFlag = 1
pSource.UpdateBy = "ADMIN"
Dim db As New ProcuracyDataContext
Dim lst = (From p In db.TblPetitionSource Where p.Name = txtName.Text Select p).ToList()
If lst.Count > 0 Then
HttpContext.Current.Response.Write("<script>alert('Đã tồn tại nguồn đơn . Bạn không thể tạo thêm được nguồn đơn này nữa')</script>")
Return
End If
db.TblPetitionSource.InsertOnSubmit(pSource)
db.SubmitChanges()
BindData()
Catch ex As Exception
lblError.Text = ex.Message
End Try
End If
Catch ex As Exception
lblError.Text = "Lỗi không " & commandNameType & " được bản ghi này <br />" & ex.Message
End Try
End Sub
This is my code using for MergeCells:
Private Sub grvData_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grvData.RowDataBound
Try
If e.Row.RowType = DataControlRowType.Header Then
e.Row.Cells.RemoveAt(e.Row.Cells.Count - 1)
e.Row.Cells(e.Row.Cells.Count - 1).ColumnSpan = 2
e.Row.Cells(e.Row.Cells.Count - 1).Text = "Thao tác"
End If
If e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells.RemoveAt(e.Row.Cells.Count - 1)
e.Row.Cells.RemoveAt(e.Row.Cells.Count - 1)
e.Row.Cells.RemoveAt(e.Row.Cells.Count - 1)
e.Row.Cells(e.Row.Cells.Count - 1).ColumnSpan = 4
End If
Catch ex As Exception
Throw New Exception(ex.Message, ex)
End Try
End Sub
Could you see more detail at these files:
https://drive.google.com/open?id=0B6NcrBkoDTV5TV9QcFFUWUpnTFk
and the form after click button:
Web form after click button
Thanks you so much!

set field to a value after DetailView is updated

After the DetailsView is updated and clicked the Update Command button on the DetailView; I want to set one of the fields to “Complete”. What am I doing wrong here? Pls. help.
here is my code behind:
Protected Sub Test(sender As Object, e As System.Web.UI.WebControls.DetailsViewUpdatedEventArgs) Handles DetailsView1.ItemUpdated
If IsPostBack Then
Dim TextBox7 As TextBox = TryCast(DetailsView1.Rows(0).Cells(0).FindControl("TextBox7"), TextBox)
TextBox7.Text = "Complete"
End If
End Sub
I have used this method and got it to work.
Protected Sub PageDetailsView_ItemCommand(sender As Object, e As DetailsViewCommandEventArgs)
If Me.PageDetailsView.DefaultMode = DetailsViewMode.[ReadOnly] Then
If e.CommandName.Equals("GenerateModifiedDate", StringComparison.CurrentCultureIgnoreCase) Then
Dim modifiedDateLabel As Label = TryCast(Me.PageDetailsView.FindControl("ModifiedDateLabel"), Label)
modifiedDateLabel.Text = DateTime.Now.ToString()
End If
Else
If e.CommandName.Equals("GenerateModifiedDate", StringComparison.CurrentCultureIgnoreCase) Then
Dim modifiedDateTextbox As TextBox = TryCast(Me.PageDetailsView.FindControl("ModifiedDateTextbox"), TextBox)
modifiedDateTextbox.Text = DateTime.Now.ToString()
End If
End If
End Sub

This code will display selected checkboxes text in textbox as 1,2,3,4,5,6,7,8,9

This code will display selected checkboxes Text in textbox as in the order i checked it 1,2,3,4,5,6,7,8,9
But it will not display selected checkboxes Text in textbox after 9
Partial Class _45seater_WebUserControl
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim str As String = Nothing
Dim id As String = Nothing
Dim ch As String = Nothing
For Each ctrl As Control In Panel1.Controls
If ctrl.GetType() Is GetType(CheckBox) Then
Dim chk As CheckBox = ctrl
UpdatePanel1.FindControl("chk")
If chk.Checked = True Then
If TextBox1.Text = "" Then
TextBox1.Text = chk.Text
Else
Dim SearchString As String = chk.Text
id = TextBox1.Text
If id.Contains(SearchString) <> -1 Then
TextBox1.Text = TextBox1.Text + "," + chk.Text
Else
End If
End If
Else
Dim SearchString As String = chk.Text
id = TextBox1.Text
If id.Contains(SearchString) <> -1 Then
Else
id = RemoveSubString(id, chk.Text)
TextBox1.Text = id
End If
End If
End If
Next
End Sub
Private Function RemoveSubString(ByVal stringvalue As String, ByVal stringremove As String) As String
Dim pos As Integer = stringvalue.IndexOf(stringremove)
If pos > 0 Then
Return stringvalue.Remove(pos - 1, stringremove.Length + 1)
ElseIf pos = 0 Then
If stringvalue.Contains(",") <> -1 Then
Return stringvalue.Remove(pos, stringremove.Length)
Else
Return stringvalue.Remove(pos, stringremove.Length + 1)
End If
End If
Return stringvalue
End Function
End Class
can any body show after chekbox10,checkbox11,checkbox12 in text box as 10,11,12 ......so on using this code
I really don't understand that requirement but i think the only thing the function should do is to print the ID's of all checked CheckBoxes in a TextBox.
Why do you complicated it, this works too:
TextBox1.Text = String.Empty
For Each control As Control In form1.Controls
If TypeOf control Is CheckBox AndAlso DirectCast(control, CheckBox).Checked Then
TextBox1.Text &= control.ID & ","
End If
Next
'remove last comma'
If TextBox1.Text.Length <> 0 Then TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1)
According to your new informations about the order, try this:
Protected Sub CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim chk As CheckBox = DirectCast(sender, CheckBox)
Dim separator As Char = ","c
If TextBox1.Text.Length <> 0 Then
Dim allIIDs As New List(Of String)(TextBox1.Text.Split(separator))
allIIDs.Remove(chk.ID)
If chk.Checked Then
allIIDs.Add(chk.ID)
End If
TextBox1.Text = String.Empty
For Each id As String In allIIDs
TextBox1.Text &= id & separator
Next
TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1)
Else
TextBox1.Text = chk.ID
End If
End Sub
To register the CheckedChanged-Event on the CheckBoxes you have to add following on aspx for every Checkbox:
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="CheckedChanged" />
or if you are lazy and want to do that in Codebehind, add following in Page_Init:
Private Sub WebForm1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For Each control As Control In Me.form1.Controls
If TypeOf control Is CheckBox Then
Dim chk As CheckBox = DirectCast(control, CheckBox)
chk.AutoPostBack = True
AddHandler chk.CheckedChanged, AddressOf CheckedChanged
End If
Next
End Sub

Resources