Linq Edit ListView - asp.net

im trying to edit a field using code instead of the wizard. im not entirely sure if the code i have is correct to update the field. here is the code i have to edit the field:
Protected Sub ListView1_ItemEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewEditEventArgs) Handles ListView1.ItemEditing
ListView1.EditIndex = e.NewEditIndex
ListView1.DataBind()
End Sub
Protected Sub ListView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewUpdateEventArgs) Handles ListView1.ItemUpdating
Dim profile = Request.QueryString("Profile")
Dim postid As Label = DirectCast(ListView1.EditItem.FindControl("postId"), Label)
Dim textbox As TextBox = DirectCast(ListView1.EditItem.FindControl("EditPostTxt"), TextBox)
Dim getComment = (From p In db.Posts Where p.PostId = New Guid(postid.Text)).Single
getComment.Post = cc.reverseExchangeSmilies(textbox.Text)
db.SubmitChanges()
ListView1.EditIndex = -1
cc.LoadComments(profile, ListView1)
End Sub
when ever i try to ether update or cancel the post because the post contains html i get the following error:
A potentially dangerous Request.Form value was detected from the client
i was wondering if before it updated the post it could use the reverseExchangeSmilies to turn them back in to smiles instead of there html or maybe allow html to be used at this point.
aspx page:
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<div id="header">
<asp:HyperLink ID="UserPageLik" runat="server" NavigateUrl='<%#"Default.aspx?Profile=" + Eval("ProfileId") %>'> <%# Eval("fullname")%> </asp:HyperLink><br />
</div>
<div id="leftcolumn">
<asp:ImageButton ID="Image1" runat="server" ImageUrl='<%#Eval("DisaplyPictureSmall") %>' /></div>
<div id="content">
<asp:Label ID="Label4" runat="server" Text='<%#Eval("Post") %>'></asp:Label><br />
</div>
<div id="footer">
<%# Eval("Date")%><br />
<asp:linkbutton id="linkbutton1" runat="server" CommandName="del" CommandArgument='<%# Eval("PostId") %>' forecolor="red" text="Delete" onclientclick="return confirm('Are you sure?');" />
<asp:linkbutton id="linkbutton2" runat="server" CommandName="Edit" CommandArgument='<%# Eval("PostId") %>' forecolor="red" text="Edit" />
</div>
<br />
</ItemTemplate>
<EditItemTemplate>
<div id="header">
<asp:Label ID="postId" runat="server" Text='<%#Eval("PostId") %>'></asp:Label>
<asp:HyperLink ID="UserPageLik" runat="server" NavigateUrl='<%#"Default.aspx?Profile=" + Eval("ProfileId") %>'> <%# Eval("fullname")%> </asp:HyperLink><br />
</div>
<div id="leftcolumn">
<asp:ImageButton ID="Image1" runat="server" ImageUrl='<%#Eval("DisaplyPictureSmall") %>' /></div>
<div id="content">
<asp:TextBox ID="EditPostTxt" runat="server" Text='<%#Eval("Post") %>' Width="100%" TextMode="MultiLine"></asp:TextBox>
</div>
<div id="footer">
<%# Eval("Date")%><br />
<asp:linkbutton id="SaveEditBut" runat="server" CommandName="Update" CommandArgument='<%# Eval("PostId") %>' forecolor="red" text="Update" />
<asp:linkbutton id="Linkbutton3" runat="server" CommandName="Cancel" CommandArgument='<%# Eval("PostId") %>' forecolor="red" text="Cancel" />
</div>
<br />
</EditItemTemplate>
</asp:ListView>
Thanks in advance.

The framework is preventing you from posting html code as a security measure. This can be turned off for the current page by adding a page directive.
<%# Page validateRequest="false" %>
The other option is to use javascript on the client side to change '<' to < and '>' to > and '&' to & before posting. Then on the server side you could decode the html before writing it to the screen.
function encodeValue(element_id)
{
var elem = document.getElementById(element_id);
var html = elem.value;
html= html.replace(/&/gi,"&");
html= html.replace(/</gi,"<");
html= html.replace(/>/gi,">");
elem.value = html;
}

Related

Repeater Autopostback Textbox Focus Position issue

