Why am I getting "Invalid postback or callback argument"? - asp.net

To explain my situation...
I am filling a listbox from a mysql table liek this
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim cmdtext = "SELECT * FROM avail_workouts"
Using conn = New MySqlConnection(connString)
Using cmd = New MySqlCommand(cmdtext, conn)
conn.Open()
reader = cmd.ExecuteReader()
While reader.Read()
ListBox1.Items.Add(reader("workout"))
End While
End Using
End Using
End Sub
I then select one of the items on the listbox and click on a button (that will do something with the value selected from the listbox) that does nothing for now. That's when I get this error
Invalid postback or callback argument.
Event validation is enabled using <pages enableEventValidation="true"/>
in configuration or <%# Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that
arguments to postback or callback events originate
from the server control that originally rendered them.
If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation
method in order to register the postback or callback data for validation.
I tried using
EnableEventValidation="false"
This seemed to work, until I tried to use the selected value in the listbox. It seems to forget the value that is selected when I click on the button. So, how can I simply fill up a listbox, select a row in the listbox, and click a button where the selected value will be used without getting this error?
Thanks in advance!

include this lines...
If Not IsPostBack
//your code
End If

Related

ASP.Net Repeater: Checkboxes checked status not persisting on form submission

I have a Repeater of checkboxes bound in code-behind:
<asp:Repeater runat="server" ID="rptOpenJobs" OnItemDataBound="rptOpenJobs_ItemDataBound">
<ItemTemplate>
<asp:CheckBoxList ID="lstOpen" runat="server"></asp:CheckBoxList>
</ContentTemplate>
</asp:Repeater>
Code-behind (VB.Net):
Protected Sub rptOpenJobs_ItemDataBound(sender As Object, e As RepeaterItemEventArgs)
Dim jobsTable As New DataTable
Dim conn As String = "[hidden]" 'Connection String to retrieve data table values
If e.Item.ItemType.Equals(ListItemType.AlternatingItem) Or e.Item.ItemType.Equals(ListItemType.Item) Then
Dim cboxlist As CheckBoxList = e.Item.FindControl("lstOpen")
If cboxlist.Items.Count = 0 Then
cboxlist.DataSource = jobsTable
cboxlist.DataTextField = "job_title"
cboxlist.DataValueField = "job_title"
cboxlist.DataBind()
End If
End If
End Sub
On form submission, the checked boxes do not stay checked. I've looked for solutions but haven't found any where the list is databound in code-behind.
I've tried adding an UpdatePanel around the repeater and around the CheckBoxList but the checked state still will not persist on form submission.
What does you page load event look like?
You ONLY load things up the first time in the If IsPostBack = False code stub.
99% if not 100% of your pages will ahve that code block. For me, comming from say Access, VB6, vb.net? Well a form loads, and we have the form load event.
but, any old button click on that page ALSO triggers a post back, and the on load event will run EVERY time (and then the button click or whatever event code will run).
So, all web pages look like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' the REAL first time load event!!!
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using cmdSQL As New SqlCommand("SELECT ID, FirstName, LastName, HotelName, City from tblHotels",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
GridView1.DataSource = cmdSQL.ExecuteReader
GridView1.DataBind()
End Using
End Sub
So note how we have that first page load event - we load up a grid. But if we do NOT put that code inside of of the IsPostBack = False part, then our setup code and our load code will run every time on a full page post back.
Your check boxes as you have should persist for you, and should survive a page post back.
I don't see where (how) you persisted the jobs table, but ONCE the repeater is loaded, they should survive a post back. I mean, the data bound event only triggers if you are re-binding the repeater. but, if you are say due to adding new rows or some such, and you do trigger (need/want) a databind event again, then that jobsTable does need to exist and be persisted if you do re-bind the repeater.
So, in your code, you have on page load, we load up the Repeater. Above code would be the same, eg this:
And since the table is used OVER and OVER for each item data bound event, then we should NOT re-pull the table each time in the item data bound event. We should setup (load) that table one time in our LoadGrid routine.
So, at the page level class, we will declarer a table variable scoped to the form/page level. This will persist long enough during each item bind event for the repeater to fill out the check box list.
We assume that you have a data source for hte repeter - it will repeat many times. And for EACH repeater, we have a checkbox list that ALSO has a set of values that we want to fill from the check box list of choices.
It is NOT 100% clear if each new check box list is to be driven from ONE table, and each repeated row of course does have a value from the table for each row of the repeating list that represents the chosen check box value.
Or, is the list of check box values for each repeated item different? This issue has to be cleared up.
Clear this last issue up for me, and I post more code as to how this can work.
Sub LoadGrid()
Using cmdSQL As New SqlCommand("SELECT ID, FirstName, LastName, HotelName, City from tblHotels",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
rptOpenJobs.DataSource = cmdSQL.ExecuteReader
rptOpenJobs.DataBind()
End Using
End Sub

Gridview data not refreshing

I have a gridview which has a List (Of MyObject) as its datasource.
gv.DataSource = MyListObject
gv.Databind()
Under a templatefield i have a button configured to delete a record from MyListObject and then rebind it. To add a record i have the below code
Protected Sub btnAddRecord_Click(sender As Object, e As EventArgs) Handles btnAddRecord.Click
Dim Customer As New Customer
With Customer
.Name = txtName.Text
.Surname = txtSurname.Text
.....
.ID += MyListObject.Count
End With
MyListObject.Add(Customer)
gv.DataSource = MyListObject
gv.DataBind()
End Sub
This works fine, but then i need to allow the user to delete a record if need be:
Private Sub gv_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
If e.CommandName = "Delete" Then
MyListObject.RemoveAt(e.CommandArgument)
gv.DataSource = Nothing
gv.DataBind()
gv.DataSource = MyObjectList
gv.DataBind()
upnl.UpdateMode = UpdatePanelUpdateMode.Conditional
upnl.Update()
End If
End Sub
When i click the button it deletes the record but doesnt refresh the data. By that i mean when the record is added i am assigning the ID as a row ID and then use that ID to remove the record. Since the List and Gridview values are now out of sync i set the datasource to nothing and rebind it in order that i was going to have the values reset and the ID would be the correct one - but this doesnt works as i expected.
Could anyone advise where im going wrong and how to correct this problem?
Is gridview in the updatepanel? If yes, that panel should also be refreshed.
I added CommandArgument='<%# Container.DataItemIndex %>' which resolved the issue as i was then deleting the row the user clicked against.
Just as a side note, I'd probably handle what get's updated when on the client side using the ajax script manager rather than doing it in the code behind. Saves headaches. The above might be updating the update panel correctly, but the ajax plumbing may not be there on the client side.

VB. NET ASPX: find controls triggers and call it dynamically

I am looking for a way, that knowing a controls name, to raise them or call the processes event/code behind.
I am using VB .NET in VS2010
I have an aspx page with a selection of checkboxes in a panel, each checkbox has its own trigger. I have code that saves a list of checked checkboxes. I have code that restores the checked states to those checkboxes, but I need to execute the associated code to the checkboxes checkchanged event.
' Read db to get saved list of checkboxes '
For each result from db
Dim cb As CheckBox
cb = 'a function that finds and returns the control'
' Now that I have the control,
' how can I find and execute it's checkedchanged code?
The control return function is working because in testing, I can process cb.checked = true, and the cb becomes checked, but this doesn't raise the event/trigger the code.
Example of associated checkedchanged subs:
Protected Sub cb_use_rc3_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cb_use_rc3.CheckedChanged
Protected Sub cb_use_casestatus_CheckedChanged(sender As Object, e As EventArgs) Handles cb_use_casestatus.CheckedChanged
Any ideas?
For Each grd_Row As GridViewRow In gvPersonalInventario.Rows
Dim cb As New Web.UI.WebControls.CheckBox
cb = grd_Row.FindControl("CheckBox2")
If cb.Checked = True Then
label1.text = grd_Row.Cells(0).Text
End If
Next
OK, I'm working on the assumption that your checkboxes each have an individual ID and are not generated by a bound control of any sort.
While it is possible to determine what handler is hooked up to what event of what object (or so I understand), it's probably more trouble than it's worth for this limited case.
The simplest, though ugliest, way to do it would be this:
Follow Mr. Schmelter's advice and isolate the business logic in meaningfully-named methods. Call them from each event handler rather than putting all the logic in the event handler.
Since you have the control, you can determine its ID. Use a Select Case statement with the ID of the control to determine which method or methods from #1 to call.

Filling the dropdown from sql bug

Good afternoon people have been trying to fill a dropdown using a sql command, until so good, when I click on the dropdown it shows all the items, but when I try to click on an item in the dropdown it always returns the first item in the dropdown .... follows the codes, what i want to do is get the selected value and item from the dropdown and save it on a label for future use.
I appreciate all the support possible,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
utilizador.Text = Me.Context.User.Identity.Name
If (Not Page.IsPostBack) Then
escolhePerfil()
End If
'DropDownPerfil.DataBind()
lbperfil2.Text = DropDownPerfil.SelectedItem.Text
lbnome.Text = DropDownPerfil.SelectedValue
End Sub
Function escolhePerfil() As Boolean
Dim connstring As String = "Data Source=10.2.24.17;Persist Security Info=True;User ID=sa;Password=Pr0dUn1C0$qL;database=ePrimavera"
Dim SQLData As New System.Data.SqlClient.SqlConnection(connstring)
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT u.WindowsUser,u.Email ,g.Description, u.Login FROM [ePrimavera].[dbo].[PLT_Users] as u,[ePrimavera].[dbo].[PLT_UserGroups] as ug, [ePrimavera].[dbo].[PLT_Groups] as g where u.ID = ug.UserID And ug.GroupID = g.ID and u.WindowsUser like 'bancounico\" & utilizador.Text & "'", SQLData)
SQLData.Open()
Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
If dtrReader.HasRows Then
DropDownPerfil.DataValueField = "Login"
DropDownPerfil.DataTextField = "Description"
DropDownPerfil.DataSource = dtrReader
DropDownPerfil.DataBind()
End If
SQLData.Close()
Return True
End Function
.aspx
<asp:DropDownList ID="DropDownPerfil" runat="server"
Height="16px" Width="202px" CssClass="DropBorderColor">
</asp:DropDownList>
try the following code:
Protected Sub DropDownPerfil_SelectedIndexChanged(sender As Object, e As EventArgs)
lbperfil2.Text = DropDownPerfil.SelectedItem.Text
lbnome.Text = DropDownPerfil.SelectedValue
End Sub
The problem is that you are trying to get the value "too early". The value is not valid in the Page_Load, since the control's OnLoad event fired after the Page's OnLoad (Page_Load) event.
The way, what the others wrote the correct, since the Event handlig section (inclueding control's onchanged event) will process after the Load section.
For more details check the offical ASP.NET life cycle site in the MSDN
The likely reason is that some (if not all) the values you are assigning to the DropDownList for Login are occur more than once.
When you then select an item in the DDL, if the value of that item occurs more than once, the selected index will highlight the first instance. To test this, comment out DropDownPerfil.DataValueField = "Login"
I am sure upon selection, it will highlight the correct item you intended on selecting.

Why I got this exception :Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback or callback argument

Why I got this error
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
this error appears when the event for Save command is started
Protected Sub DataList1_ItemCommand(source As Object, e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles dlMainTraing.ItemCommand
If e.CommandName = "Save" Then
Dim lblMainId = CType(dlMainTraing.Items(e.Item.ItemIndex).FindControl("Train_M_IndxLabel"), Label)
Dim txtSubTrainingName2 = CType(dlMainTraing.Items(e.Item.ItemIndex).FindControl("txtSubTrainingName"), TextBox)
Dim a = addSubTraining(CInt(lblMainId.Text), txtSubTrainingName2.Text)
' Dim gvSubTraning As GridView = CType(e.Item.FindControl("gvSubTraning"), GridView)
'gvSubTraning.DataBind()
End If
End Sub
At the top of your .aspx page, set EnableEventValidation to false.

Resources