I am new to jQuery and have some questions. I have created a server web control (it implements a webControl) and wanted to know how to refresh the control when an event fires. In other words:
I have a server control that has a drop-down list.
When the user makes a selection, I want to cause a partial post back and reload the control (to set some public properties values that can be read by the page consuming the control).
Can this be done just by using jQuery or would I still need to update the panels?
Here is my server control:
<Assembly: WebResource("com.myControls.WebControls.miniActiveDirectorySearchStyle.css", "text/css", PerformSubstitution:=True)>
Namespace com.myControls.WebControls
< _
System.Drawing.ToolboxBitmap(GetType(Button), "myControls.WebControls.ActiveDirectorySearch.bmp"), ToolboxData("<{0}:miniActiveDirectorySearch ID='miniActiveDirectorySearch{0}' runat=""server""> </{0}:miniActiveDirectorySearch>"), _ ClientCssResource("com.myControls.WebControls.miniActiveDirectorySearchStyle.css")> _
Public Class miniActiveDirectorySearch
Inherits WebControl
Public ddlValue As New TextBox
Public ddlText As New TextBox
Private tblMainLayout As HtmlTable
Private divControlContainer As New HtmlGenericControl()
Private modalExtender As New ModalPopupExtender()
Private tbSearchUser As New TextBox
''' <summary>
'''X Offset for modal dialog
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
<Description("Mouser Over Highlight Color")> Public Property mouseOverColor As String = "#9db3d9"
''' <summary>
'''X Offset for modal dialog
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
<Description("Drop Down List Width")> Public Property ddlWidth As String = "100"
Private Sub attachWebResources()
Dim styleLink As String = "<link rel='stylesheet' text='text/css' href='{0}' />"
Dim location As String = Page.ClientScript.GetWebResourceUrl(Me.[GetType](), "myControls.WebControls.miniActiveDirectorySearchStyle.css")
Dim styleInclude As New LiteralControl([String].Format(styleLink, location))
DirectCast(Page.Header, HtmlControls.HtmlHead).Controls.Add(styleInclude)
ScriptManager.RegisterClientScriptResource(Me, Me.GetType, "com.myControls.ActiveDirectory.WebControls.jquery-1.4.1.min.js")
ScriptManager.RegisterClientScriptResource(Me, Me.GetType, "com.myControls.ActiveDirectory.WebControls.miniActiveDirectorySearch.js")
End Sub
Protected Overrides Sub CreateChildControls()
createDynamicControls()
MyBase.CreateChildControls()
End Sub
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
attachWebResources()
MyBase.OnInit(e)
End Sub
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
End Sub
Private Sub createDynamicControls()
Controls.Clear()
Try
tblMainLayout = buildMaintable()
Controls.Add(tblMainLayout)
Catch ex As Exception
Throw New ApplicationException("Exception Occurred Creating Control.", ex.InnerException)
End Try
End Sub
Private Function buildMaintable() As HtmlTable
tblMainLayout = New HtmlTable
Dim divImage As New HtmlGenericControl("div")
ddlText = New TextBox
ddlValue = New TextBox
With ddlText
.ID = "ddlText"
End With
With ddlValue
.ID = "ddlValue"
End With
With divControlContainer
.ID = Me.UniqueID & "_divSearchResults"
.Attributes.Add("onClick", "hideMe(this)")
End With
With divImage
.ID = Me.UniqueID & "_ImageDiv"
End With
With tblMainLayout
.CellPadding = 0
.CellSpacing = 0
.Style.Add("border-collapse", "collapse")
Dim tr As New HtmlTableRow
With tr
Dim td As New HtmlTableCell
With td
With tbSearchUser
.ID = Me.UniqueID & "_tbSearchName"
.Attributes.Add("onKeyPress", "searchKeyPress(event, this.id, '" & divControlContainer.UniqueID & "', '" & mouseOverColor & "','" & ddlText.ID & "','" & ddlValue.ID & "')")
.Attributes.Add("onmouseover", "document.getElementById('" & divImage.ID & "').className='DivSearchMouseOverMini', tbMouseOver(this)")
.Attributes.Add("OnmouseOut", "document.getElementById('" & divImage.ID & "').className='divSearchDefaultMini',tbMouseOut(this)")
.Width = ddlWidth
.Attributes.Add("onClick", "showSearchResults('" & divControlContainer.UniqueID & "')")
.CssClass = "tbSearchDefault"
End With
.Controls.Add(tbSearchUser)
.Controls.Add(ddlText)
.Controls.Add(ddlValue)
End With
.Controls.Add(td)
td = New HtmlTableCell
With td
With divImage
.Attributes.Add("class", "divSearchDefaultMini")
.Attributes.Add("onmouseover", "this.className='DivSearchMouseOverMini',document.getElementById('" & tbSearchUser.ID & "').className='tbSearchMouseOver'")
.Attributes.Add("onmouseout", "this.className='divSearchDefaultMini', document.getElementById('" & tbSearchUser.ID & "').className='tbSearchDefault'")
.Attributes.Add("onClick", "showSearchResults('" & divControlContainer.UniqueID & "')")
End With
.Controls.Add(divImage)
End With
.Controls.Add(td)
End With
.Controls.Add(tr)
tr = New HtmlTableRow
With tr
Dim td As New HtmlTableCell
With td
.ColSpan = 2
.Controls.Add(divControlContainer)
End With
.Controls.Add(td)
End With
.Controls.Add(tr)
End With
Return tblMainLayout
End Function
End Class
This code creates a server control with a textbox and styles to mimick a dropdown list. This way, I can add some functionality to the drop down list. I would like to cause a partial post back when the user makes a change to the "dropdown list" or textbox. All my jQuery is done in another file that is added as a web resource.
Why not use an ajax call to the server page, which won't cause an actual post-back. Grab what you need and update it on the client in the response. Or, you can fire your server code to do that as well.
jQuery ajax is really easy to use. Just declare a static Webmethod on the server to handle whatever your request is supposed to accomplish.
Related
When using a Web Adapter class (inherited from WebControlAdapter) to render an asp:RadioButton control as I want, via the
Protected Overrides Sub RenderContents(ByVal output As HtmlTextWriter)
sub, it all works fine, even the AutoPostBack (if I call it) - but, on PostBack, the control's CheckedChanged event isn't being fired. Any ideas as to why will be gratefully received!
Imports System.Web.UI.WebControls.Adapters
Public Class myRadio
Inherits WebControlAdapter
Protected Overrides Sub RenderBeginTag(ByVal writer As System.Web.UI.HtmlTextWriter)
' MyBase.RenderBeginTag(writer)
End Sub
Protected Overrides Sub RenderEndTag(ByVal writer As System.Web.UI.HtmlTextWriter)
' MyBase.RenderEndTag(writer)
End Sub
Protected Overrides Sub RenderContents(ByVal output As HtmlTextWriter)
Dim ctrl As RadioButton = CType(Me.Control, RadioButton)
Dim sb As New StringBuilder
Dim cntxt As HttpContext = HttpContext.Current
Try
sb.Append("<label><input class=""")
sb.Append(ctrl.CssClass)
sb.Append(""" type=""radio""")
sb.Append(" name=""")
sb.Append(ctrl.GroupName)
sb.Append("""")
sb.Append(" value=""")
sb.Append(ctrl.Text)
sb.Append("""")
sb.Append(" id=""")
sb.Append(ctrl.ID)
sb.Append("""")
If ctrl.Checked Then sb.Append(" checked=""checked"" ")
If ctrl.AutoPostBack Then
sb.Append(" onclick=""javascript:setTimeout('__doPostBack(\'" & ctrl.ID & "\',\'\')', 0)"" ")
End If
sb.Append("> ")
sb.Append(ctrl.Text)
sb.Append("</label>")
Catch ex As Exception
sb = New StringBuilder
sb.Append("Error building Control:<br />")
sb.Append(ex.Message)
End Try
output.Write(sb.ToString)
End Sub
End Class
This one is REALLY driving me nuts. I've read, and tried, most of the workarounds but still it posts back!!
All the markup is generated dynamically from code-behind and inserted into a page that is part of a Master Page, from the init event.
There are a series of nested tabs, the tab content for the most part is data in a GridView. Each Gridview is set in it's own update panel. Every time a LinkButton in the GridView is clicked there is a full postback causing the tabs to reset (any button outside of the GridView and in the UpdatePanel doesn't cause a full postback.
LinkButtons are generated like this
Dim Select_Field As New CommandField
With Select_Field
.HeaderText = "View Transactions"
.SelectText = "View Transactions"
.ShowSelectButton = True
End With
GV.Columns.Add(Select_Field)
Registering with ToolKitScriptManager
Private Sub AssessmentsMain_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim vID As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID"))
Dim LB As LinkButton = CType(e.Row.Cells(4).Controls(0), LinkButton)
LB.ID = "AssMain_" & vID
AjaxControlToolkit.ToolkitScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(LB)
End If
Catch ex As Exception
Dim vError As New SendError
vError.MailError("840", PageName, ex)
ShowError()
End Try
End Sub
and the generated markup for one row is like this
<tr class="GridView" style="color:#333333;background-color:#F7F6F3;">
<td>10</td>
<td>Adam White</td>
<td>4224 Res Road</td>
<td align="right">$6,850.65</td>
<td>
<a id="ctl00_ContentPlaceHolder1_AssessmentsMainGV_ctl02_AssMain_10" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$AssessmentsMainGV','Select$0')" style="color:#333333;">View Transactions</a>
The GridView class
Public Class HAS_Gridview
Inherits GridView
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
CellPadding = 4
GridLines = WebControls.GridLines.None
ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
ClientIDMode = UI.ClientIDMode.AutoID
With MyBase.FooterStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Color.White
End With
RowStyle.BackColor = Drawing.ColorTranslator.FromHtml("#F7F6F3")
RowStyle.ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
PagerStyle.HorizontalAlign = WebControls.HorizontalAlign.Center
PagerStyle.ForeColor = Color.Black
PagerStyle.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
With MyBase.SelectedRowStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
End With
With MyBase.HeaderStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Color.Black
.CssClass = "GridView"
End With
EditRowStyle.BackColor = Drawing.ColorTranslator.FromHtml("#999999")
With MyBase.AlternatingRowStyle
.BackColor = Color.White
.ForeColor = Drawing.ColorTranslator.FromHtml("#284775")
.CssClass = "GridView"
End With
With MyBase.RowStyle
.CssClass = "GridView"
End With
End Sub
End Class
Have you tried adding trigger programmatically instead of registering in AjaxControlToolkit:
Dim trigger As New AsyncPostBackTrigger()
trigger.ControlID = LB.ID
trigger.EventName = "Click"
MyUpdatePanel.Triggers.Add(trigger)
It looks like the postback is caused by href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$AssessmentsMainGV','Select$0')" in the generated markup for the anchor tag.
Try to define your own _doPostBack.
If you haven't checked post a and post b already, they offer a couple of ways to do that.
In the end the only way I could get this to work was
Create a class for a LinkButton Template
Public Class LinkButtonTemplate
Implements ITemplate
Private m_ColumnName As String
Event LinkButtonItem_Clicked(sender As LinkButton, e As EventArgs)
Public Property ColumnName() As String
Get
Return m_ColumnName
End Get
Set(ByVal value As String)
m_ColumnName = value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal ColumnName As String)
Me.ColumnName = ColumnName
End Sub
Public Sub InstantiateIn(container As Control) Implements ITemplate.InstantiateIn
Dim LB As New LinkButton()
With LB
.ID = "LB_" & ColumnName
.Text = ColumnName
.OnClientClick = "LinkButtonClick(this);"
End With
container.Controls.Add(LB)
End Sub
End Class
Add this javascript so that it would post the ID to a hidden field and click a hidden button
Private Sub LoadLinkButtonClick()
Try
Dim SB As New StringBuilder
SB.Append("function LinkButtonClick(LinkButton){ ")
SB.Append("setTimeout(function() { ")
SB.Append("$get('" & GridViewLBClicked.ClientID & "').click(); ")
SB.Append(" }, 300); ")
SB.Append("var sendingID = LinkButton.id; ")
SB.Append("document.getElementById('" & HiddenField1.ClientID & "').value = sendingID; ")
SB.Append("} ")
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "LoadLinkButton", SB.ToString, True)
Catch ex As Exception
Dim vError As New SendError
vError.MailError("1229", PageName, ex)
End Try
End Sub
On the RowDataBound event capture the ID we need and add it to the LinkButton ID (so now we know both the sending GridView and the selected row)
Private Sub AssessmentsMain_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim vID As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID"))
Dim LB As LinkButton = CType(e.Row.Cells(4).Controls(0), LinkButton)
LB.ID = "AssMain_" & vID
End If
Catch ex As Exception
Dim vError As New SendError
vError.MailError("840", PageName, ex)
ShowError()
End Try
End Sub
From the hidden button click we can recover all the data we need to make the async postback
Private Sub RaiseLinkButton_Click(sender As Object, e As EventArgs)
Try
Dim vFunction As New Functions
Dim vValue As String = HiddenField1.Value
Dim vSplit = vValue.Split("_")
Dim i As Integer = 0
For Count As Integer = 0 To vSplit.Length - 1
i += 1
Next
Dim DGName As String = vSplit(i - 2)
Select Case DGName
Case "AssMain"
Dim MV As MultiView = vFunction.FindControlRecursive(BodyMain, "AssessmentMultiView")
Dim GV As CustomControl.HAS_Gridview = vFunction.FindControlRecursive(BodyMain, "AssessmentDetailGV")
With GV
.DataSource = AssessmentsDetail_ReturnDataSet()
.DataBind()
.PageIndex = 0
End With
MV.ActiveViewIndex = 1
Dim vPanel As UpdatePanel = vFunction.FindControlRecursive(BodyMain, "AssessmentUpdatePanel")
vPanel.Update()
End Select
Catch ex As Exception
Dim vError As New SendError
vError.MailError("953", PageName, ex)
ShowError()
End Try
End Sub
I have an asp.net web page which is giving me some problems. I developed the following classes to generate search filters for the page. The search process is not important as it already works. I want to dynamically generate the search filters.
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports MEI.SPDocuments.Type
Public Class SearchFilter
Private WithEvents _genreDropDown As DropDownList
Private WithEvents _subGenreDropDown As DropDownList
Private WithEvents _txtValue As TextBox
Private _txtBoxAutoCompleteExtender As AjaxControlToolkit.AutoCompleteExtender
Private _filterGenres As Collection(Of String)
Private _programSubGenres() As String = {"Program ID,GetPrograms", "Territory ID,GetTerritories", _
"Rep Name,GetRepNames", "District ID,GetDistricts", "DM Name,GetDMNames", "Region ID,GetRegions", _
"RM Name,GetRMNames", "Speaker Counter,GetSpeaker", "Vedor ID,GetVendors", "Vendor Name,GetVendorName", _
"Date Range,", "City,", "State,", "Pay To,", "Expense Range,", "PIF ID,GetPifs"}
Private _speakerSubGenres() As String = {"Speaker Counter,GetSpeaker", "Speaker Last Name,GetSpeakerLNames", "Speaker First Name,GetSpeakerFNames"}
Private _expenseSubGenres() As String = {"Expense Counter,GetExpenses"}
Private _vendorSubGenres() As String = {"Vendor ID,GetVendors", "Vendor Name,GetVendorName"}
Private _trackSubGenres() As String = {"Track Number,GetTracks", "HCP First Name,GetHCPFName", "HCP Last NameGetHCPLName"}
Public Sub New(ByVal company As CompanyCode, ByVal year As DocumentYearCode)
_filterGenres = New Collection(Of String)
_txtValue = New TextBox
_txtValue.ID = Guid.NewGuid.ToString
_txtBoxAutoCompleteExtender = New AjaxControlToolkit.AutoCompleteExtender
With _txtBoxAutoCompleteExtender
.ID = "AC__" + _txtValue.ID
.MinimumPrefixLength = 1
.EnableCaching = False
.ServicePath = "~/AutoComplete.asmx"
.ServiceMethod = "PlaceHolder"
.TargetControlID = _txtValue.ID
.CompletionListCssClass = "CompletionList"
.CompletionListHighlightedItemCssClass = "ItemHighlighted"
.CompletionListItemCssClass = "ListItem"
.DelimiterCharacters = ""
.Enabled = True
End With
Select Case company
Case CompanyCode.AbbottAnimalHealth, CompanyCode.AbbottDiabetesCare, CompanyCode.AbbottDiagnosticsDivision, CompanyCode.AbbottMedicalOptics, CompanyCode.AbbottMolecular, _
CompanyCode.AbbottPointOfCare, CompanyCode.AbbottVascular, CompanyCode.Corporate, CompanyCode.DivAbbottNutrition, CompanyCode.EstablishedProductsDivision, _
CompanyCode.GlobalPharmaceuticalResearchAndDevelopment, CompanyCode.GlobalStrategicMarketingAndServices, CompanyCode.PharmaseuticalProductsGroup, _
CompanyCode.ProprietaryPharmaceuticalsDivision, CompanyCode.RegulatoryAffairsPPG
_filterGenres.Add("Div Docs")
Case Else
_filterGenres.Add("Program")
_filterGenres.Add("Speaker")
_filterGenres.Add("Expense")
_filterGenres.Add("Vendor")
End Select
_genreDropDown = New DropDownList
_genreDropDown.AutoPostBack = True
_genreDropDown.Attributes.Add("runat", "server")
AddHandler _genreDropDown.SelectedIndexChanged, AddressOf _genreDropDown_ItemChanged
_subGenreDropDown = New DropDownList
_subGenreDropDown.AutoPostBack = True
_subGenreDropDown.Attributes.Add("runat", "server")
AddHandler _subGenreDropDown.SelectedIndexChanged, AddressOf _subGenreDropDown_ItemChanged
PopulateDDls()
End Sub
Private Sub PopulateDDls()
_genreDropDown.Items.Add("")
For Each s As String In _filterGenres
_genreDropDown.Items.Add(s)
Next
End Sub
Private Sub _genreDropDown_ItemChanged(ByVal sender As Object, ByVal e As System.EventArgs)
_subGenreDropDown.Items.Clear()
_subGenreDropDown.Items.Add("")
Select Case _genreDropDown.SelectedItem.ToString
Case "Program"
For Each s As String In _programSubGenres
Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))
_subGenreDropDown.Items.Add(li)
Next
Case "Speaker"
For Each s As String In _speakerSubGenres
Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))
_subGenreDropDown.Items.Add(li)
Next
Case "Expense"
For Each s As String In _expenseSubGenres
Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))
_subGenreDropDown.Items.Add(li)
Next
Case "Vendor"
For Each s As String In _vendorSubGenres
Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))
_subGenreDropDown.Items.Add(li)
Next
Case "Div Docs"
For Each s As String In _trackSubGenres
Dim li As New ListItem(s.Split(CChar(","))(0), s.Split(CChar(","))(1))
_subGenreDropDown.Items.Add(li)
Next
End Select
End Sub
Private Sub _subGenreDropDown_ItemChanged(ByVal Sender As Object, ByVal e As System.EventArgs)
_txtBoxAutoCompleteExtender.ServiceMethod = _subGenreDropDown.SelectedValue.ToString
If _subGenreDropDown.SelectedValue.ToString = String.Empty Then _txtBoxAutoCompleteExtender.ServiceMethod = "PlaceHolder"
End Sub
Public Function createMyTableRow() As HtmlTableRow
Dim myRow As New HtmlTableRow
myRow.Cells.Add(New HtmlTableCell())
myRow.Cells.Add(New HtmlTableCell())
myRow.Cells.Add(New HtmlTableCell())
myRow.Cells(0).Controls.Add(_genreDropDown)
myRow.Cells(1).Controls.Add(_subGenreDropDown)
myRow.Cells(2).Controls.Add(_txtValue)
myRow.Cells(2).Controls.Add(_txtBoxAutoCompleteExtender)
Return myRow
End Function
Private Sub newAutoCompleteExtender(ByVal genre As String)
If _txtValue.Parent.Controls.Count = 2 Then
_txtValue.Parent.Controls.RemoveAt(1)
End If
_txtValue.Parent.Controls.Add(_txtBoxAutoCompleteExtender)
End Sub
End Class
Public Class SearchFilterGroup
Private _searchFilterCollection As Collection(Of SearchFilter)
Private _tableContainer As HtmlTable
Private _company As CompanyCode
Private _year As DocumentYearCode
Public WithEvents _addFilterButton As New Button
Public Sub New(ByVal company As CompanyCode, ByVal year As DocumentYearCode)
_searchFilterCollection = New Collection(Of SearchFilter)
_tableContainer = New HtmlTable
_company = company
_year = year
_addFilterButton.Text = "Add Filter"
_addFilterButton.Attributes.Add("runat", "server")
_addFilterButton.ID = "btnAddFilter"
AddHandler _addFilterButton.Click, AddressOf _addFilterButton_Click
End Sub
Public Sub _addFilterButton_Click(ByVal Sender As Object, ByVal e As System.EventArgs)
_searchFilterCollection.Add(New SearchFilter(_company, _year))
_tableContainer.Rows.Add(_searchFilterCollection(_searchFilterCollection.Count - 1).createMyTableRow)
End Sub
Public Function table() As HtmlTable
_tableContainer.Rows.Add(New HtmlTableRow)
_tableContainer.Rows(0).Cells.Add(New HtmlTableCell)
_tableContainer.Rows(0).Cells(0).ColSpan = 3
_tableContainer.Rows(0).Cells(0).Controls.Add(_addFilterButton)
_addFilterButton_Click(Nothing, Nothing)
_addFilterButton_Click(Nothing, Nothing)
Return _tableContainer
End Function
End Class
I am having problems devising a way to persist the generate controls. Any help would be appreciated.
Basically, for task which you do is better to create custom server control. In ASP.NET exist CompositeControl class which simplifies developing your own server controls which for example should include some other server controls (like panels, texboxes and etc) as children.
A very good link to start with creating your own server controls is Dino Esposito article: A Crash Course on ASP.NET Control Development: Building Composite Controls
I'm working on a custom GridView control and need some help. I can get it to properly spit out what I need if I manually put in the column name. Right now I have 2 problems. The first one is getting the column headers to display dynamically. The second is filling in row items dynamicly.
Default.aspx
<asp:View id="vCreateNew" runat="server">
Content Here (View 2)...
<trac:DataGridView id="gvMain" runat="server" GridLines="Horizontal" AutoGenerateColumns="False" > </trac:DataGridView>
</asp:View>
Default.aspx.vb
Partial Class processes_ProgramTrack_Default
Inherits Citi.CSPaper.Controls.BasePage
Protected Sub ProgramTrackNav_MenuItemClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles ProgramTrackNav.MenuItemClick
Dim strSelection As String = ProgramTrackNav.SelectedValue
Dim sqlDataSource As New SqlDataSource()
sqlDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("CSPaperWEBConnectionString").ConnectionString
Select Case strSelection
......
Case "CreateNew"
mlvNav.SetActiveView(vCreateNew)
sqlDataSource.SelectCommand = "SELECT [ProgramNumber], [ProgramName], [ProgramStatus] FROM tblPrgTrackPrograms"
Dim args As New DataSourceSelectArguments
gvMain.DataSource = sqlDataSource.Select(args)
gvMain.DataBind()
........
End Select
End Sub
End Class
GridViewControl.ascx
<%# Control Language="VB" AutoEventWireup="false" CodeFile="GridViewControl.ascx.vb" Inherits="GridViewControl" %>
<asp:GridView ID="GridViewControl" runat="server" >
</asp:GridView>
GridViewControl.ascx.vb
Public Class GridViewControl
Inherits System.Web.UI.UserControl
Private _html As New StringBuilder()
Private _dataSource As IEnumerable
Private _CssClass As String
Private _CellSpacing As String
Public Property DataSource() As IEnumerable
Get
Return _dataSource
End Get
Set(ByVal value As IEnumerable)
_dataSource = value
End Set
End Property
Public Overridable Property CssClass() As String
Get
Return _CssClass
End Get
Set(ByVal value As String)
_CssClass = value
End Set
End Property
Public Overridable Property CellSpacing() As String
Get
Return _CellSpacing
End Get
Set(ByVal value As String)
_CellSpacing = value
End Set
End Property
Private Sub CreateBulletedList()
Dim dataSource As IEnumerable = Nothing
Dim i As Integer = 0
Dim strArr() As String = {"ID", "Name", "Fee"}
Try
dataSource = Me._dataSource
Catch
End Try
If Not (dataSource Is Nothing) Then
_html.Append("<table id=""" & ClientID & """ class=""" & _CssClass & """ CellSpacing=""" & _CellSpacing & """>")
_html.Append("<thead>" & vbCrLf & "<tr>" & vbCrLf)
For Each Item As String In strArr
_html.Append("<th>" & Item & "</th>" & vbCrLf)
Next
_html.Append("</tr>" & vbCrLf & "</thead><tbody>" & vbCrLf)
For Each dataObject As Object In dataSource
_html.Append("<tr>" & vbCrLf)
For i = 0 To 2
_html.Append("<td>" & vbCrLf)
_html.Append(dataObject.Row(i))
_html.Append("</td>" & vbCrLf)
Next
_html.Append("</tr>" & vbCrLf)
Next dataObject
_html.Append("</tbody></table>" & vbCrLf)
End If
End Sub
Public Overrides Sub DataBind()
MyBase.OnDataBinding(EventArgs.Empty)
CreateBulletedList()
End Sub
Protected Overrides Sub Render(ByVal output As HtmlTextWriter)
output.Write(_html)
End Sub
End Class
------------------------------------
| Table Data |
------------------------------------
ID AppName Environment
2 TestApp UAT
3 ServerFileMaint UAT
4 ProgramTrack Development
5 RegZ_Stmnt_Adj Active
6 SecInv Decommission
I do not want to manually code for i = 0 to ..., the upperbound, but want to do this dynamicly. Same way for the headings. The problem I run into is if I don't hard code the upperbound I get an error message stating Cannot find column 3.. I get this when coding a second For Each block to loop through the row contained data.
I think I understand whats going on here, and how to fix it.
The biggest source of confusion for me is this block:
For Each dataObject As Object In dataSource
_html.Append("<tr>" & vbCrLf)
For i = 0 To 2
_html.Append("<td>" & vbCrLf)
_html.Append(dataObject.Row(i))
_html.Append("</td>" & vbCrLf)
Next
_html.Append("</tr>" & vbCrLf)
Next dataObject
If dataSource is a DataSet then this kind of makes sense... but not really because instead you would want to reference Table(0). If dataSource is a DataTable then this kind of makes sense except not really because then you would want to loop through For Each dataObject as DataRow in dataSource.Rows. This doesn't appear to be the case though because you reference dataObject.Row(i).
What you probalby want to do is (in rough/untested code) more like this:
For Each dataObject As DataRow In dataSource.Rows
_html.Append("<tr>" & vbCrLf)
For Each col as DataColumn In dataSource.Columns
_html.Append("<td>" & vbCrLf)
_html.Append(dataObject(col).ToString())
_html.Append("</td>" & vbCrLf)
Next
_html.Append("</tr>" & vbCrLf)
Next
This makes the assumption that dataSource is a DataTable, you are going to loop through all of that tables rows, and then for each row you will loop through all columns in the datatable and get the data in that row for each column and display it.
I'm trying to get thee previous page visited in ASP.NET using VB.NET using the following code:
Partial Class _Default Inherits Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim previousPage As String = Page.Request.UrlReferrer.ToString
If (Request.UrlReferrer <> Nothing) Then
If previousPage.Contains("Login") Then
Dim tUsername As String = Session("Username")
lblUsername.Text = "Welcome, " + tUsername
ElseIf previousPage.Contains("Register") Then
Dim cUsername As String = Session("CUsername")
lblUsername.Text = "Welcome, " + cUsername
Else
lblUsername.Text = "Welcome, Guest"
End If
End If
End Sub
End Class
I get this error:
Object reference not set to an instance of an object.
at:
Dim previousPage As String = Page.Request.UrlReferrer.ToString
What I want to do is get the previous page visited so I can get a session variable.
Try This code.
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If (Request.UrlReferrer <> Nothing) Then
Dim previousPage As String = Page.Request.UrlReferrer.ToString
If previousPage.Contains("Login") Then
Dim tUsername As String = Session("Username")
lblUsername.Text = "Welcome, " + tUsername
ElseIf previousPage.Contains("Register") Then
Dim cUsername As String = Session("CUsername")
lblUsername.Text = "Welcome, " + cUsername
End If
Else
lblUsername.Text = "Welcome, Guest"
End If
End Sub
End Class
Unsure what you are trying to do but while its easy enough to answer your specific question, you should take a step back and review why you are doing things that way.
It seems you are trying to control flow based on some authentication. If so, consider ASP.Net Forms Authentication +/- Login Controls. You can "plug" this architecture into your existing auth mechanism (meaning you don't have to uproot your existing stuff to implement it).
(If you still want to reinvent the wheel) Consider cookies instead of trying to figure out "where the user came from" prior to landing on "this" page - both of which can vary by x - the more web pages your web site has or will have, you'll have more spaghetti.