Updating in an editable gridview once it has been displayed after the updatepanel it is in has been made visible by the user - vb.net

I have been searching forums and trying to solve this for a few days now but I'm stuck. Apologies if this is something so simple and obvious that I have missed. Although I have found posts similar to my issue, they are not quite the same.
Here is the outline of what my Web app partly does:
shows a simple asp:dropdownlist
When the user selects a value, the appropriate updatepanel is made visible (these update panels are visible = false in the Page_Load code behind), showing an editable gridview:
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
If DropDownList1.SelectedItem.Value <> "0" Then
If DropDownList1.SelectedValue = "Activate or Inactivate Users" Then
UpdatePanel1.Visible = True
End If
...
<asp:GridView ID="GridView3" runat="server" AllowSorting="True" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="iMemberId" HeaderText="iMemberId" InsertVisible="False" ReadOnly="True" SortExpression="iMemberId" />
<asp:BoundField DataField="sFname" HeaderText="sFname" SortExpression="sFname" />
<asp:BoundField DataField="sSname" HeaderText="sSname" SortExpression="sSname" />
<asp:BoundField DataField="dDateCreated" HeaderText="dDateCreated" SortExpression="dDateCreated" />
<asp:BoundField DataField="sEmailAddress" HeaderText="sEmailAddress" SortExpression="sEmailAddress" />
<asp:BoundField DataField="sMobileNo" HeaderText="sMobileNo" SortExpression="sMobileNo" />
<asp:CheckBoxField DataField="bActiveMember" HeaderText="bActiveMember" SortExpression="bActiveMember" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" Runat="server" ConnectionString="<%$ ConnectionStrings:PTCCHomeTestConnectionString %>" SelectCommand="SELECT * FROM [MemberTable] ORDER BY [sSname]"
UpdateCommand="UPDATE MemberTable SET sFname = #sFname, sSname = #sSname, sEmailAddress = #sEmailAddress, sMobileNo =, bActiveMember = WHERE (iMemberId = #iMemberId)">
<UpdateParameters>
<asp:Parameter Name="sFname" />
<asp:Parameter Name="sSname" />
<asp:Parameter Name="sEmailAddress" />
<asp:Parameter Name="iMemberId" />
</UpdateParameters>
</asp:SqlDataSource>
</ContentTemplate>
Each gridview's select and update queries have been tested and work fine. I have tested the gridviews in a page where they are all visible ( and it all works fine, but I would like to have the only the appropriate gridview visible depending on which one the user selects from the dropdown list.
The user should then be able to click Edit on a chosen row and update it. The gridview displays fine, properly populated, but when the user clicks on the Edit (to update) link in a row I get the error:
"Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page...
Stack Trace:
[ArgumentException: Invalid postback or callback argument. Event validation is enabled using in configuration or 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.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +144
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +111
System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +32
System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +9643314
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929"`
I have tried the following (but still the same error):
I added a Render sub that registers all the values from the select and update for event validation:
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
'override (page) Render and loop over the GridView Rows
Dim row As GridViewRow
For Each row In GridView3.Rows
If (row.RowType = DataControlRowType.DataRow) Then
Page.ClientScript.RegisterForEventValidation(New System.Web.UI.PostBackOptions(Me.GridView3, "Select$" + row.RowIndex.ToString()))
Page.ClientScript.RegisterForEventValidation(New System.Web.UI.PostBackOptions(Me.GridView3, "Update$" + row.RowIndex.ToString()))
End If
Next
MyBase.Render(writer)
...
I also tried to rebind the gridview and datasource:
If Not (IsPostBack) Then
SqlDataSource2.DataBind()
GridView3.DataBind()
End If
I have also tried to add the EnableEventValidation="false" in the Page tag. What happens is that I now can press the Edit link but then the UpdatePanel disappears (as per the Page_Load) and when I then select the value from the dropdown list it appears again with the row in Edit mode, but with blanks instead of the row's current values.
I also tried defining the datasource of the gridview outside of the same updatePanel that the gridview is in but that did not make any difference.
Just to confirm, if I don't make the UpdatePanels visible=false in the Page_Load code so the user can see all of them then the gridviews work fine with updating rows. This makes me think that the issue lies with the statelessness as if I understand correctly, when an Edit link is pressed the Page_Load code is called again and the dropdownlistvalue is no longer held, thus making the updatepanel which the gridview is in visible=false again.
So, is there any other way to make the updatepanels hidden depending on the dropdownlist selection that is not Page_Load? Could this be where a solution lies?
Or another way to have the dropdownlist chosen value persist after an Edit link (Page_Load call) is done?
I think that I'm sort of on the right track but it would be really helpful to get a little guidance.

Related

GridView.RowCommand Event

In the first column of a Gridview I am trying to place an image button that executes its own routine and opens another webform.
I understand that this should be arranged via an click-event, so I did search for examples the inet for solutions.
I found this in the books:
GridView.RowCommand Event Occurs when a button is clicked in a
GridView control.
The next code generate an error:
<asp:GridView ID="Grid" runat="server"
rowSelection="single"
AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" CellPadding="4" DataKeyNames="OID"
DataSourceID="SqlDataSource1"
ForeColor ="#333333" BorderColor="#CC9966" rderStyle="None"
BorderWidth="1px">
<AlternatingRowStyle BackColor="White"/>
<Columns>
<asp:ButtonField
commandname="Select"
ButtonType="Image"
ImageUrl ="~/Props/Pen.png"
onrowcommand="Pen_Click()"
/>
Error:
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Type 'System.Web.UI.WebControls.ButtonField' does not have a public property named 'onrowcommand'.
many regars,
Ton from Thailand
The onrowcommand belongs to the GridView itselt not the button.
<asp:gridview id="ContactsGridView"
onrowcommand="ContactsGridView_RowCommand"
runat="server">

How to get gridview clickable cell data value to new page aspx

I have two columns in a GridView where every cell of 1 column is hyperlinked.
<asp:GridView ID="gvBlogList" runat="server" DataKeyNames="Id"
AutoGenerateColumns="False" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLinkField DataTextField="id"
HeaderText="Blog id" NavigateUrl="detailspage.aspx" />
</ItemTemplate>
<ItemStyle Width="150px"></ItemStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
How can I get cell value in 2nd page as a session variable?
Thanks!
As per the what I understand from your question, you want to catch the value of the cell that is clicked, store it in session and make it accessible on the page that have redirect to. This is possible and you can try a flow like this :
You can use the GridView's inbuilt method onRowCommand in this case to generate a server side event and you can then identify which cell was clicked and lastly, you can get its value by index. The below code is a demonstration that you can try and manipulate as per your requirement. This is a sample where a Linkbutton is used in Gridview and on the click of it, its value is fetched.
You can also try to use the CommandName and CommandArgument properties if you want to assign that particular control a value that you may use at the server side.
protected void Grd1_RowCommand(object sender, GridViewCommandEventArgs e)
{
LinkButton lnk = (LinkButton)e.CommandSource;
string value = lnk.Text;
}
And for storing it in Session, you just have to make use of Session["yourVarName"] = value;. And this value can be accessed on the other page.
Hope this helps.

ASP.net VB Listbox

I've seen many questions around this one, but none hitting it directly.
I put a listbox on a page and populate it with three items from an Access database. I have a button on that page that will extract several values including the selected item from the listbox. Or I want to anyway.
I can see the item selected in windows (highlighted) when I click the button, but when I try to select it no item is available as selected in the listbox. The ListBox1.SelectedIndex is alway -1.
Here is the code from the page:
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem Text="List1" />
<asp:ListItem Text="List2" />
<asp:ListItem Text="List3" />
</asp:ListBox>
Is there a property missing?
Here is the code from the code behind page:
Public Function getDept() As String
Dim dept As String
If ListBox1.SelectedIndex > -1 Then
dept = ListBox1.SelectedItem.Text
Else
dept = "CMS"
End If
Return dept
End Function
Please help, I have until about noon to figure this out.
There may some reasons:
1- Check if your page's viewstate is true.
2- Call your method after Page_Load event.
Where do you call the function?
Consider that you should call it after Page_Load event. Also your viewstate

VB.net: Accessing data from DataList in Page_Load

New to VB.net, and trying to re-factor an 'old-skool' ASP page where all the page logic is happening on the .aspx page itself, to code-behind. Basically, I have a button that has a state, either on or off. If on, I set a hidden field to 1, if off, I set it to 0 (the default when a user visits the page).
The goal is to simply change the message I am sending to the user.
Have the following relevant code in MyPage.aspx:
<asp:HiddenField ID="hfldState" runat="server" Visible="false" Value="0" />
<div id="mainContent">
<asp:Literal ID="lblMessage" runat="server"
Visible="false" />
<asp:DataList ID="dlList" runat="server"
DataSourceID="sdsList"
DataKeyField="Entry No_"
RepeatLayout="Flow">
<ItemTemplate>
<div>
<asp:HyperLink ID="hlCurriculum" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Title") %>'
NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "File Path") %>'
ToolTip='<%# DataBinder.Eval(Container.DataItem, "Title") %>'
Target="_blank"
Style="font-weight: bold;">
</asp:HyperLink>
</div>
</ItemTemplate>
</asp:DataList>
</div>
<asp:SqlDataSource ID="sdsList" runat="server"
ConnectionString="..."
SelectCommand="SELECT [Entry No_], [Title], [File Path] FROM [Table] WHERE ([State] = #State)">
<SelectParameters>
<asp:ControlParameter ControlID="hfldState" Name="State" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
And the following in the Page_Load Sub:
If Page.IsPostBack Then
' Check for results
dlList.DataBind()
If dlList.Items.Count > 0 Then
' Results, display them
lblMessage.Text = "<h3>Results</h3>"
lblMessage.Visible = True
Else
' No results
lblMessage.Text = "<p>No Results</p>"
lblMessage.Visible = True
End If
Else
' user has not clicked anything
lblMessage.Text = "<p>Click button!</p>"
End If
The above code produces the following effect: when I click the button, setting the state to 1 and the page reloads, in Page_Load, I am getting zero results from the If dlList.Items.Count > 0 Then check, and thus am showing the 'No results' message, but the actual asp:DataList on the MyPage.aspx page is returning results... and then if I click the button again, setting it back to 0, in Page_Load, the datalist is now returning results, so I set the text to 'Results', but again, the control on the MyPage.aspx page behaves correctly, and shows no results, as expected. Now keep in mind that the above works perfectly in terms of checking the number of results if I move the If dlList.Items.Count > 0 Then page logic out of Page_Load and back to the MyPage.aspx file, it all works fine (i.e. results when state = 1, none when state = 0)
Any ideas?
I dont see a check in your page load for a postback:
If Not IsPostBack
'code
dList.DataBind() 'here is where you want to bind the data...
end if
The issue related to my ignorance of the page lifecycle in VB.net. Solution was to adjust the visibility of the asp:Literal, asp:DataList, set values etc in Page_PreRenderComplete. Basically, the asp:DataList wasn't being set in Page_Load, as expected, so doing any kind of logic in Page_Load based on the item count didn't make any sense.

