Adding dynamic links using NavigateURL on ASP.NET (VB) - asp.net

I Have this code in my page, and I want that every NavigateUrl display another page like :
simple.aspx?id=1, simple.aspx?id=2, ...
Where id = c
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim c As Integer = 0
While c < 5
Dim Label1 As New Label()
Dim ltr As New Literal()
Dim link As New HyperLink()
link.NavigateUrl = "simple.aspx"
link.BackColor = Drawing.Color.Aqua
Label1.Text = c.ToString()
ltr.Text = "<br/>"
PlaceHolder1.Controls.Add(Label1)
PlaceHolder1.Controls.Add(link)
PlaceHolder1.Controls.Add(ltr)
c += 1
End While
End Sub
Thanks.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim c As Integer = 0
While c < 5
Dim Label1 As New Label()
Dim ltr As New Literal()
Dim link As New HyperLink()
link.NavigateUrl = "simple.aspx?id=" & c.tostring
link.BackColor = Drawing.Color.Aqua
Label1.Text = c.ToString()
ltr.Text = "<br/>"
PlaceHolder1.Controls.Add(Label1)
PlaceHolder1.Controls.Add(link)
PlaceHolder1.Controls.Add(ltr)
c += 1
End While
End Sub

Related

ASP.NET Click event not firing in buttons inside a customized Panel control

I'm trying to learn ASP.NET with VB.
I've created a customized Panel control with below code.
Public Class RowPanel
Inherits Panel
Private WithEvents pnlMain As New Panel
Private btnRack() As Button
Public Sub New(Optional ByRef NoOfRacks As Integer = 8)
createPanel(NoOfRacks)
End Sub
Public Sub createPanel(ByVal NoOfRacks As Integer)
With pnlMain
.Height = 600
.Width = 200
.BackColor = Drawing.Color.BurlyWood
.BorderStyle = WebControls.BorderStyle.Dashed
End With
ReDim btnRack(NoOfRacks - 1)
For i = 1 To NoOfRacks
btnRack(i - 1) = New Button
With btnRack(i - 1)
.Width = pnlMain.Width.Value - 20
.ID = "Rack" & Guid.NewGuid().ToString("N")
.Text = "Rack" & i
'AddHandler .Click, AddressOf rackbutton_Click
End With
Next
Dim bt As Button
For Each bt In btnRack
AddHandler bt.Click, AddressOf rackbutton_Click
Next
For b As Integer = 0 To btnRack.GetUpperBound(0)
Dim brk As New LiteralControl("</br>")
pnlMain.Controls.Add(btnRack(b))
pnlMain.HorizontalAlign = WebControls.HorizontalAlign.Center
pnlMain.Controls.Add(brk)
Next
Me.Controls.Add(pnlMain)
End Sub
Protected Sub rackbutton_Click(sender As Object, e As EventArgs)
Dim clickedbtn As Button
clickedbtn = CType(sender, Button)
MsgBox(clickedbtn.ID.ToString)
End Sub
End Class
My problem is the rackbutton_Click event is not firing when I clicked a button in the panel.
Main webform code:
Public Class WebForm1
Inherits System.Web.UI.Page
Private dynamicPnlIDs As New List(Of String)
Const _MaxRacks As Integer = 10
Dim rck As Integer = 1
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Session("dynamicBtnIDs") IsNot Nothing Then
dynamicPnlIDs = DirectCast(Session("dynamicBtnIDs"), List(Of String))
For Each pnlID As String In dynamicPnlIDs
Dim rk As Integer
rk = Right(pnlID, pnlID.Length - (1 + pnlID.IndexOf(":"c)))
Dim pnl As New RowPanel(rk)
Dim tblCell As New TableCell
pnl.ID = Right(pnlID, pnlID.IndexOf(":"c) - 1).ToString()
tblCell.Controls.Add(pnl)
Table1.Rows(0).Controls.Add(tblCell)
Next
Else
dynamicPnlIDs = New List(Of String)()
End If
End Sub
Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
Session("dynamicBtnIDs") = dynamicPnlIDs
End Sub
Protected Sub addRow_Click(sender As Object, e As EventArgs) Handles addRow.Click
rck = TextBox1.Text
If Not (rck > 0 And rck <= _MaxRacks) Then
MsgBox("Invalid Entry!" & vbCrLf & "Please enter a value between 1 &" & _MaxRacks & ".", vbOKOnly, "Error")
TextBox1.BackColor = Drawing.Color.PaleVioletRed
Exit Sub
Else
TextBox1.BackColor = System.Drawing.ColorTranslator.FromHtml("#CDCDCD")
End If
Dim pnl As New RowPanel(rck)
Dim tblCell As New TableCell
pnl.ID = "pnl" & Guid.NewGuid().ToString("N")
tblCell.Controls.Add(pnl)
Table1.Rows(0).Controls.Add(tblCell)
dynamicPnlIDs.Add(pnl.ID & ":" & rck.ToString())
End Sub
End Class
Please help me.
(This is my first post, any advise is welcome)
Remove or comment out the following line and it should start working.
'.ID = "Rack" & Guid.NewGuid().ToString("N")
You can replace it with something meaningful, if you want to.
e.g.
.ID = pnlMain.UniqueID & "_Rack" & i.ToString