I have a repeater control that contains a Textbox within an UpdatePanel, as well as other controls. The repeater fetches data from an SQL database and when the user makes changes to this specific textbox, the OnTextChange event is fired when the user "tabs out" of the text box. This event triggers a Stored Procedure code to update the databse with the new values in the textbox. The functionality I'd like to implement is when the user tabs out of the text box, the next text box in the repeater row should be focused on for continuous editing (similar to an excel spreadsheet) after the AutoPostBack from the OnTextChange event is fired. Would anyone have an example on how to do this using the code i have provided below? Thank you in advance!
Form Markup:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Repeater ID="GradeEditor" runat="server">
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server" Width="100%" Height="100%">
<table style="width:100%;">
<tr>
<td>
<asp:Label ID="LateLabel" runat="server" CssClass="label label-success" Visible="False"></asp:Label>
</td>
<td> </td>
</tr>
<tr>
<td colspan="2">
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" BackColor="Transparent" BorderColor="Transparent" OnTextChanged="Grade_TextChanged" style="text-align: center" Text='<%# Bind("Grade_Code") %>' Width="100%"></asp:TextBox>
</td>
</tr>
</table>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("ID") %>' Visible="False"></asp:Label>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("ID") %>' />
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# Bind("Class_ID") %>' />
<asp:HiddenField ID="HiddenField3" runat="server" Value='<%# Bind("Assignment_ID") %>' />
<asp:HiddenField ID="HiddenField4" runat="server" Value='<%# Bind("Student_ID") %>' />
<asp:HiddenField ID="HiddenField5" runat="server" Value='<%# Bind("Exempt") %>' />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:Repeater>
Code Behind for Update:
Protected Sub Grade_TextChanged(sender As Object, e As EventArgs)
'Find the reference of the Repeater Item.
Dim ScoreText As TextBox = CType(sender, TextBox)
Dim item As RepeaterItem = CType(ScoreText.NamingContainer, RepeaterItem)
Dim ScoreID As Integer = Integer.Parse(TryCast(item.FindControl("HiddenField1"), HiddenField).Value)
Dim ClassID As Integer = TryCast(item.FindControl("HiddenField2"), HiddenField).Value.Trim()
Dim AssignmentID As String = TryCast(item.FindControl("HiddenField3"), HiddenField).Value.Trim()
Dim StudentID As String = TryCast(item.FindControl("HiddenField4"), HiddenField).Value.Trim()
Dim Grade As String = TryCast(item.FindControl("TextBox1"), TextBox).Text
Dim constr As String = ConfigurationManager.ConnectionStrings("AthenaConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Scores_CRUD")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Action", "UPDATE")
cmd.Parameters.AddWithValue("#Score", Grade)
cmd.Parameters.AddWithValue("#ScoreID", ScoreID)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Me.BindRepeater()
End Sub
You have an issue in your markup with UpdatePanel. The UpdatePanel should have the Repeater control within its ContentTemplate as in markup below.
Change your code to as given below.
Correct Markup
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:Repeater ID="GradeEditor" runat="server">
<ItemTemplate>
<asp:Panel ID="Panel1" runat="server" Width="100%" Height="100%">
<table style="width:100%;">
<tr>
<td>
<asp:Label ID="LateLabel" runat="server" CssClass="label label-success" Visible="False"></asp:Label>
</td>
<td> </td>
</tr>
<tr>
<td colspan="2">
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" BackColor="Transparent" BorderColor="Transparent" OnTextChanged="Grade_TextChanged" style="text-align: center" Text='<%# Bind("Grade_Code") %>' Width="100%"></asp:TextBox>
</td>
</tr>
</table>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("ID") %>' Visible="False"></asp:Label>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("ID") %>' />
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# Bind("Class_ID") %>' />
<asp:HiddenField ID="HiddenField3" runat="server" Value='<%# Bind("Assignment_ID") %>' />
<asp:HiddenField ID="HiddenField4" runat="server" Value='<%# Bind("Student_ID") %>' />
<asp:HiddenField ID="HiddenField5" runat="server" Value='<%# Bind("Exempt") %>' />
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Then, you need to emit JavaScript for focusing the next textbox from the text changed event of textbox in Repeater. This can be done using C# code as below.
Text changed event C# code for focusing the next box
protected void Grade_TextChanged(object sender, EventArgs e) {
//PUT your original code for calling stored procedure here
TextBox textBox = sender as TextBox;
BindRepeater();
RepeaterItem currentRepeaterItem = (RepeaterItem)(textBox.NamingContainer);
int currentRepeaterItemIndex = currentRepeaterItem.ItemIndex;
RepeaterItem nextRepeaterItem = null;
//get the next item row of Repeater
if ((rptCustomers.Items.Count - 1) >= (currentRepeaterItemIndex + 1)) {
nextRepeaterItem = GradeEditor.Items[currentRepeaterItemIndex + 1];
}
if (nextRepeaterItem != null) {
//get the textbox in next row of Repeater
TextBox nextTextBox = nextRepeaterItem.FindControl("TextBox1") as TextBox;
//emit JavasSript to focus the next textbox
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "focusnext", String.Format(" var nextTextBox = document.getElementById('{0}'); nextTextBox.focus(); nextTextBox.select();", nextTextBox.ClientID), true);
}
}

