Trying to attach a handler to linkbutton - asp.net

Hello I am trying to get this Pager working. I am having some trouble adding the event handler to pagerCommand event. What am i doing wrong? I can attach the handler to the dropdown with no problem, but the link is having an issue. Any guidance will be appreciated. Thanks
Public Class DataPagerDDL
Inherits DataPager
Protected Overrides Sub OnInit(ByVal e As EventArgs)
Me.CreateDefaultPagerFields()
MyBase.OnInit(e)
End Sub
Protected Sub CreateDefaultPagerFields()
'add custom template
Dim templateField As TemplatePagerField = New TemplatePagerField
templateField.PagerTemplate = New CustomTemplate
'add previous/next page template
Fields.Add(templateField)
End Sub
Public Sub cmbPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim cmbPage As DropDownList = CType(sender, DropDownList)
SetPageProperties((cmbPage.SelectedIndex * MaximumRows), MaximumRows, True)
End Sub
Public Sub cmb_PagerCommand(ByVal sender As Object, ByVal e As DataPagerCommandEventArgs)
' Check which button raised the event
Select Case e.CommandName
Case "Next"
Dim newIndex As Integer = e.Item.Pager.StartRowIndex + e.Item.Pager.PageSize
If newIndex <= e.TotalRowCount Then
e.NewStartRowIndex = newIndex
e.NewMaximumRows = e.Item.Pager.MaximumRows
End If
Case "Previous"
e.NewStartRowIndex = e.Item.Pager.StartRowIndex - e.Item.Pager.PageSize
e.NewMaximumRows = e.Item.Pager.MaximumRows
Case "First"
e.NewStartRowIndex = 0
e.NewMaximumRows = e.Item.Pager.MaximumRows
Case "Last"
Dim newIndex As Integer = e.Item.Pager.StartRowIndex + e.Item.Pager.PageSize
If newIndex <= e.TotalRowCount Then
e.NewStartRowIndex = newIndex
e.NewMaximumRows = e.Item.Pager.MaximumRows
End If
End Select
End Sub
End Class
Public Class CustomTemplate
Implements System.Web.UI.ITemplate
Dim PageCount As Integer
Dim CurrentPage As Integer
Dim PageSize As Integer
Dim TotalRowCount As Integer
Dim MaximumRows As Integer
Dim StartRowIndex As Integer
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Dim caller As DataPagerFieldItem = CType(container, DataPagerFieldItem)
Dim pager As DataPagerDDL = CType(caller.Parent, DataPagerDDL)
PageSize = pager.PageSize
TotalRowCount = pager.TotalRowCount
MaximumRows = pager.MaximumRows
PageCount = (TotalRowCount / MaximumRows)
If ((pager.TotalRowCount Mod pager.MaximumRows) > 0) Then
PageCount = (PageCount + 1)
End If
Dim link As LinkButton = New LinkButton
'first Link
link.Text = "<< First "
link.CommandName = "Page"
link.CommandArgument = "First"
link.ID = "lnkFirst"
link.Enabled = StartRowIndex > 0
container.Controls.Add(link)
'prev link
link = New LinkButton
link.Text = "< Prev "
link.CommandName = "Page"
link.CommandArgument = "Previous"
link.ID = "lnkPrev"
link.Enabled = StartRowIndex > 0
container.Controls.Add(link)
CurrentPage = ((StartRowIndex / MaximumRows) + 1)
Dim cmbPage As DropDownList = New DropDownList
cmbPage.ID = "cmbPage"
cmbPage.AutoPostBack = True
Dim i As Integer = 1
Do While (i <= PageCount)
Dim item As ListItem = New ListItem(i.ToString, i.ToString)
If (i = CurrentPage) Then
item.Selected = True
End If
cmbPage.Items.Add(item)
i = (i + 1)
Loop
AddHandler cmbPage.SelectedIndexChanged, AddressOf pager.cmbPage_SelectedIndexChanged
'add nav buttons
' we just add a Label with 'Page ' Text
container.Controls.Add(PageOf())
' our DropDownList control here.
container.Controls.Add(cmbPage)
' and our Total number of Pages
container.Controls.Add(PageTotal())
'next link
link = New LinkButton
link.Text = "Next > "
link.CommandName = "Page"
link.CommandArgument = "Next"
link.ID = "lnkNext"
link.Enabled = StartRowIndex + PageSize < TotalRowCount
container.Controls.Add(link)
'last link
link = New LinkButton
link.Text = "Last >> "
link.CommandName = "Page"
link.CommandArgument = "Last"
link.ID = "lnkLast"
link.Enabled = StartRowIndex + PageSize < TotalRowCount
'Problem line
AddHandler pager.cmb_PagerCommand, New EventHandler(AddressOf pager.cmb_PagerCommand)
container.Controls.Add(link)
container.Controls.Add(PageInfo(TotalRowCount))
End Sub
Private Function PageOf() As Label
' it is just a label
Dim lbl As New Label()
lbl.Text = " Page "
Return lbl
End Function
Private Function PageTotal() As Label
' a label of GridView's Page Count
Dim lbl As New Label()
lbl.Text = String.Format(" of {0} ", PageCount)
Return lbl
End Function
Private Function PageInfo(ByVal rowCount As Integer) As Label
' create a label that will display the current Record you're in
Dim label As New Label()
Dim currentPageFirstRow As Integer = ((CurrentPage * PageSize) + 1)
Dim currentPageLastRow As Integer = 0
Dim lastPageRemainder As Integer = rowCount Mod PageSize
currentPageLastRow = IIf((PageCount = CurrentPage + 1), (currentPageFirstRow + lastPageRemainder - 1), (currentPageFirstRow + PageSize - 1))
label.Text = [String].Format("Record {0} to {1} of {2}", currentPageFirstRow, currentPageLastRow, rowCount)
Return label
End Function
End Class
DataPager.png
This is what I have for my gridview, I am trying to replicate the functionality in a free standing pager. A little stumped at the moment