Access Multiple Dynamic Dropdownlists selected Value - ASP.Net

I am adding multiple dynamic dropdownlists to my form.
I'm wanting to access the selected values of the dropdownlists on click of a button.
Private pnlDropDownList As Panel
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreInit
'Create a Dynamic Panel
pnlDropDownList = New Panel()
pnlDropDownList.ID = "pnlDropDownList"
pnlDropDownList.BorderWidth = 1
pnlDropDownList.Width = 300
Me.form1.Controls.Add(pnlDropDownList)
'Create a LinkDynamic Button to Add TextBoxes
Dim btnAddDdl As New Button
btnAddDdl.ID = "btnAddDdl"
btnAddDdl.Text = "Add DropDownList"
AddHandler btnAddDdl.Click, AddressOf btnAdd_Click
Me.form1.Controls.Add(btnAddDdl)
'Recreate Controls
RecreateControls("ddlDynamic", "DropDownList")
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim cnt As Integer = FindOccurence("ddlDynamic")
CreateDropDownList("ddlDynamic-" & Convert.ToString(cnt + 1))
End Sub
Private Function FindOccurence(ByVal substr As String) As Integer
Dim reqstr As String = Request.Form.ToString()
Return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length)
End Function
Private Sub RecreateControls(ByVal ctrlPrefix As String, ByVal ctrlType As String)
Dim ctrls As String() = Request.Form.ToString().Split("&"c)
Dim cnt As Integer = FindOccurence(ctrlPrefix)
If cnt > 0 Then
For k As Integer = 1 To cnt
For i As Integer = 0 To ctrls.Length - 1
If ctrls(i).Contains((ctrlPrefix & "-") + k.ToString()) AndAlso Not ctrls(i).Contains("EVENTTARGET") Then
Dim ctrlID As String = ctrls(i).Split("="c)(0)
If ctrlType = "DropDownList" Then
CreateDropDownList(ctrlID)
End If
Exit For
End If
Next
Next
End If
End Sub
Private Sub CreateDropDownList(ByVal ID As String)
Dim ddl As New DropDownList()
ddl.ID = ID
ddl.DataSource = Me.odsNames
ddl.DataTextField = "Name"
ddl.DataValueField = "ID"
ddl.DataBind()
ddl.Items.Insert(0, New ListItem("All", -1))
ddl.SelectedIndex = 0
ddl.AutoPostBack = True
AddHandler ddl.SelectedIndexChanged, AddressOf OnSelectedIndexChanged
pnlDropDownList.Controls.Add(ddl)
Dim lt As New Literal()
lt.Text = "<br />"
pnlDropDownList.Controls.Add(lt)
End Sub
Protected Sub OnSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
'Not used, want to get Values from button click
End Sub
Protected Sub cmdAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdAdd.Click
Dim cnt As Integer = FindOccurence("ddlDynamic")
pnlDropDownList.Controls.Remove(pnlDropDownList.FindControl("ddlDynamic-" & Convert.ToString(cnt)))
End Sub
This is where I would like to check all dynamic dropdownlists and extract their selected values
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
'' Check All dynamic Dropdownlists and retrieve selected values
End Sub
End Class
Any assistance would be much appreciated. thanks
You could use Linq to get the references of your dynamic DropDowns in the panel:
Dim allDdls = pnlDropDownList.Controls.OfType(Of DropDownList)()
For Each ddl In allDdls
Dim selectedValue = ddl.SelectedValue
Next

