I have my DataList in ASP.NET 3.5 Access 2003 DataSource. I want to create paging for a DataList control using VB.
DataList lacks functionality of pagging like in GridView but its possible to implement pagging functionality for DataList.
Here i have done pagging using PagedDataSource which enclose the paging related properties of a data-bound control, that allow it to perform the pagging. More details about PagedDataSource
Inline code
<div>
<asp:DataList ID="dataListStudent" runat="server">
<ItemTemplate>
<table cellpadding="10">
<tr>
<td nowrap="nowrap">
<b>Student id</b>
</td>
<td nowrap="nowrap">
<b>First name</b>
</td>
<td nowrap="nowrap">
<b>Last name</b>
</td>
<td>
<b>City</b>
</td>
</tr>
<hr />
<tr>
<td nowrap="nowrap">
<%# Eval("StudentID") %>
</td>
<td nowrap="nowrap">
<%# Eval("FirstName") %>
</td>
<td nowrap="nowrap">
<%# Eval("LastName") %>
</td>
<td nowrap="nowrap">
<%# Eval("City") %>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<br />
<table border="0" width="410">
<tr>
<td align="left">
<asp:LinkButton ID="lbPrev" runat="server">
Prev
</asp:LinkButton>
</td>
<td align="right">
<asp:LinkButton ID="lbNext" runat="server">
Next
</asp:LinkButton>
</td>
</tr>
</table>
</div>
Code-behind
Imports System.Data
Imports System.Data.OleDb
Partial Class _Default
Inherits System.Web.UI.Page
Dim pageds As New PagedDataSource()
Public Property CurrentPage() As Integer
Get
If Me.ViewState("CurrentPage") Is Nothing Then
Return 0
Else
Return Convert.ToInt16(Me.ViewState("CurrentPage").ToString())
End If
End Get
Set(ByVal value As Integer)
Me.ViewState("CurrentPage") = value
End Set
End Property
Sub bindDataList()
Dim sql As String
sql = "SELECT * FROM STUDENTS"
Dim da As New OleDbDataAdapter(sql, "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Course.mdb")
Dim dt = New DataTable()
da.Fill(dt)
Try
pageds.DataSource = dt.DefaultView
pageds.AllowPaging = True
pageds.PageSize = 3
pageds.CurrentPageIndex = CurrentPage
lbNext.Enabled = Not pageds.IsLastPage
lbPrev.Enabled = Not pageds.IsFirstPage
dataListStudent.DataSource = pageds
dataListStudent.DataBind()
Catch ex As Exception
Throw ex
End Try
End Sub
Protected Sub lbPrev_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbPrev.Click
currentPage -= 1
bindDataList()
End Sub
Protected Sub lbNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbNext.Click
currentPage += 1
bindDataList()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
bindDataList()
End If
End Sub
End Class
Your connection string, Column names might be different you might want different layout of DataList feel free to fiddle with it. Hopefully it will help you to solve the problem.
Related
I am very new to vb.net. I am exporting data from Repeater control to Excel; I am doing it fine but in my repeater control I have a check box. I just don't want to display it in my Excel. How can I exclude it?
<asp:Repeater ID="fillmrepeater" runat="server">
<HeaderTemplate>
<tr>
<td>
Select
</td>
<td>
Name
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<input type="checkbox" value='<%# DataBinder.Eval(Container.DataItem, "Id")%>'
name="cP" id="cP">
</td>
<td>
<%# DataBinder.Eval(Container.DataItem("Name"), "Name")%>)%>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
and in codebehind while exporting to Excel
Private Sub exportExcel_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.exportExcelClickEventArgs) Handles exportExcel_Click.Click
For Each repter As RepeaterItem In fillmrepeater.Items
If repter.ItemType = ListItemType.Item Or repter.ItemType = ListItemType.AlternatingItem Then
Dim ckb As New CheckBox()
CType(repter.FindControl("chkPerson"), CheckBox).Visible = False
End If
Next
Response.Clear()
Response.Buffer = True
Response.AddHeader("Content-Disposition", "attachment; filename=report.xls;")
Response.ContentType = "application/vnd.ms-excel"
Dim sw As New StringWriter()
Dim hw As New Html32TextWriter(sw)
fillmrepeater.RenderControl(hw)
Response.Write("<table>")
Response.Write(sw.ToString())
Response.Write("</table>")
Response.Flush()
Response.End()
END Sub
END Class
I am getting object reference not set to instance of an object
so I am getting null here. I just need to making visible=false to checkck box.
Put the RunAt="server" attribute on your checkbox so that it is available in the code-behind.
<input type="checkbox" runat="server" value='<%# DataBinder.Eval(Container.DataItem, "Id")%>' name="chkPerson" id="chkPerson" />
Modify your code as follows:
For Each repter As RepeaterItem In fillmrepeater.Items
If repter.ItemType = ListItemType.Item Or repter.ItemType = ListItemType.AlternatingItem Then
CType(repter.FindControl("chkPerson"), HtmlInputCheckBox).Visible = False
End If
Next
EDIT :
To hide the Header Row:
Mark your HeaderTemplate <TR> with runat="server" so that we can access it in the code-behind.
<HeaderTemplate>
<tr runat="server" id="HeaderRow">
<td>
Select
</td>
<td>
Name
</td>
</tr>
</HeaderTemplate>
[you already know what to do now :) ]
Dim headerRow As HtmlTableRow = fillmrepeater.Controls(0).FindControl("HeaderRow")
headerRow.Visible = False
I have the below code to retrieve the table element when the checkbox is checked.
With this, I could get the table ID. When I try to get the HtmlTable with the ID, it throws the null reference exception.
Once I get the table element with its ID, I need to loop through the rows of that table. Could anyone help me out?
ASPX.VB
Protected Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs)
Dim tab As String
Dim check As CheckBox = CType(sender, CheckBox)
tab = check.Parent.Parent.Parent.ID
Dim tabb As HtmlControl = Me.FindControl(tab)
Dim myTab As HtmlTable = CType(tabb, HtmlTable)
For Each cell As HtmlTableRow In myTab.Rows
//My Code Here
Next
End Sub
ASPX:
<table id="itemlist" class="mel-table" runat="server">
<tr>
<td>
<asp:CheckBox runat="server" ID="CheckBox2" OnCheckedChanged="CheckBox2_CheckedChanged" AutoPostBack="true" />
</td>
</tr>
</table>
Use the parent element ID under which the table is nested like below.
Protected Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs)
Dim tab As String
Dim check As CheckBox = CType(sender, CheckBox)
tab = check.Parent.Parent.Parent.ID
Dim myTab As HtmlTable = CType(mydiv.FindControl(tab), HtmlTable)
For Each cell As HtmlTableRow In myTab.Rows
//My Code Here
Next
End Sub
<div id="mydiv" runat="server">
<table id="itemlist" class="mel-table" runat="server">
<tr>
<td>
<asp:CheckBox runat="server" ID="CheckBox2" OnCheckedChanged="CheckBox2_CheckedChanged" AutoPostBack="true" />
</td>
</tr>
</table>
</div>
I'm trying to populate labels on a repeater from what a user enters in a text box. However, the value entered in the text box isn't being picked up so nothing happens when I click the button that is to dispplay the text in the labels.
My VB code is here:
Protected Sub cmdShowCost_Click(sender As Object, e As EventArgs) Handles cmdShowCost.Click
rptProducts.DataBind()
Dim someString As String
Dim txtField As TextBox
Dim lblField As Label
Dim j As Integer = 0
For Each item In rptProducts.Items
txtField = CType(item.FindControl("txtAmountToBuy"), TextBox)
lblField = CType(item.FindControl("lblCost"), Label)
If Not IsNothing(txtField) Then
j = j + 1
someString = txtField.Text
lblField.Text = someString
Else
lblField.Text = 0
End If
Next
End Sub
and my html is here:
<div>
<table>
<asp:Repeater ID="rptProducts" runat="server" >
<HeaderTemplate>
<tr>
<td>
Product Name
</td>
</td>
<td>
Price per Kg
</td>
<td>
Kg in Stock
</td>
<td>
Action
</td>
<td>
Amount to Buy
</td>
<td>
Cost
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#Eval("Product")%>
</td>
<td>
<%#Eval("PricePerKg")%>
</td>
<td>
<%#Eval("QuantityKg")%>
</td>
<td>
<a href='amount.aspx?ProductID=<%# DataBinder.Eval(Container.DataItem, "ProductID")%>&Stock=<%#Eval("QuantityKg")%>'>Details...</a>
</td>
<td>
<asp:TextBox ID="txtAmountToBuy" runat="server"/>
</td>
<td>
<asp:Label runat="server" ID="lblCost" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
</table>
</div>
The rest of the repeater works fine, it's just the populating the labels that doesn't work.
This is my first time posting a question, hopefully someone can help. I searched as best I could for this problem but nothing seemed to work.
Thanks.
Two thing you need to take care of:
1.In page_Load you need to make sure that you are not binding the repeater in PostBack:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
rptProducts.DataSource = GetProducts() 'Or whatever datasource you have
rptProducts.DataBind()
End If
End Sub
2.In click method of the cmdShowCost button, don't bind the repeater (As mentioned by ajakblackgoat ) :
Protected Sub cmdShowCost_Click(sender As Object, e As EventArgs) Handles cmdShowCost.Click
'rptProducts.DataBind()
Dim someString As String
Dim txtField As TextBox
Dim lblField As Label
Dim j As Integer = 0
For Each item In rptProducts.Items
txtField = CType(item.FindControl("txtAmountToBuy"), TextBox)
lblField = CType(item.FindControl("lblCost"), Label)
If Not IsNothing(txtField) Then
j = j + 1
someString = txtField.Text
lblField.Text = someString
Else
lblField.Text = 0
End If
Next
End Sub
I have a UserControl inside DataList, I fill the controls inside the usercontrol according to the PrimeryKey of the DataList's data. At first load program behaves as expected but when user changes page index all the MessageID's returns 0, most probably value coming with
<%# Eval("id").toString()%> is lost. I dont want to hard code the usercontrol because i used it in many place in the project, it makes the code maintainable. How can i correct this behaviour? Thanks in advance.
My code is below:
<asp:DataList ID="DataList1" runat="server" Width="658px">
<ItemTemplate>
<table style="width: 100%;">
<tr>
<td style="font-weight: 700; color: #FF0000; font-size: medium; font-size: 10pt; font-family: Tahoma">
<%# Eval("hadding") +" ["+Eval("startTime")+" - "+Eval("endTime")+"]"%>
</td>
</tr>
<tr>
<td style="font-weight: 700; font-size: 10pt; font-family: Tahoma">
<%# Eval("location") %>
</td>
</tr>
<tr>
<td>
<uc1:MyUserControl ID="MyUserControl1" runat="server" MessageID='<%# Eval("id").toString()%>' />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<table>
<tr>
<td>
<asp:Button ID="btnfirst" runat="server" Font-Bold="true" Text="<<" Height="31px"
Width="43px" OnClick="btnfirst_Click" /></td>
<td>
<asp:Button ID="btnprevious" runat="server" Font-Bold="true" Text="<" Height="31px"
Width="43px" OnClick="btnprevious_Click" /></td>
<td>
<asp:Button ID="btnnext" runat="server" Font-Bold="true" Text=">" Height="31px"
Width="43px" OnClick="btnnext_Click" /></td>
<td>
<asp:Button ID="btnlast" runat="server" Font-Bold="true" Text=">>" Height="31px"
Width="43px" OnClick="btnlast_Click" /></td>
</tr>
</table>
and my user control:
Partial Class MyUserControl
Inherits System.Web.UI.UserControl
Private _messageID As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (_messageID > 0) Then
Fill(_messageID)
End If
End Sub
Public Property MessageID As Integer
Get
Return _messageID
End Get
Set(value As Integer)
_messageID = value
End Set
End Property
Protected Sub Fill(messageID As Integer)
'Some code
End Sub
End Class
Difficult to answer without looking at the whole page lifecycle, but you may try to store the MessageId in your control's ViewState, like this :
Public Property MessageID As Integer
Get
If (Me.ViewState("VSMessageID") IsNot Nothing) Then
return CType(Me.ViewState("VSMessageID "), Integer)
else
return 0 // arbitrary value
End Get
Set(value As Integer)
Me.ViewState.Add("VSMessageID", value)
End Set
End Property
Then :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (MessageID > 0) Then
Fill(MessageID )
End If
End Sub
See http://msdn.microsoft.com/en-us/library/ms227551%28v=vs.85%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
Sorry if bad VB.Net syntax
I solved the problem by changing the usercontrol as such:
Partial Class MyUserControl
Inherits System.Web.UI.UserControl
Public Property MessageID As Integer
Get
Return 0
End Get
Set(value As Integer)
Fill(value)
End Set
End Property
Protected Sub Fill(messageID As Integer)
'Some code
End Sub
End Class
As jbl said, this is because of the page lifecycle. OnPageIndexChange event of an ASPxDataview or on your custom PageIndexChange event for asp.net DataList, code work as such:
DataList (or ASPxDataview ) Load
UserControl Property setting
UserControl Load
PageIndexChange event
UserControl Load
UserControl Property setting
That's why on UserControl.Load Property is not set.
I'm trying - quite unsuccessfully - to access a button inside a repeater control. I have a repeater set up on a page that displays movies that are currently showing in cinemas. I have created two buttons and added them to the repeater - one for trailer and another for review. For the review I want to link to another page which will have another repeater with paging enabled. When a users clicks the review button they should be brought to a page that shows only the reviews for that specific movie. This is that code I have:
MARKUP:
The repeater:
<asp:Repeater ID="movies" runat="server">
<ItemTemplate>
<table width="641px">
<tr>
<td>
<span style="font-weight:bold;font-size:16px;">
<%# Container.DataItem("MovieTitle")%>
</span>
</td>
<td>
<span style="float:right;">
<asp:Image ID="Image1" runat="server" ImageUrl = '<%# Eval("Total")%>' style="width:80px;height:14px;"/>
</span>
</td>
</tr>
<tr>
<td colspan="2">
<hr style="height:1px;border-bottom:none;color:#e3e3e3;"/>
</td>
</tr>
</table>
<table width="641px">
<tr>
<td>
<asp:Image ID="Image2" runat="server" ImageUrl = '<%# Eval("MovieImageFileName")%>' style="width:180px;height:108px;border:1px solid #e3e3e3;"/>
</td>
<td style="vertical-align:top;">
<%# Container.DataItem("Synopsis")%>
</td>
</tr>
</table>
<table width="641px">
<tr>
<td>
<span style="float:right">
<asp:Button ID="btnTrailer" runat="server" Text="Trailer" BackColor="#FF9900" ForeColor="White" />
<asp:Button ID="btnReview" runat="server" Text="Review" BackColor="#FF9900" ForeColor="White" CommandName="Review" />
</span>
</td>
</tr>
<tr>
<td>
<hr style="height:1px;border-bottom:none;color:#e3e3e3;"/>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
CodeBehind:
Dim movie_title As String
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim myConn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim dr, aDataReader As OleDbDataReader
Dim query, movieID As String
movie_title = Request.QueryString("id")
myConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & _
Server.MapPath("/App_Data/MovieBoard.accdb"))
myConn.Open()
Dim sqlQuery = "Select movieID From Movies"
Dim aCmd = New OleDbCommand(sqlQuery, myConn)
aDataReader = aCmd.ExecuteReader()
If aDataReader.Read() = True Then
movieID = aDataReader(0)
Else
movieID = "0"
End If
query = ("Select MovieTitle, Genre, Synopsis, Starring, Total, Director, MovieImageFileName From Movies, MovieReviews, MReviewRatings WHERE Movies.MovieID = MovieReviews.MovieID AND MovieReviews.MReviewID = MReviewRatings.MReviewID AND ReviewerTypeID = 1")
cmd = New OleDbCommand(query, myConn)
dr = cmd.ExecuteReader()
movies.DataSource = dr
movies.DataBind()
End Sub
Protected Sub movies_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles movies.ItemCommand
If e.CommandName = "Review" Then
Response.Redirect("testingreviews.aspx?id = '" & movie_title)
End If
End Sub
When I run page the page displays but when I click the review button I get the following 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.
Anyone any ideas on what I am doing wrong? I am very new to asp.net.
If you want to access a button use the event ItemCreated or maybe its ItemDataBound.
Handles movies.ItemCreated
In that event you can then refeer to the button using FindControl,
Something like this
Sub Movies_ItemDataBound(Sender As Object, e As RepeaterItemEventArgs) Handles movies.ItemDataBound
Dim Btn As Button = CType(e.Item.FindControl("ButtonName"),Button)
End Sub