FormView ItemUpdating e.oldValues and e.NewValues seems null

I have a FormView on a page in my asp.net 4.5 VB application. I have a FileUpload in EditItemTemplate and InsertItemTemplate of my FormView. InsertItemTemplate works fine as expected. I want my FormView to:
Insert values into SQL DB, and save the file into the file system and save its name into DB (Which it does as expected).
Update DB and the file system by replacing the old values and with new ones (this is OK too.) and previous file of the row with the new file (This is OK too) and Delete the old file... (NOT OK!)
Keep the previous file name in DB if FileUpload has no file.(NOT OK!) records NULL if is empty.
Delete record from db along with the file associated (This is OK too.)
FormView:
<asp:FormView ID="FormView1" runat="server" AllowPaging="True" DataKeyNames="KurumId" DataSourceID="KurumlarDS" Width="500px">
<EditItemTemplate>
KurumId:
<asp:Label ID="KurumIdLabel1" runat="server" Text='<%# Eval("KurumId") %>' />
<br />
KurumAdi:
<asp:TextBox ID="KurumAdiTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumAdi") %>' />
<br />
KurumLogoPath:
<%--<img runat="server" ID="imgKurumLogo" src='<%# Eval("KurumLogoPath", "../images/kurum/{0}?w=80")%>' alt="Kurum Logosu" />
<br />--%>
<asp:FileUpload ID="KurumLogoPathFUU" runat="server" />
<br />
KurumTelefon:
<asp:TextBox ID="KurumTelefonTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumTelefon") %>' />
<br />
KurumBelgeGecer:
<asp:TextBox ID="KurumBelgeGecerTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumBelgeGecer") %>' />
<br />
KurumWebAdresi:
<asp:TextBox ID="KurumWebAdresiTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumWebAdresi") %>' />
<br />
KurumEMail:
<asp:TextBox ID="KurumEMailTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumEMail") %>' />
<br />
KurumTarihce:
<asp:TextBox ID="KurumTarihceTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumTarihce") %>' />
<br />
KurumRengi:
<asp:TextBox ID="KurumRengiTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumRengi") %>' />
<br />
KurumAdres:
<asp:TextBox ID="KurumAdresTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumAdres") %>' TextMode="MultiLine" />
<br />
KurumSortExpression:
<asp:TextBox ID="KurumSortExpressionTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumSortExpression") %>' />
<br />
KurumLat:
<asp:TextBox ID="KurumLatTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumLat") %>' />
<br />
KurumLon:
<asp:TextBox ID="KurumLonTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumLon") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Güncelle" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Vazgeç" />
</EditItemTemplate>
<InsertItemTemplate>
</InsertItemTemplate>
<ItemTemplate>
</ItemTemplate>
<PagerSettings Mode="NumericFirstLast" Position="TopAndBottom" />
Related CodeBehind:
Private Sub FormView1_ItemUpdating(sender As Object, e As FormViewUpdateEventArgs) Handles FormView1.ItemUpdating
Dim fu As FileUpload = CType(FormView1.FindControl("KurumLogoPathFUU"), FileUpload)
Dim MyPath As String = Server.MapPath("~/images/kurum/")
Dim fName As String = fu.FileName
Dim FullPathedFile As String = MyPath & fName
Try
If fu.HasFile = True Then
Dim oldName As String = e.OldValues("KurumLogoPath")
Dim newName As String = e.NewValues("KurumLogoPath")
If File.Exists(MyPath & oldName) Then
File.Delete(MyPath & oldName)
End If
e.NewValues("KurumLogoPath") = fName
fu.SaveAs(FullPathedFile)
Else
e.NewValues("KurumLogoPath") = e.OldValues("KurumLogoPath")
End If
Catch ex As Exception
Response.Write("Cannot Update!" & ex.Message())
e.Cancel = True
End Try
End Sub
I can see MyPath but not e.NewValues("KurumLogoPath") or e.OldValues("KurumLogoPath") I also tried e.NewValues.Item("KurumLogoPath") and e.NewValues.Item("KurumLogoPath") with no success. So I think that all e.OldValues and e.NewValues are null.. Thus file.delete tries to delete C:\inetpub\wwwroot\WebApp1\images\kurum instead of C:\inetpub\wwwroot\WebApp1\images\kurum\oldfile.jpg as a result deletes nothing.
I have checked permissions for the folder and Application, they are OK. I have googled, binged, yahooed, trialed & errored with no success. It's been about two days now that I am on this :(
What am I doing wrong? Any ideas?
Thanks in advance.
After causita's comment I used index for the values. It worked for all columns except for KurumLogoPath column. While trying to find that columns index I realized that no index number was related to KurumLogoPath column. Then I realized indices are coming from <%# Bind("ColumName") %> statements.. But FileUpload control doesn't have databinding in it's nature just like a textbox or a hiddenfield did. So I added a hiddenfield under it:
<asp:FileUpload ID="KurumLogoPathFUU" runat="server" />
<asp:HiddenField ID="KurumLogoPathHF" Value='<%# Bind("KurumLogoPath") %>' runat="server" />
and then both e.OldValues("KurumLogoPath") and e.OldValues(2) and file deleting process worked very well.

