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
Related
im trying to get value(true or false) from database but i want to select from role(DropDownList) to display if had permission or not in section
dropdownlist and checkboxlist using entitdatasource
i try this ( DropdownList(ddlRole))
Protected Sub ddlRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlRole.SelectedIndexChanged
Using context As New AGIP_dbModel.AGIP_dbEntities()
For Each oItem As ListItem In ckSection.Items()
Dim objPerm As tbl_permission = New tbl_permission()
oItem.Value = objPerm.pre_status
Next
End Using
End Sub
This how submite button work(Store in database)
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Using context As New AGIP_dbModel.AGIP_dbEntities()
Dim id As Integer = ddlRole.SelectedValue
Try
Dim obj = context.tbl_permission.Where(Function(u) u.role_id = id)
For Each permission As tbl_permission In obj.ToList
context.tbl_permission.DeleteObject(permission)
context.SaveChanges()
Next
Catch ex As Exception
End Try
For Each oItem As ListItem In ckSection.Items()
Dim objPerm As tbl_permission = New tbl_permission()
objPerm.role_id = ddlRole.SelectedValue
objPerm.pre_status = oItem.Selected
objPerm.section_id = oItem.Value
context.tbl_permission.AddObject(objPerm)
context.SaveChanges()
Next
Response.Redirect("permission.aspx")
End Using
End Sub
tbl_role
tbl_section
tbl_permission relationship with role and section
I'm not familiar with usage of Entity yet so I hope you can get what I'm trying to do here.
Also not sure if checkbox has a Caption or Text property, kindly check.
Protected Sub ddlRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlRole.SelectedIndexChanged
Using context As New AGIP_dbModel.AGIP_dbEntities()
For Each oItem As ListItem In ckSection.Items()
Dim objPerm As tbl_permission = New tbl_permission()
If objPerm.section_name = oItem.Caption Then 'Check if the permission record is same with the caption of the current checkbox in iteration
oItem.Checked = objPerm.pre_status
End If
Next oItem
End Using
End Sub
You also need to modify your SQL query on returning the permission records to include the section_name if you haven't already.
Finally found The Answer:
Protected Sub ddlRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlRole.SelectedIndexChanged
Using context As New BWJO_dbModel.BWJO_dbEntities
Try
For Each secTionItem As ListItem In ckSection.Items
secTionItem.Selected = False
For Each oItem As ListItem In ckSection.Items
Dim PermObj = context.tbl_permission.Any(Function(u) u.role_id = ddlRole.SelectedValue And u.permission_status = True And u.section_id = oItem.Value)
If PermObj = True Then
oItem.Selected = True
End If
Next
Next
Catch ex As Exception
End Try
End Using
End Sub
End Class
I have a function loadList() that loads a dynamic list based on our database.
In element_maint.aspx.vb:
Private Sub loadList()
'load sub-organizations
Dim lstItems As cihElementList = Nothing
Dim thr As TableHeaderRow = Nothing
Dim tr As TableRow = Nothing
Dim tc As TableCell = Nothing
Dim lnk1 As HyperLink = Nothing
Dim lnk2 As HyperLink = Nothing
Dim item As cihCategoryOrgDef = Nothing
Dim rvd As Routing.RouteValueDictionary = Nothing
Dim rvdDeactivate As Routing.RouteValueDictionary = Nothing
Dim vpd As Routing.VirtualPathData = Nothing
Dim vpdDeactivate As Routing.VirtualPathData = Nothing
Dim btnAction As cihBootstrapButtonDropdown = Nothing
'*****************************************
'Build the action drop down
'Build the action button
'*****************************************
btnAction = New cihBootstrapButtonDropdown("Action", cihBootstrapButtonDropdown.buttonTypes.link)
'Existing Items
lstItems = New cihElementList()
lstItems.loadForOrganization(orgId)
For Each ele As cihElementList.elementShort In lstItems.listOfElements
tr = New TableRow
lnk1 = New HyperLink
lnk1.Text = "Edit"
lnk2 = New HyperLink
lnk2.Text = "Deactivate"
rvd = New Routing.RouteValueDictionary(New With {.action = "edit", .elementid = ele.elementId.ToString()})
rvdDeactivate = New Routing.RouteValueDictionary(New With {.action = "deactivate", .elementid = ele.elementId.ToString()})
vpd = Routing.RouteTable.Routes.GetVirtualPath(Nothing, "element_maint", rvd)
vpdDeactivate = Routing.RouteTable.Routes.GetVirtualPath(Nothing, "element_deactivate", rvdDeactivate)
btnAction.addLink("Edit", vpd.VirtualPath, False)
If (ZenCommon.CurrentUser.secLevelId = cihCommonDef.FullSiteAdmin Or ZenCommon.CurrentUser.secLevelId = cihCommonDef.OrganizationAdmin) Then 'if SuperAdmin or Campus Admin
'Need Help here
btnAction.addLink("Deactivate", vpdDeactivate.VirtualPath, False)
End If
ZenCommon.AddCell(tr, ele.eleDescr, , , "200px")
tc = New TableCell
tc.Controls.Add(New LiteralControl(btnAction.buttonHTML))
tc.Style.Add("width", "50px")
tr.Cells.Add(tc)
Me.tblList.Rows.Add(tr)
Next
End Sub
Private Sub deactivateTag()
'Goto Database, flag 'tag' as inactive
End Sub
I want the btnAction.addLink("Deactivate") to call a function in my aspx.vb. The function will go mark the tag as inactive.
Right now the 'Edit" button (just above the 'Deactivate' button, will go to a new page to allow you to edit it. I get that. But is there a way to make it so when I click my 'Deactivate' button it will just call my deactivateTag()
In your codebehind you could change your method signature
Protected Sub deactivateTag(ByRef sender as Object, ByRef e as System.EventArgs) Handles btnDeactivate.Click
and in your markup
<asp:Button ID="btnDeactivate" onClick="deactivateTag" />
Or you can add a click event for the button and call your function from that event.
Protected Sub btnDeactivate_Click(ByRef sender as Object, ByRef e as System.EventArgs) Handles btnDeactivate.Click
deactivateTag()
End Sub
It depends on whether you'll need to call deactivateTag from other controls or not.
I select values from database into textboxes on page load. Then when I change them and want to update the database, values are same as original values. For example I select name Robin Hood into TextBoxName, change it to Bill Gates, but the value of textbox on updating is still Robin Hood. How can I fix this behavior?
However this applies only to textboxes with TextMode="SingleLIne" Or "MultiLine". When textbox has TextMode="Url" for example, it works fine.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Bind
Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "SELECT * FROM Profiles WHERE (ProfileId = #ProfileId)"
cmd.Parameters.AddWithValue("#ProfileId", Request.QueryString("id"))
conn.Open()
Dim rd As SqlDataReader = cmd.ExecuteReader()
While rd.Read()
ProfileImage.ImageUrl = rd.Item("ProPicUrl")
txtName.Text = rd.Item("Name")
txtCity.Text = rd.Item("City")
drpRegion.Items.FindByText(rd.Item("Region")).Selected = True
txtAge.Text = rd.Item("Age")
RadioButtonList1.Items.FindByText(rd.Item("Sex")).Selected = True
txtLink.Text = rd.Item("Link")
txtPhone.Text = rd.Item("Phone")
txtAbout.Text = rd.Item("About")
txtMotto.Text = rd.Item("Motto")
txtGoal.Text = rd.Item("Goal")
txtHobby.Text = rd.Item("Hobby")
End While
conn.Close()
End Using
Catch ex As Exception
End Try
End Sub
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim fileUrl As String = "~/ProPics/"
Dim name As String = txtName.Text
Try
'Save profile picture
Try
If FileUpload1.HasFile Then
fileUrl += FileUpload1.FileName
FileUpload1.SaveAs(Server.MapPath(fileUrl))
Else
fileUrl = ProfileImage.ImageUrl
End If
Catch ex As Exception
UploadMessage.Text = "Nastala chyba při nahrávání obrázku." + vbCrLf + "Chybové hlášení: " + ex.Message
End Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "UPDATE Profiles SET Name = #Name, ProPicUrl = #Url, City = #City, Region = #Region, Age = #Age, Sex = #Sex, Link = #Link, Phone = #Phone, About = #About, Motto = #Motto, Goal = #Goal, Hobby = #Hobby WHERE (ProfileId = #ProfileId)"
cmd.Parameters.AddWithValue("#Url", fileUrl)
cmd.Parameters.AddWithValue("#Name", name)
cmd.Parameters.AddWithValue("#City", txtCity.Text)
cmd.Parameters.AddWithValue("#Region", drpRegion.SelectedItem.Text)
cmd.Parameters.AddWithValue("#Age", txtAge.Text)
cmd.Parameters.AddWithValue("#Sex", RadioButtonList1.SelectedItem.Text)
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text)
cmd.Parameters.AddWithValue("#Link", txtLink.Text)
cmd.Parameters.AddWithValue("#About", txtAbout.Text)
cmd.Parameters.AddWithValue("#Motto", txtMotto.Text)
cmd.Parameters.AddWithValue("#Goal", txtGoal.Text)
cmd.Parameters.AddWithValue("#Hobby", txtHobby.Text)
cmd.Parameters.AddWithValue("#ProfileId", Request.QueryString("id"))
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
'Refresh page
Response.Redirect(Request.RawUrl)
End Using
Catch ex As Exception
End Try
End Sub
You need to add a check for IsPostBack property of the page when you execute code in the Page_Load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
if Not PostBack Then
...... code to execute only the first time the Page_Load is called
Try
End Try
Catch ex As Exception
End Try
End If
.. code to execute every time....
End Sub
When your user clicks on a button with Runat=Server then the button calls the event on the server side code, but this cause a new call to Page_Load.
Actually your code reloads from the database the original value everytime the Page_Load event executes and thus your button click event code sees the original value from the database instead of the modified value.
This article on the Page Life Cycle could be useful here
In my VB.net ASP application, i have some ASPTREEVIEW where, on page load there is a Label, to which i set some value. After clicking on any row, i catch that value & assign it to the label.
But suddenly that label value is not updating by the chosen value. As if i check it via debugging the value, the value changes, but when i use Lable.text = chosen_value... It sets the value, but it is not actually changing on the html page. HTML shows the old value.
What will be the problem, i am not getting it.
Imports DevExpress
Imports DevExpress.Xpo
Imports DevExpress.Data
Imports DevExpress.Data.Filtering
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Public testvar As Integer = 35
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xpcol As New XPCollection(Of WCSOEE.WcsGCObject)
Dim GCObj1 As WCSOEE.WcsGCObject
Dim Filter1 As New DevExpress.XtraCharts.DataFilter
Dim SelectedGCObject As WCSOEE.WcsGCObject
Filter1.ColumnName = "Oid"
Filter1.Condition = XtraCharts.DataFilterCondition.Equal
Filter1.Value = Label2.Text
If Label2.Text = "" Then
Label2.Text = 10
End If
For Each Siris As DevExpress.XtraCharts.Series In WebChartControl1.Series
' WebChartControl1.Series(Siris.Name).DataFilters.Item(0).Value = CInt(Label2.Text)
Next
Dim masterKeyvalue As DevExpress.Web.ASPxTreeList.TreeListNode = ASPxTreeList1.FocusedNode
If masterKeyvalue IsNot Nothing Then
SelectedGCObject = masterKeyvalue.DataItem
Else
SelectedGCObject = xpcol.Object(31)
End If
' MsgBox(SelectedGCObject.GCName)
MsgBox(Label2.Text)
If IsPostBack = False Then
Label2.Text = calculatehours(SelectedGCObject.Oid)
End If
End Sub
Protected Function calculatehours(Oid As Integer)
xpocolLogAvailability.Session = DevExpress.Xpo.XpoDefault.Session
Dim logavail As New XPCollection(Of WCSOEE.LogAvailability)
Dim gcobjlist As New XPCollection(Of WCSOEE.WcsGCObject)
gcobjlist.Filter = CriteriaOperator.Parse("[Oid]=?", Oid)
Dim filter As CriteriaOperator
Dim ds As New DataTable
Dim Series As New DevExpress.XtraCharts.Series
Dim Filter1 As New DevExpress.XtraCharts.DataFilter
' Label2.Text = Oid
logavail.Filter = CriteriaOperator.Parse("GCObject.Oid=?", Oid)
Filter1.ColumnName = "Oid"
Filter1.Condition = XtraCharts.DataFilterCondition.Equal
Filter1.Value = Oid
Dim arr1(32) As Long
'For i As Int16 = 1 To 32
' arr1(i) = 0
'Next
'For Each gcobj As WCSOEE.LogAvailability In logavail
' arr1(gcobj.Status) = arr1(gcobj.Status) + gcobj.Duration
'Next= ""
'ds.Columns.Add(New DataColumn("Name", System.Type.GetType("System.Int32")))
For Each Siris As DevExpress.XtraCharts.Series In WebChartControl1.Series
WebChartControl1.Series(Siris.Name).DataFilters.Item(0).Value = Oid
Next
WebChartControl1.RefreshData()
'For i As Int16 = 1 To 32
' ds.Rows.Add(i, arr1(i))
'Next
'ASPxListBox1.DataSource = ds
'ASPxListBox1.DataBind()
Return Oid
End Function
Protected Sub ASPxTreeList1_CustomCallback(sender As Object, e As DevExpress.Web.ASPxTreeList.TreeListCustomCallbackEventArgs) Handles ASPxTreeList1.CustomCallback
End Sub
Protected Sub ASPxTreeList1_FocusedNodeChanged(sender As Object, e As System.EventArgs) Handles ASPxTreeList1.FocusedNodeChanged
Dim masterKeyvalue As DevExpress.Web.ASPxTreeList.TreeListNode = ASPxTreeList1.FocusedNode
Dim SelectedGCObject As WCSOEE.WcsGCObject = masterKeyvalue.DataItem
' MsgBox(SelectedGCObject.GCName)
If IsPostBack Then
Label2.Text = calculatehours(SelectedGCObject.Oid)
End If
MsgBox(IsPostBack)
MsgBox(Label2.Text)
End Sub
End Class
Post some code so we can see exactly what your doing, without seeing anything so far ensure you have an If statement in your page load to only apply the label text if the current request is not a postback other wise the the label will be set to this on every request.
If Not IsPostBack() Then
lblSomeLabel.Text = "Page load text"
End If
After the DetailsView is updated and clicked the Update Command button on the DetailView; I want to set one of the fields to “Complete”. What am I doing wrong here? Pls. help.
here is my code behind:
Protected Sub Test(sender As Object, e As System.Web.UI.WebControls.DetailsViewUpdatedEventArgs) Handles DetailsView1.ItemUpdated
If IsPostBack Then
Dim TextBox7 As TextBox = TryCast(DetailsView1.Rows(0).Cells(0).FindControl("TextBox7"), TextBox)
TextBox7.Text = "Complete"
End If
End Sub
I have used this method and got it to work.
Protected Sub PageDetailsView_ItemCommand(sender As Object, e As DetailsViewCommandEventArgs)
If Me.PageDetailsView.DefaultMode = DetailsViewMode.[ReadOnly] Then
If e.CommandName.Equals("GenerateModifiedDate", StringComparison.CurrentCultureIgnoreCase) Then
Dim modifiedDateLabel As Label = TryCast(Me.PageDetailsView.FindControl("ModifiedDateLabel"), Label)
modifiedDateLabel.Text = DateTime.Now.ToString()
End If
Else
If e.CommandName.Equals("GenerateModifiedDate", StringComparison.CurrentCultureIgnoreCase) Then
Dim modifiedDateTextbox As TextBox = TryCast(Me.PageDetailsView.FindControl("ModifiedDateTextbox"), TextBox)
modifiedDateTextbox.Text = DateTime.Now.ToString()
End If
End If
End Sub