Unable to Get Element with ID in VB.Net - asp.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>

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")

Pass Text From a List View Controller to a OnClick Sub VB.Net

Is there a way to pass text from a List View controller to a OnClick Subroutine? For example, there's a label in the List View and I've attached a Button in the List View and attached an OnClick Subroutine to it. Now I want to pass the text from the Label over to the OnClick Subroutine. I hope this make sense. Down below is my code:
VB.Net Code:
Protected Sub AmButtonClick(ByVal sender As Object, ByVal e As System.EventArgs)
Dim url As String = CType(Me.AmListViewDetails.FindControl("merchantLink"), Label).Text
Dim sb As New StringBuilder()
sb.Append("<script type = 'text/javascript'>"_
sb.Append("window.open('")
sb.Append(url)
sb.Append("');")
sb.Append("</script>")
ClientScript.RegisterStartupScript(Me.GetType(), "script", sb.ToString())
End Sub
ASP.Net:
<asp:ListView runtat="server" ID="AmListViewDetails" ...>
<ItemTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<asp:Label ID="merchantLink" runat="server" Text='<%Eval("Link")%>' />
</td>
</tr>
<tr runat="server">
<td runat="server">
<asp:Button ID="AmBtn" runat="server" Text="Checkout" OnClick="AmButtonClick"/>
</td>
</tr>
</table>
</ItemTemplate>
</asp:ListView>
Add a CommandArgument property to the button. That's going to be the value passed to the event handler. You don't need an OnClick property.
<asp:Button ID="AmBtn" runat="server" Text="Checkout" CommandArgument="???" />
Your event handler would be
Sub AmListViewDetails_ItemCommand(object sender, ListViewCommandEventArgs e)
Dim valuePassedFromListView = Cstr(e.CommandArgument)
End Sub

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

Accessing button in repeater control

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

Repeater control. Using a table that spans rows

The following "FindControl" method fails to find the imgAd control. Any idea why? Could it be the Table that contains it? The intent of the table is to line things up in columns across rows.
<asp:Content ID="Content3" ContentPlaceHolderID="phPageContent" runat="Server">
<asp:Repeater ID="repBanner" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Image ID="imgAd" runat="server" AlternateText="Panda Visa" ImageUrl="Images/AffiliateBanners/125%20by%20125.jpg" />
</td>
<td>
<asp:TextBox ID="txtHtml" runat="server" Columns="80" ReadOnly="True" Rows="7" TextMode="MultiLine"></asp:TextBox>
</td>
<td>
<asp:Button runat="server" Text="Copy HTML to Clipboard" OnClientClick="ClipBoard('txtHtml')" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Protected Sub repBanner_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles repBanner.ItemDataBound
Dim CurrentAd As Ad = CType(e.Item.DataItem, Ad)
Dim RepeaterItem As RepeaterItem = e.Item
Dim imgAd As Image = CType(RepeaterItem.FindControl("imgAd"), Image)
imgAd.ImageUrl = "Images/" & "125 by 125.jpg" '<<<Error occurs here
End Sub
Object reference not set to an instance of an object.
Here's some debug info that I thought may help:
? RepeaterItem.Controls.Count
1
? RepeaterItem.Controls(0).Controls.Count
0
? typename(RepeaterItem.Controls(0))
"LiteralControl"
You need to check e.Item.ItemType to make sure that you're dealing with an item, not a header or footer. Something like this:
Protected Sub repBanner_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles repBanner.ItemDataBound
If (e.Item.ItemType <> ListItemType.Item AndAlso e.Item.ItemType <> ListItemType.AlternatingItem) Then
Return
End If
Dim CurrentAd As Ad = CType(e.Item.DataItem, Ad)
Dim RepeaterItem As RepeaterItem = e.Item
Dim imgAd As Image = CType(RepeaterItem.FindControl("imgAd"), Image)
imgAd.ImageUrl = "Images/" & "125 by 125.jpg" '<<<Error occurs here
End Sub

Resources