I'm a tad confused. I have a Repeater which populates a list of Checkbox controls and Label controls. But it doesn't seem like the checked state of the checkboxes is remembered in ViewState until AFTER the first postback.
Scenario: I have 5 items in my custom checkbox list. I select the first 3 and submit the form. The first 3 are no longer selected. I select items 1, 3 and 5 and submit again. After the page is loaded 1, 3 and 5 are still selected.
Here's the entire code for the test page I'm using. My apologies for the VB :-p
Imports System.Xml
Partial Public Class _Default
Inherits System.Web.UI.Page
Dim _roles As Repeater
Dim _output As Literal
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
_roles = New Repeater()
_roles.ItemTemplate = New RolesListTemplate(ListItemType.Item)
Me.Form.Controls.Add(_roles)
Dim btn As New Button()
btn.Text = "Save"
btn.UseSubmitBehavior = True
AddHandler btn.Command, AddressOf btnSave_OnCommand
Me.Form.Controls.Add(btn)
_output = New Literal
Me.Form.Controls.Add(_output)
End Sub
Private Sub btnSave_OnCommand(ByVal sender As Object, ByVal e As CommandEventArgs)
Dim roleData As String = GetXML(_roles)
_output.Text = "<br>" & HttpUtility.HtmlEncode(roleData) & "<br>DONE"
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim RoleData As New List(Of Role)
RoleData.Add(New Role With {.selected = 0, .enabled_ind = 1, .role_id = 123, .role_description = "Role 123"})
RoleData.Add(New Role With {.selected = 0, .enabled_ind = 1, .role_id = 345, .role_description = "Role 345"})
RoleData.Add(New Role With {.selected = 0, .enabled_ind = 1, .role_id = 678, .role_description = "Role 678"})
RoleData.Add(New Role With {.selected = 0, .enabled_ind = 1, .role_id = 6987, .role_description = "Role 6987"})
RoleData.Add(New Role With {.selected = 0, .enabled_ind = 1, .role_id = 1122, .role_description = "Role 1122"})
If RoleData IsNot Nothing Then
If RoleData.Count > 0 Then
_roles.DataSource = RoleData
_roles.DataBind()
_roles.Visible = True
Else
_roles.Visible = False
End If
End If
End If
End Sub
Private Function GetXML(ByVal _cb_roles As Repeater) As String
Dim settings As New XmlWriterSettings
settings.CheckCharacters = True
settings.CloseOutput = True
settings.OmitXmlDeclaration = True
Dim xw As XmlWriter
Dim sb As New StringBuilder()
xw = XmlWriter.Create(sb, settings)
xw.WriteStartDocument()
xw.WriteStartElement("roles")
For Each row As RepeaterItem In _cb_roles.Items
Dim pnl As Panel = TryCast(row.Controls.Item(0), Panel)
Dim cb As CheckBox = TryCast(pnl.Controls.Item(0), CheckBox)
Dim id As String = String.Empty
Dim parts() As String = cb.ID.Split("_"c)
id = cb.InputAttributes("role_id")
xw.WriteStartElement("role")
xw.WriteAttributeString("role_id", id)
If cb.Checked Then
xw.WriteAttributeString("selected", "1")
Else
xw.WriteAttributeString("selected", "0")
End If
xw.WriteEndElement()
Next
xw.WriteEndElement()
xw.WriteEndDocument()
xw.Close()
Return sb.ToString
End Function
Public Class RolesListTemplate
Implements ITemplate, INamingContainer
Private _ltItemType As ListItemType
Private _ctlParent As WebControl
Sub New(ByVal pType As ListItemType)
Try
_ltItemType = pType
Catch ex As Exception
Throw ex
End Try
End Sub
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Select Case _ltItemType
Case ListItemType.Header
Case ListItemType.Item
Dim pnl As New Panel()
Dim cb As New CheckBox()
cb.AutoPostBack = True
cb.ID = "role_check"
AddHandler cb.DataBinding, AddressOf RolesListTemplate_DataBind
pnl.Controls.Add(cb)
Dim lbl As New Label()
lbl.ID = "role_lbl"
AddHandler lbl.DataBinding, AddressOf RolesListTemplate_DataBind
pnl.Controls.Add(lbl)
container.Controls.Add(pnl)
Case ListItemType.AlternatingItem
Case ListItemType.Footer
End Select
End Sub
Private Sub RolesListTemplate_DataBind(ByVal sender As Object, ByVal e As System.EventArgs)
Dim _sender As Control = DirectCast(sender, Control)
Dim container As RepeaterItem = DirectCast(_sender.NamingContainer, RepeaterItem)
Dim role As Role = TryCast(container.DataItem, Role)
If role IsNot Nothing Then
If role.selected OrElse role.enabled_ind Then
Select Case _sender.ID
Case "role_check"
Dim role_check As CheckBox = DirectCast(_sender, CheckBox)
role_check.Checked = role.selected
role_check.ID = "role_list_" & role.role_id.ToString()
role_check.InputAttributes("role_id") = role.role_id.ToString()
Case "role_lbl"
Dim role_lbl As Label = DirectCast(_sender, Label)
role_lbl.Text = role.role_description
End Select
Else
container.Visible = False
End If
End If
End Sub
End Class
Public Class Role
Public enabled_ind As Boolean
Public selected As Boolean
Public role_id As Integer
Public role_description As String
End Class
End Class
This is a very common mistake. You want to call DataBind in the Init event, even for post backs.
Related
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
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
I have a dropdown in gridview, which gets data through web method,but after saving data, i am unable to show saved data in gridview.
Here is the code behind for gridview bind through web method:
Private Sub BindData()
Dim objTable As New DataTable("ProjectInfoClass")
objTable = objWebService.BindProjectInfo
projectInfoList.Clear()
For Each dr As DataRow In objTable.Rows
projectInfoList.Add(New ProjectInfoClass With {.ProjectNumber = dr("ProjectNumber").ToString(), .ProjectId = dr("ProjectId").ToString(), .ProjectName = dr("ProjectName").ToString(), .ProjectModifiedDate = dr("ProjectModifiedDate").ToString(), .RecordUpdatedDate = dr("RecordUpdatedDate").ToString(), .ProjectLocation = dr("ProjectLocation").ToString(), .LocationServerName = dr("LocationServerName").ToString(), .ProjectModifiedBy = dr("ProjectModifiedBy").ToString(), .DBServer = dr("DBServer").ToString(), .DBName = dr("DBName").ToString(), .Flag = Nothing})
Next
GridView1.DataSource = objTable
GridView1.DataBind()
End Sub
Save method
For Each objectList In projectInfoList
If objectList.Dirty = True And objectList.Flag = Nothing Then
objWebService.UpdateProjectInfo(objectList)
Label1.Text = "Record updated successfully"
ElseIf objectList.Flag = "I" And objectList.Dirty = True Then
objWebService.InsertProjectInfo(objectList)
Label1.Text = "Record inserted successfully"
End If
Next
BindData()
btnEdit.Enabled = True
btnSave.Enabled = False
btnAddNewRow.Enabled = False
End Sub
Here is the code behind to bind dropdown which calls the web method:
Public Sub BindDataDropDown()
For Each grdRow As GridViewRow In GridView1.
Dim dropDown As DropDownList = DirectCast(GridView1.Rows(grdRow.RowIndex).Cells(7).FindControl("ddlProjectModifiedBy"), DropDownList)
dropDown.DataSource = objWebService.BindDropDown()
dropDown.DataValueField = "EmpId"
dropDown.DataTextField = "EmpName"
dropDown.DataBind()
Next
End Sub
rowdatabound
Protected Sub ddlProjectModifiedBy_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
BindDataDropDown()
End Sub
indexchange
Protected Sub ddlProjectModifiedBy_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim gv As DropDownList = TryCast(sender, DropDownList)
Dim row As GridViewRow = gv.Parent.NamingContainer
Dim rowindex As Integer = row.RowIndex
projectInfoList.Item(rowindex).ProjectModifiedBy = gv.SelectedItem.ToString()
projectInfoList.Item(rowindex).Dirty = True
End Sub
What should i write in the rowbound event of grid to hold selected data of dropdown in gridview?
Call the drop down binding method BindDataDropDown() after you have successfully saved the changes to the database.
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
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 :)