Accessing button in repeater control - asp.net

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

Related

How to get specific value from data row while binding into a data list ? asp.net vb.net

I have a data list control, inside of it I have two tables:
<asp:DataList ID="dataListAccount" runat ="server">
<ItemTemplate >
<table runat ="server" id="tblAccountInfo">
<tr>
<td>
Account Id: <%#Eval("AccountId")%>
</td>
</tr>
</table>
<br>
<table runat="server" id ="tblAccountAmount" border="1">
<tr>
<td><%#Eval("AccountBalance", "{0:C}")%></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
Then I populate the data list control with:
'create datatable
Dim dataTableAccount As DataTable = New DataTable()
dataTableAccount.Columns.Add("AccountID")
dataTableAccount.Columns.Add("AccountBalance")
'populate data table
Dim dataRow As DataRow = dataTableAccount.NewRow()
dataRow(0) = 1 'Account ID
dataRow(1) = 100 'Balance on the Account with Id=1
dataTableAccount.Rows.Add(dataRow)
Dim dataRow1 As DataRow = dataTableAccount.NewRow()
dataRow1(0) = 2 'Account Id
dataRow1(1) = 0 'Balance on the Account with Id=2
dataTableAccount.Rows.Add(dataRow1)
dataListAccount.DataSource = dataTableAccount
dataListAccount.DataBind()
In the event dataListAccount_ItemDataBound I want to know how can I get the "AccounId" for the current item binding.
Private Sub dataListAccount_ItemDataBound(sender As Object, e As
System.Web.UI.WebControls.DataListItemEventArgs) Handles
dataListAccount.ItemDataBound
Dim CurrentAccountId= ???????
End Sub
Better put value into label
Account Id: <asp:label id="lblAccountID" runat="server" Text ='<%#Eval("AccountId")%>' />
On code behind, you can easy to find it use
Dim CurrentAccountId = e.item.FindControl("lblAccountID")
I think I found one way to do it:
Dim currentRowBinding As System.Data.DataRowView = CType(e.Item.DataItem, System.Data.DataRowView)
Dim currentAccountId = currentRowBinding("AccountId")

How to make invisible check box in repeater control while exporting to excel vb.net?

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

Unable to Get Element with ID in VB.Net

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>

Trying to populate a label with text entered by a user in a repeater

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

How to do Paging in a Datalist control?

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.

Resources