Access Multiple Dynamic Dropdownlists selected Value - ASP.Net - 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

Related

How can I create a self-incrementing column for a DataGridView?

I need to add a self-incrementing column to a DataGridView. Every time a row is added to the grid I want to increment the No column.
My Form_Load code:
Private Sub SAP_OrdenVenta_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.ColumnCount = 6
DataGridView1.Columns(0).Name = ("No")
DataGridView1.Columns(1).Name = ("NoArticulo")
DataGridView1.Columns(2).Name = ("Descripcion")
DataGridView1.Columns(3).Name = ("Cantidad")
DataGridView1.Columns(4).Name = ("Precio")
DataGridView1.Columns(5).Name = ("Total")
End Sub
The DataGridView Button Click event for the add button:
Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click
Dim articulo, cantidad As Integer
Dim precio, total1 As Double
Dim i As Integer = 0
articulo = txtArticulo.Text.Trim()
cantidad = txtCantidad.Text.Trim()
precio = txtPrecio.Text.Trim()
total1 = txtPrecio.Text.Trim()
'Agrego Linea a DataGridView
Dim row As String() = New String() {1, articulo, "No disponible", cantidad, precio, total1}
DataGridView1.Rows.Add(row)
End Sub
How can I make this work?
Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click
Dim LastIndex As Integer = DataGridView1.Rows.Count - 1
Dim LastNo As Integer = Integer.Parse(DataGridView1.Rows(LastIndex).Cells(0).Value)
Dim NewNo As String = (LastNo + 1).ToString()
Dim row As String() = New String() {NewNo, txtArticulo.Text, "No disponible", txtCantidad.Text, txtPrecio.Text, txtPrecio.Text}
DataGridView1.Rows.Add(row)
End Sub
Take note, however: if this view is loaded from a real database table, you almost always want to rely on your database's ability to generate ID values. Otherwise, this is a huge race condition waiting to blow up.

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

Repeater forgetting how many items to display when next button is clicked

I have a repeater list that displays results in sets of 15. When you click the next button it shows the next 15 and so on.
I have added some buttons that will then filter the display to show the results in sets of 10, 25, 50.
When you click these it does work but when you click the next button it resets the display value to 15.
Below is the chunk of script:
Public Property CurrentPage() As Integer
Get
' look for current page in ViewState
Dim o As Object = Me.ViewState("_CurrentPage")
If o Is Nothing Then
Return 0
Else
' default to showing the first page
Return CInt(o)
End If
End Get
Set
Me.ViewState("_CurrentPage") = value
End Set
End Property
Protected Sub ItemsGet()
Dim pageSize As Integer = 15
ItemsGet(pageSize)
End Sub
Private Sub ItemsGet(ByVal pageSize As Integer)
' Read sample item info from XML document into a DataSet
' Populate the repeater control with the Items DataSet
Dim objPds As New PagedDataSource()
Dim selectedCategory As String = ddlCategory.SelectedValue.ToString()
Dim selectedCategoryIndex As Integer = ddlCategory.SelectedIndex
Dim selectedCategoryMonth As String = ddlCategoryMonth.SelectedValue.ToString()
Dim selectedCategoryMonthIndex As Integer = ddlCategoryMonth.SelectedIndex
Dim query = GetXmlDataSet()
If (Not String.IsNullOrEmpty(selectedCategory) And selectedCategoryIndex > 0) Then
query = query.Where(Function(x) x("SCategoryName") = selectedCategory)
End If
If (Not String.IsNullOrEmpty(selectedCategoryMonth) And selectedCategoryMonthIndex > 0) Then
query = query.Where(Function(x) x("SCategoryMonth") = selectedCategoryMonth)
End If
If (query.Count() > 0) Then
objPds.DataSource = query.CopyToDataTable().Rows
objPds.AllowPaging = True
objPds.PageSize = pageSize
objPds.CurrentPageIndex = CurrentPage
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " + objPds.PageCount.ToString()
' Disable Prev or Next buttons if necessary
cmdPrev.Enabled = Not objPds.IsFirstPage
cmdNext.Enabled = Not objPds.IsLastPage
Display10.Enabled = True
Display25.Enabled = True
Display50.Enabled = True
categories.DataSource = objPds
categories.DataBind()
Else
CurrentPage = 0
categories.Controls.Clear()
cmdPrev.Enabled = False
cmdNext.Enabled = False
Display10.Enabled = False
Display25.Enabled = False
Display50.Enabled = False
lblCurrentPage.Text = "Page: 0 of 0 "
End If
End Sub
Private Sub Display10_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim pageSize As Integer = 10
CurrentPage = 0
ItemsGet(pageSize)
End Sub
Private Sub Display25_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim pageSize As Integer = 25
CurrentPage = 0
ItemsGet(pageSize)
End Sub
Private Sub Display50_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim pageSize As Integer = 50
CurrentPage = 0
ItemsGet(pageSize)
End Sub
Private Sub cmdPrev_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Set viewstate variable to the previous page
CurrentPage -= 1
' Reload control
ItemsGet()
End Sub
Private Sub cmdNext_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Set viewstate variable to the next page
CurrentPage += 1
' Reload control
ItemsGet()
End Sub
Protected Sub ddlCategory_SelectedIndexChanged1(ByVal sender As Object, ByVal e As System.EventArgs)
CurrentPage = 0
ItemsGet()
End Sub
Protected Sub ddlCategoryMonth_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
CurrentPage = 0
ItemsGet()
End Sub
You need to 'persist' the number of items to get.
There are a few ways to do this....
Re-factor PageSize into a property with its backing kept in the viewstate, remember to initialise with appropriate default values.
Change the ItemsGet sub to use the property instead.
My vb is rusty!
Public Property PageSize() As Integer
Get
If Me.ViewState("PageSize") Is Nothing Then
Me.ViewState("PageSize") = 15
End If
Return CInt( Me.ViewState("PageSize") )
End Get
Set
Me.ViewState("PageSize") = value
End Set
End Property

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