Try replacing the following line of code
AddHandler pager.cmb_PagerCommand, New EventHandler(AddressOf pager.cmb_PagerCommand)
with
AddHandler link.Command, AddressOf pager.cmb_PagerCommand

Related

GridView template field events

I have added Checkbox and Radio buttons as column values to the GridView in runtime.
Now, i am unable to fire Checkbox_CheckedChanged event upon Checkbox.checked
Any suggestions on how to call event ? Below is the Grid i implemented.
Below is the source code:
1) Grid Init
Dim COUNT As Integer = 0
For i As Integer = 0 To ListHeaderDataFieldArray.Count - 1
If ListHeaderDataFieldArray(i) = Me.CRMSignCond Then
Dim TemplateCol As New TemplateField
TemplateCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center
TemplateCol.ItemStyle.Width = New Unit(RowChildWidth)
TemplateCol.HeaderText = ListHeaderTextArray(i)
TemplateCol.ItemTemplate = New GridViewTemplate(DataControlRowType.DataRow, ListHeaderDataFieldArray(i))
GridviewChild.Columns.Add(TemplateCol)
Else
If ListHeaderTextArray(i) = "Target Sign" Then
Dim colItem As TemplateField = New TemplateField
colItem.HeaderText = ListHeaderTextArray(i)
'colItem.DataField = ListHeaderDataFieldArray(i)
colItem.SortExpression = ListHeaderDataFieldArray(i)
colItem.ItemStyle.Width = New Unit(RowChildWidth)
GridviewChild.Columns.Add(colItem)
ElseIf ListHeaderTextArray(i) = "Consolidate" Then
Dim colItem As TemplateField = New TemplateField
colItem.HeaderText = ListHeaderTextArray(i)
'colItem.DataField = ListHeaderDataFieldArray(i)
colItem.SortExpression = ListHeaderDataFieldArray(i)
colItem.ItemStyle.Width = New Unit(RowChildWidth)
GridviewChild.Columns.Add(colItem)
ElseIf ListHeaderTextArray(i) = "Signing Group" Then
Dim colItem As TemplateField = New TemplateField
colItem.HeaderText = ListHeaderTextArray(i)
'colItem.DataField = ListHeaderDataFieldArray(i)
colItem.SortExpression = ListHeaderDataFieldArray(i)
colItem.ItemStyle.Width = New Unit(RowChildWidth)
GridviewChild.Columns.Add(colItem)
Else
Dim colItem As BoundField = New BoundField
colItem.HeaderText = ListHeaderTextArray(i)
colItem.DataField = ListHeaderDataFieldArray(i)
colItem.SortExpression = ListHeaderDataFieldArray(i)
colItem.ItemStyle.Width = New Unit(RowChildWidth)
GridviewChild.Columns.Add(colItem)
End If
End If
2) Adding Controls to the GridView Columns in "RowDataBound" event.
Protected Sub GridviewChild_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridviewChild.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow AndAlso Not String.IsNullOrEmpty(CRMSignCond) Then
Dim s As String = ""
Dim lbValue As Label = DirectCast(e.Row.Cells(5).FindControl("lbValue"), Label)
e.Row.Cells(5).Attributes.Add("onmousemove", "Show('" + lbValue.Text + "')")
e.Row.Cells(5).Attributes.Add("onmouseout", "this.style.backgroundColor=this.oldcolor;Hide();")
End If
Dim cbTargetSign As New CheckBox
Dim rbConsolidate As New RadioButton
Dim tbSignGrp As New TextBox
cbTargetSign.ID = "chkSelect"
cbTargetSign.AutoPostBack = True
rbConsolidate.ID = "rbConsolidate"
tbSignGrp.ID = "tbConsolidate"
tbSignGrp.Width = 25
If Not e.Row.RowIndex = -1 Then
e.Row.Cells(6).Controls.Add(cbTargetSign)
e.Row.Cells(4).Controls.Add(tbSignGrp)
For i As Integer = 0 To 1
rbConsolidate = New RadioButton()
If i = 0 Then
rbConsolidate.Text = "YES"
Else
rbConsolidate.Text = "NO"
End If
'ii.Location = New Point(20, tt)
'ii.Tag = fileArray(i)
'tt = tt + 20
rbConsolidate.GroupName = "Consolidate"
e.Row.Cells(7).Controls.Add(rbConsolidate)
Next
End If
End Sub
Regards,
VK
You are adding and binding events programmatically in code behind and adding them to the GridView. And since dynamic Controls need to be recreated on every time the page is loaded to function properly, you should make sure the RowDataBound event is triggered on every Page Load, and that includes a PostBack.
So I'm guessing you do this (like you would normally):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
GridView1.DataSource = mySource
GridView1.DataBind
End If
End Sub
Change it to
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
GridView1.DataSource = mySource
GridView1.DataBind
End Sub