How to check a check box automatically on vb.net asp.net?

i have to insert some data value and value like this picture on insert.aspx
And how i show like this to update the data update.aspx
So how to make check box on update.aspx check automatic like on insert.aspx
on Insert.aspx.vb
Protected Sub insertdata()
Dim cls As New connections
cls.openconnections()
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cls.cn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_inserttrainer"
cmd.Parameters.AddWithValue("#id", txtKode.Text)
cmd.Parameters.AddWithValue("#nama", txtnama.Text)
cmd.Parameters.AddWithValue("#status", txtstatus.SelectedValue)
cmd.Parameters.AddWithValue("#alamat", txtalamat.Text)
cmd.Parameters.AddWithValue("#telp", txttel.Text)
cmd.Parameters.AddWithValue("#hp", txthp.Text)
cmd.Parameters.AddWithValue("#email", txtemail.Text)
cmd.ExecuteNonQuery()
cls.closeconnection()
End Sub
Protected Sub savedatamateri()
Dim cbterpilih As Boolean = False
Dim cb As CheckBox = Nothing
Dim n As Integer = 0
Do Until n = gridsecond.Rows.Count
cb = gridsecond.Rows.Item(n).FindControl("chkStatus")
If cb IsNot Nothing AndAlso cb.Checked Then
cbterpilih = True
Dim cls As New connections
cls.openconnections()
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cls.cn
cmd.CommandText = "Insert Into m_trainer_detil (trainer_id, materi_id)"
cmd.CommandText &= "values(#triner, #materi)"
Dim com As HiddenField = CType(gridsecond.Rows(n).FindControl("HiddenField2"), HiddenField)
cmd.Parameters.AddWithValue("#triner", txtKode.Text)
cmd.Parameters.AddWithValue("#materi", com.Value)
cmd.ExecuteNonQuery()
cls.closeconnection()
End If
n += 1
Loop
End Sub
Protected Sub insert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles insert.Click
If txtalamat.Text = "" Then
labelran.Text = "Tolong isi Alamat"
ElseIf txtemail.Text = "" Then
labelran.Text = "Tolong isi Email"
ElseIf txtnama.Text = "" Then
labelran.Text = "Tolong isi Nama"
ElseIf txttel.Text = "" Then
labelran.Text = "Tolong isi Telepon"
ElseIf txthp.Text = "" Then
labelran.Text = "Tolong isi Handphone"
Else
insertdata()
savedatamateri()
listhendle()
End If
End Sub
and for update.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
listhendle()
listmateri()
End If
End Sub
Protected Sub listhendle()
Dim ds As New DataSet
Dim cls As New connections
ds = cls.returndataset("select * from [m_trainer] ")
If ds.Tables(0).Rows.Count = 0 Then
ds.Tables(0).Rows.Add(ds.Tables(0).NewRow)
End If
griddata.DataSource = ds
griddata.DataBind()
End Sub
Protected Sub listmateri()
Dim ds As New DataSet
Dim cls As New connections
ds = cls.returndataset("select * from [m_materi] ")
If ds.Tables(0).Rows.Count = 0 Then
ds.Tables(0).Rows.Add(ds.Tables(0).NewRow)
End If
gridsecond.DataSource = ds
gridsecond.DataBind()
End Sub
Protected Sub griddata_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles griddata.SelectedIndexChanging
Dim kode As HiddenField = CType(griddata.Rows(e.NewSelectedIndex).FindControl("HiddenField1"), HiddenField)
txtKode.Text = kode.Value
txtnama.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(1).Text, " ", "")
txtalamat.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(2).Text, " ", "")
txttel.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(3).Text, " ", "")
txthp.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(4).Text, " ", "")
txtstatus.SelectedValue = Replace(griddata.Rows(e.NewSelectedIndex).Cells(5).Text, " ", "")
txtemail.Text = Replace(griddata.Rows(e.NewSelectedIndex).Cells(6).Text, " ", "")
End Sub
But i don't know how connect materi with database
Thank You
It looks like you are storing the materi_id in the table m_trainer. So it looks like you would need to set up an OnRowDataBound event on your "gridSecond" GridView. Within the OnRowDatabound event get a dataset for the selected trainer_id and if the materi_id exists within that dataset set its checked value as true.

