LinqDataSource "OnSelecting" event not firing on Post-backs - linqdatasource

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

Related

Find Radiobutton Control from ID String in vb.net

I have 3 radiobuttons in my aspx:
<asp:RadioButton ID="rdoMasculin"
runat="server" AutoPostBack="true"
Checked="true" GroupName="gender"
TextAlign="Right" />
<asp:RadioButton ID="rdoFeminin"
runat="server" AutoPostBack="true"
GroupName="gender" />
<asp:RadioButton ID="rdoAnonymous"
runat="server" AutoPostBack="true"
GroupName="gender" />
When sending the form I'm storing the ID of the checked radiobutton in a Session variable:
for example: Session("currentGender") = rdoZukuTermine.ID
When I'm getting back on the page in a later stage I'm using the following code in codebehind:
Dim currentRadio = CType(FindControl(Session("currentGender")), RadioButton)
currentRadio.Checked = True
Session.Remove("currentGender")
currentRadio ends up as a null reference. But when I'm checking the Session it contains the right ID as a string.
Can someone help me?
Is the RadioButton control directly in your .aspx or does it have any parent controls? if yes call Findcontrol() on it direct parent like this:
Dim currentRadio = CType(ParentControl.FindControl(Session("currentGender")), RadioButton)

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

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

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.

Making asp:Label a specific HTML tag

New to VB.net, just trying to figure out how to properly manipulate the asp:Label control.
I have a page that, based on if there are results, etc should display an <h1></h1> tag with a header, then the data. As I am using the code-behind model, my user facing page essentially just has the following:
<asp:Label ID="lblMessage" runat="server"
Visible="false" />
<asp:DataList ID="dlCurriculumLists" runat="server"
DataSourceID="sdsCurriculumLists"
DataKeyField="Entry No_"
RepeatLayout="Flow"
Visible="false">
<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>
On my code-behind page, I then set the asp:Label and asp:DataList to Visible="true" based on the data from the database. Here's the catch - if there is data, I want to set lblMessage to be an H1, and if not, just standard Label text. I realize I can emulate the look through the CSS, but was just hoping there was another way (maybe similar to the ItemTemplate concept) to specify the HTML type of the Label control - it appears to be a by default.
For people coming from a VB background, it's a common mistake to think that the most basic control for displaying arbitary text is a Label.
That's not true. A label should label something, usually another UI control (that's what the AssociatedControlId property is for).
If you just want to display arbitrary text or HTML markup, use something more basic instead. Some examples are asp:Literal, asp:Placeholder or asp:Localize.
Using, for example, an asp:Literal called myLiteral, you can easily create a heading in code:
myLiteral.Text = "<h1>" & Server.HtmlEncode(myHeading) & "</h1>"
As far as I know, the asp:Label component will always generate a <label> HTML tag when its AssociatedControlId attribute is set.
What you could do instead is use a Literal Control and populate it with the HTML you wish at runtime.
UPDATE
One thing you could do to make this work as required using your current Label control is to have a theme for the label that marks it up as a H1. You could then toggle the controls EnableTheming property as required.
Aside from what already has been suggested here, you can also implement your own ASP.NET control with any properties you want, then modify its rendering on the fly, depending on the properties' values. It is pretty fun to do and is not as hard as one might think. Here is some information on the subject: http://msdn.microsoft.com/en-us/library/vstudio/zt27tfhy(v=vs.100).aspx