LinqDataSource "OnSelecting" event not firing on Post-backs

I have a web page with two dropdownlist controls, each bound to separate LinqDataSource objects. One displays a list of Categories and the other displays a list of Articles. The Category choice drives Article list (at least, that's my intended behaviour). The Article list is also filtered based on the users language preference, stored in the Session and applied in the ArticleLinqDataSource_Selecting event handler.
<asp:Label runat="server" Text="Category Code:" AssociatedControlID="CategoryDropDownList" />
<asp:DropDownList runat="server" ID="CategoryDropDownList" DataSourceID="CategoryLinqDataSource" DataValueField="CategoryID" DataTextField="CategoryCode" AutoPostBack="true" />
...
<asp:Label runat="server" Text="Article Code:" AssociatedControlID="ArticleCodeDropDown" />
<asp:DropDownList runat="server" ID="ArticleCodeDropDown" DataSourceID="ArticleLinqDataSource" DataValueField="ArticleID" DataTextField="ArticleCode" OnDataBound="ArticleCodeDropDown_DataBound" />
...
<asp:LinqDataSource runat="server" ID="CategoryLinqDataSource"
ContextTypeName="Article.Data.ArticleDataContext"
TableName="Categories" Select="new (CategoryID, CategoryCode)">
</asp:LinqDataSource>
...
<asp:LinqDataSource runat="server" ID="ArticleLinqDataSource"
ContextTypeName="Arcicle.Data.ArticleDataContext"
TableName="Articles" OrderBy="ArticleCode"
Select="new (ArticleID, ArticleCode)"
OnSelecting="ArticleLinqDataSource_Selecting">
</asp:LinqDataSource>
This all works fine when the page first loads. The Category list contains the all the available category values, and the first category in the list is selected. And the corresponding Articles for the first category are displayed appropriately in the Article dropdown control. However, when I change the category (a post-back happens because I have it set to AutoPostBack="true", the Article dropdown does not get refreshed. In other words, the OnSelecting event is not getting fired on subsequent postbacks. Is this the expected bahaviour? If it is, how do I get around this?
You need to call DataBind on the DropDownList in the CategoryDropDownList's SelectedIndexChanged event. It doesn't happen on its own.
e.g.
Protected Sub CategoryDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CategoryDropDownList.SelectedIndexChanged
ArticleCodeDropDown.DataBind()
End Sub