how to calulate the column cells in gridview?

i have grid view with column ..price ...
Sno. Product price ($)
1 Pencil 1
2 Rubber 3
3 sharpner 2
I want to calulate the price column .... means //// i want to calculate the cells in Price column of GridView .....
the reult of price will be shown as 1+3+2 = 6
You could use Datatable's compute function to calculate the sum:
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(2).Text = DirectCast(Me.GridView1.DataSource, DataTable).Compute("SUM(Price)", Nothing).ToString
End If
End Sub
This was my Testdata:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindFooData()
End If
End Sub
Private Sub BindFooData()
Dim tblFoo As New DataTable("Foo")
tblFoo.Columns.Add(New DataColumn("ID", GetType(Int32)))
tblFoo.Columns.Add(New DataColumn("Product", GetType(String)))
tblFoo.Columns.Add(New DataColumn("Price", GetType(Double)))
Dim drProduct As DataRow = tblFoo.NewRow
drProduct("ID") = 1
drProduct("Product") = "Pencil"
drProduct("Price") = 1
tblFoo.Rows.Add(drProduct)
drProduct = tblFoo.NewRow
drProduct("ID") = 2
drProduct("Product") = "Rubber"
drProduct("Price") = 3
tblFoo.Rows.Add(drProduct)
drProduct = tblFoo.NewRow
drProduct("ID") = 3
drProduct("Product") = "sharpner"
drProduct("Price") = 2
tblFoo.Rows.Add(drProduct)
Me.GridView1.DataSource = tblFoo
Me.GridView1.AutoGenerateColumns = True
Me.GridView1.ShowFooter = True
Me.GridView1.DataBind()
End Sub
Or you could calculate it manually:
Private AllPrices As New List(Of Double)
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim price As Double = DirectCast(DirectCast(e.Row.DataItem, DataRowView)("Price"), Double)
AllPrices.Add(price)
ElseIf e.Row.RowType = DataControlRowType.Footer Then
Dim TotalPrice As Double
Dim TotalUnitPriceText As New System.Text.StringBuilder
For Each price As Double In AllPrices
TotalPrice += price
TotalUnitPriceText.Append(price).Append("+")
Next
If TotalUnitPriceText.Length <> 0 Then
TotalUnitPriceText.Length -= 1
TotalUnitPriceText.Append(" = ")
End If
e.Row.Cells(1).Text = TotalUnitPriceText.ToString
e.Row.Cells(2).Text = TotalPrice.ToString
End If
End Sub
Last but not least you could calculate it with your sql-query with SUM.

Dynamic gridview columns event problem