Ajax Extension (Timer) stopped working when I retrieve value from DataTable

Currently I have an Ajax Timer which executes a function every few second. It is working perfectly fine until I tried to retrieve data from a DataTable. I have no idea why. I have tried debugging. I even placed label on the page to check.
For example the Ajax Timer:
Protected Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
Label1.Text = DateTime.Now.ToLongTimeString()
End Sub
The datalist (the one giving the problem):
Protected Sub dlOrgProfile_ItemCreated(sender As Object, e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dlOrgProfile.ItemCreated
Dim bizLayerMgmt As BlOrganizations
Dim dt As DataTable
bizLayerMgmt = New BlOrganizations()
dt = bizLayerMgmt.getOrgDetails(userId).Tables(0)
ddl = CType(e.Item.FindControl("ddlCoType"), DropDownList)
Dim value As Integer = Convert.ToInt32(dt.Rows(0)(3)) 'I have narrowed the problem to this line, if I comment this line.. everything works perfectly
ddl.SelectedValue = value
End Sub
The problem lies in the dt.Rows(0)(3). I have no idea why. I need to use it to retrieve some data from the database.
Just in case if its the front-end side.. here's the markup for the site.
<div class="content">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="1000">
</asp:Timer>
<asp:DataList ID="dlOrgProfile" runat="server" DataSourceID="odsOrgDetails"
EnableTheming="True" RepeatLayout="Flow" ShowFooter="False" ShowHeader="False">
<ItemTemplate>
<h3>
<asp:TextBox ID="txBxCoName" runat="server" Text='<%# Eval("OrgName") %>'></asp:TextBox>
<div class="ddlSelect">
<asp:DropDownList ID="ddlCoType" runat="server" DataSource='<%# listOrgType() %>' DataTextField="OrganizationType" DataValueField="OrgTypeID" >
</asp:DropDownList>
</div>
<h3>
</h3>
<a id="linkCoImg" href="upload_co_logo.aspx">
<asp:Image ID="CoImg" runat="server" ImageUrl="~/logo/org/default.png" />
<span>Change</span> </a>
<br />
<div id="description">
<textarea id="taCoDesc" rows="2" cols="1"><%# Eval("Description") %></textarea>
</div>
<br />
<asp:Label ID="lblContacts" runat="server" Text="Contacts:"></asp:Label>
<br />
<div id="contacts">
<asp:TextBox ID="tbContactOffice" runat="server" CssClass="tbContacts"></asp:TextBox>
<asp:TextBox ID="tbContactFax" runat="server" CssClass="tbContacts"></asp:TextBox>
<asp:TextBox ID="tbContactMail" runat="server" CssClass="tbContacts2"></asp:TextBox>
</div>
<br />
<asp:Button ID="btnSave" runat="server" CommandArgument='<%# Eval("OrgID") %>'
CommandName="save" Text="Save" />
</h3>
</ItemTemplate>
</asp:DataList>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
Okay I have resolved my own problem.. Still don't really get it why but this is what I did.. Instead of using ItemCreated, I used ItemDataBound.
Protected Sub dlOrgProfile_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dlOrgProfile.ItemDataBound
Dim bizLayerMgmt As BlOrganizations
Dim dt As DataTable
bizLayerMgmt = New BlOrganizations()
dt = bizLayerMgmt.getOrgDetails(userId).Tables(0)
ddl = CType(e.Item.FindControl("ddlCoType"), DropDownList)
Dim value As Integer = Convert.ToInt32(dt.Rows(0)(3))
ddl.SelectedValue = value
End Sub

generate onclick event in image control in asp.net

i am have one datalist in asp.net
i m using vb with asp
now my code is just as follow
<table border="0" cellpadding="0" cellspacing="0" >
<tr>
<br />
<td>
Question Number:
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Question_no") %>' />
<br />
Cust_id:
<asp:Label ID="Cust_idLabel" runat="server" Text='<%# Eval("Cust_id") %>' />
<br />
Question:
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Question") %>' />
<br />
Time:
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Date_time") %>' />
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/ImagesFolde/Chrysanthemum.jpg" Height="50" Width="50" **OnClientClick="s()"**/>
all this in datalist as you can see
so it will be repeated..
i have put one image in it
now i want call a method when any image will be clicked
i make one sub called s() in vb
i want to call it
i use on clientclick() event but doesn't work
what to do?
you use onclientclick - have you made your functions with javascript/jquery ? ( the server side won't be fired)
for instance :
if you call you client method like this :
OnClientClick="return myFunction();"
then your function should be in the header as follows:
<script type=text/javascript>
function myFunction()
{
alert("activated here");
}
</script>
Suppose you have a datalist:
ASPX:
<asp:DataList id="ItemsList" OnItemCommand="Item_Command" runat="server">
<ItemTemplate>
<asp:LinkButton id="SelectButton" Text="Select" CommandName="ModifyRow"
runat="server" CommandArgument='<%#Eval("Id")%>' />
</ItemTemplate>
</asp:DataList>
VB (Code Behind) :
Here I am taking the id from '<%#Eval("Id")%>' and binding some products in bulleted list:
Protected Sub ItemsList_ItemCommand _
(source As Object, e As RepeaterCommandEventArgs) _
Handles Categories.ItemCommand
If e.CommandName = "ModifyRow" Then
' Determine the CategoryID
Dim categoryID As Integer = Convert.ToInt32(e.CommandArgument)
' Get the associated products from the ProudctsBLL and
' bind them to the BulletedList
Dim products As BulletedList = _
CType(e.Item.FindControl("ProductsInCategory"), BulletedList)
Dim productsAPI As New ProductsBLL()
products.DataSource = productsAPI.GetProductsByCategoryID(categoryID)
products.DataBind()
End If
End Sub
<asp:ImageButton ID="imgexpand" runat="server" ImageAlign="Bottom" ImageUrl="~/img/plus.png" OnClick="s" />
you do not need the () in the control onclick statement
this will fire the sub s() procedure in the vb code

ASP.NET VB DataPager buttons not required when only one record of data

I am using a datapager inside a nested Listview succesfully. When only one record of data is available the next previous last and first buttons are faded as per normal. However I would like them to not appear at all.
The aspx code I have is:
<asp:ListView ID="Pictures" runat="server" DataSourceID="SqlDataSource2" >
<EmptyDataTemplate>
<span>No data was returned.</span>
</EmptyDataTemplate>
<ItemTemplate>
<span style="">
<br />
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' ToolTip='<%# Eval("ToolTip") %>'
Height="150px" />
<br />
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />
<br />
<br />
</span>
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholderContainer" runat="server" style="">
<span runat="server" id="itemPlaceholder" />
</div>
<div style="clear: both;">
<asp:DataPager ID="DataPager1" runat="server" PageSize="1">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
</asp:ListView>
The code behind that I have attempted to use is:
Dim pager As DataPager = CType(e.Item.FindControl("DataPager1"), DataPager)
If (Not pager Is Nothing) Then
pager.Visible = (pager.PageSize < pager.TotalRowCount)
End If
However the pager is always nothing in the debugger i.e it can't find the control.
This may be because I have not selected the event handler correctly (I've tried several) or the method may be wrong.
Any advice gratefully received.
Try it in the listview's databound event and also call the FindControl function from the listview.
Protected Sub Pictures_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles Pictures.DataBound
Dim pager As DataPager = CType(Pictures.FindControl("DataPager1"), DataPager)
If (Not pager Is Nothing) Then
pager.Visible = (pager.PageSize < pager.TotalRowCount)
End If
End Sub

Resources