How do I get the value of a multiple dynamically generated dropdownlist?

I'm doing a small website for school and I got stuck on this problem. How can I get the value of each dropdownlist? The dropdownlist are dynamically generated by code. I did the same with the textboxes and it works perfectly, but with the values of the dropdownlists doesn't work, I mean, I don't get the values back. What should I do?
Partial Class Opties
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim aantalMensen As Integer = CInt(Session("aantalVolwassenen")) + CInt(Session("aantalKinderen")) + CInt(Session("aantalBabys"))
Session("aantalMensen") = CStr(aantalMensen)
For x As Integer = 1 To aantalMensen
'Passagiers info
Dim aanhef As New DropDownList()
Dim aanhefSelectie As ListItem
aanhefSelectie = New ListItem("Dhr.", "Dhr.")
aanhef.Items.Add(aanhefSelectie)
aanhefSelectie = New ListItem("Mevr.", "Mevr.")
aanhef.Items.Add(aanhefSelectie)
Dim voornaam As New TextBox With {.ID = "txtVoornaam" & x}
Dim achternaam As New TextBox With {.ID = "txtAchternaam" & x}
Dim lt As New Literal()
Dim Endlt As New Literal()
Dim space As New Literal()
lt.Text = "<p>Persoon " + CStr(x) + ":"
Endlt.Text = "</p> "
space.Text = "<br />"
gegevensPassagiers.Controls.Add(lt)
gegevensPassagiers.Controls.Add(aanhef)
gegevensPassagiers.Controls.Add(voornaam)
gegevensPassagiers.Controls.Add(achternaam)
gegevensPassagiers.Controls.Add(Endlt)
gegevensPassagiers.Controls.Add(space)
Next
For i As Integer = 1 To aantalMensen
'Bagage DropDownlist
Dim aantalKG As New DropDownList With {.ID = "ddlBagage" & i}
Dim KGselectie As ListItem
KGselectie = New ListItem("Geen", "Geen")
aantalKG.Items.Add(KGselectie)
KGselectie = New ListItem("15kg", "15kg")
aantalKG.Items.Add(KGselectie)
KGselectie = New ListItem("25kg", "25kg")
aantalKG.Items.Add(KGselectie)
KGselectie = New ListItem("35kg", "35kg")
aantalKG.Items.Add(KGselectie)
aantalKG.AutoPostBack = True
Dim lt As New Literal()
Dim Endlt As New Literal()
Dim space As New Literal()
lt.Text = "<p>Persoon " + CStr(i) + ":"
Endlt.Text = "</p> "
space.Text = "<br />"
bagageDIV.Controls.Add(lt)
bagageDIV.Controls.Add(aantalKG)
bagageDIV.Controls.Add(Endlt)
bagageDIV.Controls.Add(space)
Next
Dim index As Integer = 1
If IsPostBack Then
For Each key As String In Request.Form.Keys
If key.Contains("txtVoornaam") Then
Session("Voornaam" & index) = CType(Request.Form(key), String)
index += 1
End If
If key.Contains("txtFamilienaam") Then
Session("Familienaam" & index) = CType(Request.Form(key), String)
index += 1
End If
If key.Contains("ddlBagage") Then
Session("Bagage" & index) = CType(Request.Form(key), String)
index += 1
End If
Next
End If
End Sub
You can use JavaScript for get selected value of dropdownlists.
for example:
var e = document.getElementById("aanhef ");
var Selectedvalue = e.options[e.selectedIndex].value;
Well, after testing some methodes and attributes and other stuff.... I found an easy solution for my problem (also thanks for helping #MaCron).
Here is the code:
For Each aantalKG As DropDownList In bagageDIV.Controls.OfType(Of DropDownList)()
Session("Bagage" & index) = aantalKG.SelectedValue
index += 1
Next

Access Objects Created By Another VB Script

I have a gridview that has textboxes where the user can type text to filter results. The textboxes are created dynamically by an extender below:
Imports Microsoft.VisualBasic
Namespace ControlExtenders
Partial Public Class GridView : Inherits System.Web.UI.WebControls.GridView
' METHOD:: OnLoad
Protected Overrides Sub OnLoad(ByVal e As EventArgs)
MyBase.OnLoad(e)
Me.SetPageSize()
End Sub
Protected Overloads Overrides Sub InitializeRow(ByVal row As GridViewRow, ByVal fields As DataControlField())
MyBase.InitializeRow(row, fields)
If row.RowType = DataControlRowType.Header Then
InitializeHeaderRow(row, fields)
End If
End Sub
Protected Overridable Sub InitializeHeaderRow(ByVal row As GridViewRow, ByVal fields As DataControlField())
' AddGlyph(Me, row)
AddFilters(row, fields)
End Sub
Protected Overridable Sub AddFilters(ByVal headerRow As GridViewRow, ByVal fields As DataControlField())
For i As Integer = 0 To Columns.Count - 1
If Not Columns(i).SortExpression = [String].Empty Then
AddFilter(i, headerRow.Cells(i), fields(i))
End If
Next
End Sub
Dim m_txtFilter As New Hashtable
Dim m_ddlFilter As New Hashtable
Protected Overridable Sub AddFilter(ByVal columnIndex As Integer, ByVal headerCell As TableCell, ByVal field As DataControlField)
If headerCell.Controls.Count = 0 Then
Dim ltlHeaderText As New LiteralControl(headerCell.Text)
headerCell.Controls.Add(ltlHeaderText)
End If
Dim ltlBreak As New LiteralControl("</br>")
headerCell.Controls.Add(ltlBreak)
Dim txtFilter As TextBox = Nothing
If m_txtFilter.Contains(columnIndex) Then
txtFilter = DirectCast(m_txtFilter(columnIndex), TextBox)
Else
txtFilter = New TextBox()
txtFilter.ID = (ID & "_txtFilter") + columnIndex.ToString()
'If field.ItemStyle.Width.Value <> 0.0R Then
' txtFilter.Style.Add(HtmlTextWriterStyle.Width, Convert.ToString(field.ItemStyle.Width.Value) & "px")
'ElseIf field.HeaderStyle.Width.Value <> 0.0R Then
' txtFilter.Style.Add(HtmlTextWriterStyle.Width, Convert.ToString(field.HeaderStyle.Width.Value) & "px")
'Else
'End If
m_txtFilter(columnIndex) = txtFilter
AddHandler txtFilter.TextChanged, AddressOf Me.HandleFilterCommand
Dim js As String
js = "javascript:" & Page.GetPostBackEventReference(Me, "#####buttonPostBack") & ";"
txtFilter.Attributes.Add("onchange", js)
End If
headerCell.Controls.Add(txtFilter)
End Sub
Private Sub HandleFilterCommand(ByVal sender As Object, ByVal e As EventArgs)
'this is required to make sure that unsetting of filter is also handled
Me.RequiresDataBinding = True
' Dim filterArgs As New FilterCommandEventArgs()
'filterArgs.FilterExpression = GetFilterCommand()
Dim filterString = GetFilterCommand()
'Me.OnFilterCommand(filterArgs)
End Sub
Protected Overloads Overrides Sub OnPreRender(ByVal e As EventArgs)
Dim filterCommand As String = GetFilterCommand()
If [String].IsNullOrEmpty(filterCommand) = False Then
ApplyFilterCommand(filterCommand)
End If
MyBase.OnPreRender(e)
End Sub
Public Function IsBoundColumn(ByVal objColumn As DataControlField) As Boolean
If Not objColumn.SortExpression = String.Empty Then
Return True
End If
End Function
Protected Overridable Function GetFilterCommand() As String
' Return ""
Dim filterCommand As String = ""
Dim i As Integer = 0
While i < Me.Columns.Count
If IsBoundColumn(Me.Columns(i)) Then
If Me.HeaderRow Is Nothing Then
i = i + 1
Continue While
End If
Dim headerCell As DataControlFieldHeaderCell = DirectCast(Me.HeaderRow.Cells(i), DataControlFieldHeaderCell)
Dim txtFilter As TextBox = DirectCast(m_txtFilter(i), TextBox)
Dim aColumn As DataControlField
'If Not (TypeOf Me.Columns(i) Is BoundField) Then
' i = i + 1
' Continue While
'End If
aColumn = DirectCast(Me.Columns(i), DataControlField)
If [String].IsNullOrEmpty(txtFilter.Text) Then
i = i + 1
Continue While
End If
Dim TextValue As String = txtFilter.Text
TextValue = TextValue.Replace("'", "''")
If [String].IsNullOrEmpty(filterCommand) Then
' Convert(TimespanColumn, 'System.String'
filterCommand = "Convert(" & aColumn.SortExpression + "," + Chr(39) + "System.String" + Chr(39) + ") like " + Chr(39) + "%" + TextValue + "%" + Chr(39)
Else
filterCommand += " AND " + "Convert(" & aColumn.SortExpression + "," + Chr(39) + "System.String" + Chr(39) + ") like " + Chr(39) + "%" + TextValue + "%" + Chr(39)
End If
End If
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
Return filterCommand
End Function
Protected Overridable Sub ApplyFilterCommand(ByVal filterCommand As String)
Dim dsv As DataSourceView = Me.GetData()
Dim objDataSourceView As ObjectDataSourceView = dsv
objDataSourceView.FilterExpression = filterCommand
Me.DataBind()
If Me.Rows.Count = 0 Then
objDataSourceView.FilterExpression = ""
Me.ShowNotFoundMessage()
Me.DataBind()
End If
End Sub
Public Sub ShowNotFoundMessage()
Dim strMessage As String = "No records found for this specified search specification."
Dim strScript As String = "alert('" & strMessage & "'); "
If (Not Me.Page.ClientScript.IsStartupScriptRegistered("clientScript")) Then
ScriptManager.RegisterClientScriptBlock(Me.Page, Me.GetType, "clientScript", strScript, True)
End If
End Sub
Public Sub SetPageSize()
'Skip hardcoded page size for role permission
If Me.PageSize <> 500 And Me.PageSize <> 25 Then
Me.PageSize = DBUtilities.GetPageSize
End If
End Sub
End Class
End Namespace
My question is, how do I access the values of the created textboxes in the calling page's code? I've tried the following but none of them work:
Label.Text = GridView1.FindControl("txtFilter3")
or
Dim row As GridViewRow = GridView1.Rows(0)
Label.Text = row.Cells(2).Text
or
Label.Text = C_C_C_CtlAccountProjectList1_GridView1_GridView1_txtFilter3

gridview loop issue

I have a gridview with 4 columns, three of them are template fields where the user can enter the information needed and click a button to submit it to the database. I have 2 issues:
When I click my button to add a second row... the data in the first row posts
disappears. I want to be able to add the row without the first row of information
disappearing for multiple record entry situations. My code follows:
Private Sub SetInitialRow()
Dim dts As New DataTable()
Dim drs As DataRow = Nothing
dts.Columns.Add(New DataColumn("Approval Date", GetType(String)))
dts.Columns.Add(New DataColumn("Total Amount", GetType(String)))
dts.Columns.Add(New DataColumn("Comments", GetType(String)))
dts.Columns.Add(New DataColumn("Initials", GetType(String)))
drs = dts.NewRow()
drs("Approval Date") = String.Empty
drs("Total Amount") = String.Empty
drs("Comments") = String.Empty
drs("Initials") = String.Empty
dts.Rows.Add(drs)
ViewState("CurrentTable") = dts
gvOLIAdj.DataSource = dts
gvOLIAdj.DataBind()
End Sub
Private Sub AddNewRowToGrid()
Dim rowIndex As Integer = 0
If ViewState("CurrentTable") IsNot Nothing Then
Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count > 0 Then
For i As Integer = 1 To dtCurrentTable.Rows.Count
'extract the TextBox values
Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
drCurrentRow = dtCurrentTable.NewRow()
drCurrentRow("Approval Date") = box1.Text
dtCurrentTable.Rows(i - 1)("Total Amount") = box2.Text
dtCurrentTable.Rows(i - 1)("Comments") = box3.Text
'dtCurrentTable.Rows(i - 1)("Initials") =
rowIndex += 1
Next
dtCurrentTable.Rows.Add(drCurrentRow)
ViewState("CurrentTable") = dtCurrentTable
gvOLIAdj.DataSource = dtCurrentTable
gvOLIAdj.DataBind()
End If
Else
Response.Write("ViewState is null")
End If
'Set Previous Data on Postbacks
SetPreviousData()
End Sub
Private Sub SetPreviousData()
Dim rowIndex As Integer = 0
If ViewState("CurrentTable") IsNot Nothing Then
Dim dats As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
If dats.Rows.Count > 0 Then
For i As Integer = 0 To dats.Rows.Count - 1
Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
box1.Text = dats.Rows(i)("Approval Date").ToString()
box2.Text = dats.Rows(i)("Total Amount").ToString()
box3.Text = dats.Rows(i)("Comments").ToString()
rowIndex += 1
Next
End If
End If
End Sub
Protected Sub btnAddNewRow_Click(sender As Object, e As EventArgs) Handles btnAddNewRow.Click
AddNewRowToGrid()
End Sub
When I try to write a loop that will loop through each of the template fields to grab
the data and put it into my database it doesn't recognize that I have data in the
template fields? This is what I have tried thus far to no avail...
Protected Sub btn_Update_Click(sender As Object, e As EventArgs) Handles btn_Update.Click
For Each row As GridViewRow In gvOLIAdj.Rows
For Each gv As GridViewRow In gvOLIAdj.Rows
Dim appDt As String = (Rows(rowIndex).Cells(1).FindControl("txtAdjAppr")), TextBox)
Dim approvalDt As String = CType(gv.FindControl("txtAdjAppr"), TextBox).Text
Dim totalAmt As String = CType(gv.FindControl("txtAdjAmt"), TextBox).Text
Dim comments As String = CType(gv.FindControl("txtcmmts"), TextBox).Text
Dim intitials As String = DirectCast(gv.FindControl("total"), TextBox).Text
Next
End Sub
In your AddNewRowToGrid method you are doing the following:
dtCurrentTable.Rows(i - 1)("Total Amount") = box2.Text
dtCurrentTable.Rows(i - 1)("Comments") = box3.Text
What's wrong here is the updating of the row in dtCurrentTable.Rows(i - 1). You are updating the values in the row above that which you wish to update.

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