i have a GridView (selectable) in which I want to generate a dynamic GridView in a new row BELOW the selected row.
I can add the row and gridview dynamically in the Gridview1 PreRender event. I need to use this event because:
_OnDataBound is not called on every postback (same for _OnRowDataBound)
_OnInit is not possible because the 'Inner table' for the Gridview is added after Init
_OnLoad is not possible because the 'selected' row is not selected yet.
I can add the columns to the dynamic GridView based on my ITemplate class.
But now the button events won't fire.... Any suggestions?
The dynamic adding of the gridview:
Private Sub GridView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PreRender
Dim g As GridView = sender
g.DataBind()
If g.SelectedRow IsNot Nothing AndAlso g.Controls.Count > 0 Then
Dim t As Table = g.Controls(0)
Dim r As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
Dim c As New TableCell
Dim visibleColumnCount As Integer = 0
For Each d As DataControlField In g.Columns
If d.Visible Then
visibleColumnCount += 1
End If
Next
c.ColumnSpan = visibleColumnCount
Dim ph As New PlaceHolder
ph.Controls.Add(CreateStockGrid(g.SelectedDataKey.Value))
c.Controls.Add(ph)
r.Cells.Add(c)
t.Rows.AddAt(g.SelectedRow.RowIndex + 2, r)
End If
End Sub
Private Function CreateStockGrid(ByVal PnmAutoKey As String) As GridView
Dim col As Interfaces.esColumnMetadata
Dim coll As New BLL.ViewStmCollection
Dim entity As New BLL.ViewStm
Dim query As BLL.ViewStmQuery = coll.Query
Me._gridStock.AutoGenerateColumns = False
Dim buttonf As New TemplateField()
buttonf.ItemTemplate = New QuantityTemplateField(ListItemType.Item, "", "Button")
buttonf.HeaderTemplate = New QuantityTemplateField(ListItemType.Header, "", "Button")
buttonf.EditItemTemplate = New QuantityTemplateField(ListItemType.EditItem, "", "Button")
Me._gridStock.Columns.Add(buttonf)
For Each col In coll.es.Meta.Columns
Dim headerf As New QuantityTemplateField(ListItemType.Header, col.PropertyName, col.Type.Name)
Dim itemf As New QuantityTemplateField(ListItemType.Item, col.PropertyName, col.Type.Name)
Dim editf As New QuantityTemplateField(ListItemType.EditItem, col.PropertyName, col.Type.Name)
Dim f As New TemplateField()
f.HeaderTemplate = headerf
f.ItemTemplate = itemf
f.EditItemTemplate = editf
Me._gridStock.Columns.Add(f)
Next
query.Where(query.PnmAutoKey.Equal(PnmAutoKey))
coll.LoadAll()
Me._gridStock.ID = "gvChild"
Me._gridStock.DataSource = coll
AddHandler Me._gridStock.RowCommand, AddressOf Me.gv_RowCommand
Me._gridStock.DataBind()
Return Me._gridStock
End Function
The ITemplate class:
Public Class QuantityTemplateField : Implements ITemplate
Private _itemType As ListItemType
Private _fieldName As String
Private _infoType As String
Public Sub New(ByVal ItemType As ListItemType, ByVal FieldName As String, ByVal InfoType As String)
Me._itemType = ItemType
Me._fieldName = FieldName
Me._infoType = InfoType
End Sub
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Select Case Me._itemType
Case ListItemType.Header
Dim l As New Literal
l.Text = "<b>" & Me._fieldName & "</b>"
container.Controls.Add(l)
Case ListItemType.Item
Select Case Me._infoType
Case "Button"
Dim ib As New Button()
Dim eb As New Button()
ib.ID = "InsertButton"
eb.ID = "EditButton"
ib.Text = "Insert"
eb.Text = "Edit"
ib.CommandName = "Edit"
eb.CommandName = "Edit"
AddHandler ib.Click, AddressOf Me.InsertButton_OnClick
AddHandler eb.Click, AddressOf Me.EditButton_OnClick
container.Controls.Add(ib)
container.Controls.Add(eb)
Case Else
Dim l As New Label
l.ID = Me._fieldName
l.Text = ""
AddHandler l.DataBinding, AddressOf Me.OnDataBinding
container.Controls.Add(l)
End Select
Case ListItemType.EditItem
Select Case Me._infoType
Case "Button"
Dim b As New Button
b.ID = "UpdateButton"
b.Text = "Update"
b.CommandName = "Update"
b.OnClientClick = "return confirm('Sure?')"
container.Controls.Add(b)
Case Else
Dim t As New TextBox
t.ID = Me._fieldName
AddHandler t.DataBinding, AddressOf Me.OnDataBinding
container.Controls.Add(t)
End Select
End Select
End Sub
Private Sub InsertButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("insert click")
End Sub
Private Sub EditButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("edit click")
End Sub
Private Sub OnDataBinding(ByVal sender As Object, ByVal e As EventArgs)
Dim boundValue As Object = Nothing
Dim ctrl As Control = sender
Dim dataItemContainer As IDataItemContainer = ctrl.NamingContainer
boundValue = DataBinder.Eval(dataItemContainer.DataItem, Me._fieldName)
Select Case Me._itemType
Case ListItemType.Item
Dim fieldLiteral As Label = sender
fieldLiteral.Text = boundValue.ToString()
Case ListItemType.EditItem
Dim fieldTextbox As TextBox = sender
fieldTextbox.Text = boundValue.ToString()
End Select
End Sub
End Class
Oh my oh my, I went to MVC, anybody reading this question should do the same :)

Resources