I'm trying to create a pager in a repeater control. The content is being pulled from the database and is displaying but when I click on the previous and next buttons they don't page, that is, I stay on the same content. Would anyone be able to see the error from the code below? No errors or showing so I think it is something minor but I have been banging my head against a wall trying to find it
Markup:
<asp:Repeater ID="ArtRepeater" runat="server">
<HeaderTemplate>
<h2>Items in Selected Category:</h2>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" ID="HyperLink"
NavigateUrl='<%# Eval("MovieID", "Default2.aspx?ArtID={0}")%>'>
<%# DataBinder.Eval(Container.DataItem, "MovieTitle")%>
</asp:HyperLink>
</li>
</ItemTemplate>
Code Behind:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & _
Server.MapPath("/App_Data/MovieBoard.accdb"))
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT MovieID, MovieTitle FROM Movies", strConnect)
objOleDBAdapter.Fill(DS, "Movies")
Return DS.Tables("Movies").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 1
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()
End Sub
After banging my head against a wall I found a solution. I forgot to connect the buttons to the repeater control. Here's a solution:
Imports System.Data
Imports System.Data.OleDb
Partial Class Default2
Inherits System.Web.UI.Page
Dim pagedData As New PagedDataSource
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " & _
Server.MapPath("/App_Data/MovieBoard.accdb"))
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT MovieID, MovieTitle FROM Movies", strConnect)
objOleDBAdapter.Fill(DS, "Movies")
Return DS.Tables("Movies").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 1
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (Not pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
If Not pagedData.IsFirstPage Then
btnPrev.PostBackUrl = Request.CurrentExecutionFilePath + _
"?Page=" + CStr(pagedData.CurrentPageIndex - 1)
End If
If Not pagedData.IsLastPage Then
btnNext.PostBackUrl = Request.CurrentExecutionFilePath + _
"?Page=" + CStr(pagedData.CurrentPageIndex + 1)
End If
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()
Related
I'm working on a web app using Visual Studio VB.NET. I have a web form with two panels. I have the code below:
Protected Sub WebForm2_load(sender As Object, e As EventArgs) Handles Me.Load
Dim y As Integer = 1
Protected cr(100) As Button
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
Dim requ As String
requ = "SELECT DISTINCT ENSEIGNEMENTS.Code_Mat From ENSEIGNANT INNER Join ENSEIGNEMENTS On ENSEIGNANT.Code_Ens = ENSEIGNEMENTS.Code_Ens where NomUser='" + un + "' and Sem='S1'"
cmd = New SqlCommand(requ, con)
Dim rd As SqlDataReader = cmd.ExecuteReader()
While rd.Read()
cr(y) = New Button
cr(y).Text = rd("Code_Mat").ToString
cr(y).ID = "btn" & y.ToString
Panel1.Controls.Add(cr(y))
AddHandler cr(y).Click, AddressOf btnc
y = y + 1
End While
End Sub
Protected Sub btnc(ByVal sender As Object, ByVal e As System.EventArgs)
Protected cr1(100) As Button
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
Dim btn As Button()
Dim x As Integer = 1
Dim requete As String
cdmat = CType(sender, Button).Text
'Response.Redirect("TestGroupes.aspx")
requete = "SELECT ENSEIGNEMENTS.Gr FROM ENSEIGNANT INNER JOIN ENSEIGNEMENTS ON ENSEIGNANT.Code_Ens = ENSEIGNEMENTS.Code_Ens WHERE (((ENSEIGNEMENTS.Code_Mat)='" + cdmat + "') AND ((ENSEIGNANT.[NomUser])='" + un + "') AND ((ENSEIGNEMENTS.[Sem])='S1'))"
Dim commande As New SqlCommand
commande = New SqlCommand(requete, con)
Dim reader As SqlDataReader = commande.ExecuteReader()
While reader.Read()
cr1(x) = New Button()
cr1(x).Text = reader("Gr").ToString
cr1(x).ID = "bt" & x.ToString
Panel2.Controls.Add(cr1(x))
AddHandler cr1(x).Click, AddressOf Groupe
x = x + 1
End While
End Sub
Protected Sub Groupe(sender As Object, e As EventArgs)
MsgBox("hhhhh")
End Sub
My problem is that AddHandler cr(y).Click, AdressOf btnc and WenForm2_load work well but AddHandler cr1(x).Click, AdressOf Groupe does not: when I click on a button in Panel2 nothing happens.
You always create the primary buttons (Code_Mat), but you also need to re-create the secondary buttons (Gr) when it posts back, so you'll need to save the variable(s) used to create those secondary buttons.
As a demonstration, I created a new Web Forms project named "testing" with one page named "index.aspx":
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="index.aspx.vb" Inherits="testing.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Panel ID="Panel2" runat="server"></asp:Panel>
</div>
<asp:Literal id="msg" runat="server">msg</asp:Literal>
</form>
</body>
</html>
Using this code-behind:
Public Class index
Inherits System.Web.UI.Page
Sub Groupe(sender As Object, e As EventArgs)
Dim bn = DirectCast(sender, Button)
msg.Text = bn.CommandArgument
End Sub
Sub CreateSecondaryButtonsHelper(codeMat As String)
Panel2.Controls.Clear()
For i = 1 To 3
Dim bn As New Button With {.Text = "Gr" & i & codeMat, .ID = "bnB" & i, .CommandArgument = "Hello from " & codeMat & i}
AddHandler bn.Click, AddressOf Groupe
Panel2.Controls.Add(bn)
Next
End Sub
Sub CreateSecondaryButtons(ByVal sender As Object, ByVal e As System.EventArgs)
Dim clickedButton = DirectCast(sender, Button)
CreateSecondaryButtonsHelper(clickedButton.Text)
Session("CodeMat") = clickedButton.Text
End Sub
Sub CreateMainButtons()
For i = 1 To 3
Dim bn As New Button With {.Text = "CodeMat" & i, .ID = "bnA" & i}
AddHandler bn.Click, AddressOf CreateSecondaryButtons
Panel1.Controls.Add(bn)
Next
If Session("CodeMat") IsNot Nothing Then
CreateSecondaryButtonsHelper(CStr(Session("CodeMat")))
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
CreateMainButtons()
End Sub
End Class
It is rather dull, but I think it shows what you want to do.
N.B. You should make a new SqlConnection each time you use it and call .Dispose() on it as soon as you've finished using it. Also, using SQL parameters to pass the values instead of making up a string with them will make it more reliable and avoid SQL injection attacks.
I am having a problem with validation. I created a dynamic textboxes with corresponding dynamic numeric validator but it's not firing....
Here is my code
code behind on_load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
For i = 0 To AssetByDimension(oVal).Rows.Count - 1
Dim lt As New Literal()
Dim label As New Label()
Dim count As Integer = pnlDimension.Controls.OfType(Of Label)().ToList().Count
label.Text = "<b>" + AssetByDimension(oVal).Rows(i)("Dimension_Type") + " (" + AssetByDimension(oVal).Rows(i)("Unit_Of_Measure_Code") + "): </b>"
pnlDimension.Controls.Add(label)
Dim textbox As New TextBox()
count = pnlDimension.Controls.OfType(Of TextBox)().ToList().Count
textbox.ID = "txtDimension" & i
pnlDimension.Controls.Add(textbox)
Dim vdr As New RegularExpressionValidator
vdr.ControlToValidate = "txtDimension" & i
vdr.ValidationExpression = "\d+"
vdr.ErrorMessage = "Numbers only"
vdr.BorderColor = Drawing.Color.Red
vdr.ForeColor = Drawing.Color.Red
vdr.SetFocusOnError = True
pnlDimension.Controls.Add(vdr)
lt.Text = "<br /><br />"
pnlDimension.Controls.Add(lt)
Next
End Sub
and here's the button event handler
Protected Sub btnSaveDim_Click(sender As Object, e As EventArgs)
if Page.isvalid then
Response.Redirect("AddAsset.aspx")
else
'do nothing...
end
End Sub
What I have tried:
I tried to use Page.isValid but is not working...
Hoping for your kind
This one is REALLY driving me nuts. I've read, and tried, most of the workarounds but still it posts back!!
All the markup is generated dynamically from code-behind and inserted into a page that is part of a Master Page, from the init event.
There are a series of nested tabs, the tab content for the most part is data in a GridView. Each Gridview is set in it's own update panel. Every time a LinkButton in the GridView is clicked there is a full postback causing the tabs to reset (any button outside of the GridView and in the UpdatePanel doesn't cause a full postback.
LinkButtons are generated like this
Dim Select_Field As New CommandField
With Select_Field
.HeaderText = "View Transactions"
.SelectText = "View Transactions"
.ShowSelectButton = True
End With
GV.Columns.Add(Select_Field)
Registering with ToolKitScriptManager
Private Sub AssessmentsMain_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim vID As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID"))
Dim LB As LinkButton = CType(e.Row.Cells(4).Controls(0), LinkButton)
LB.ID = "AssMain_" & vID
AjaxControlToolkit.ToolkitScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(LB)
End If
Catch ex As Exception
Dim vError As New SendError
vError.MailError("840", PageName, ex)
ShowError()
End Try
End Sub
and the generated markup for one row is like this
<tr class="GridView" style="color:#333333;background-color:#F7F6F3;">
<td>10</td>
<td>Adam White</td>
<td>4224 Res Road</td>
<td align="right">$6,850.65</td>
<td>
<a id="ctl00_ContentPlaceHolder1_AssessmentsMainGV_ctl02_AssMain_10" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$AssessmentsMainGV','Select$0')" style="color:#333333;">View Transactions</a>
The GridView class
Public Class HAS_Gridview
Inherits GridView
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
CellPadding = 4
GridLines = WebControls.GridLines.None
ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
ClientIDMode = UI.ClientIDMode.AutoID
With MyBase.FooterStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Color.White
End With
RowStyle.BackColor = Drawing.ColorTranslator.FromHtml("#F7F6F3")
RowStyle.ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
PagerStyle.HorizontalAlign = WebControls.HorizontalAlign.Center
PagerStyle.ForeColor = Color.Black
PagerStyle.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
With MyBase.SelectedRowStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Drawing.ColorTranslator.FromHtml("#333333")
End With
With MyBase.HeaderStyle
.BackColor = Drawing.ColorTranslator.FromHtml("#E2DED6")
.Font.Bold = True
.ForeColor = Color.Black
.CssClass = "GridView"
End With
EditRowStyle.BackColor = Drawing.ColorTranslator.FromHtml("#999999")
With MyBase.AlternatingRowStyle
.BackColor = Color.White
.ForeColor = Drawing.ColorTranslator.FromHtml("#284775")
.CssClass = "GridView"
End With
With MyBase.RowStyle
.CssClass = "GridView"
End With
End Sub
End Class
Have you tried adding trigger programmatically instead of registering in AjaxControlToolkit:
Dim trigger As New AsyncPostBackTrigger()
trigger.ControlID = LB.ID
trigger.EventName = "Click"
MyUpdatePanel.Triggers.Add(trigger)
It looks like the postback is caused by href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$AssessmentsMainGV','Select$0')" in the generated markup for the anchor tag.
Try to define your own _doPostBack.
If you haven't checked post a and post b already, they offer a couple of ways to do that.
In the end the only way I could get this to work was
Create a class for a LinkButton Template
Public Class LinkButtonTemplate
Implements ITemplate
Private m_ColumnName As String
Event LinkButtonItem_Clicked(sender As LinkButton, e As EventArgs)
Public Property ColumnName() As String
Get
Return m_ColumnName
End Get
Set(ByVal value As String)
m_ColumnName = value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal ColumnName As String)
Me.ColumnName = ColumnName
End Sub
Public Sub InstantiateIn(container As Control) Implements ITemplate.InstantiateIn
Dim LB As New LinkButton()
With LB
.ID = "LB_" & ColumnName
.Text = ColumnName
.OnClientClick = "LinkButtonClick(this);"
End With
container.Controls.Add(LB)
End Sub
End Class
Add this javascript so that it would post the ID to a hidden field and click a hidden button
Private Sub LoadLinkButtonClick()
Try
Dim SB As New StringBuilder
SB.Append("function LinkButtonClick(LinkButton){ ")
SB.Append("setTimeout(function() { ")
SB.Append("$get('" & GridViewLBClicked.ClientID & "').click(); ")
SB.Append(" }, 300); ")
SB.Append("var sendingID = LinkButton.id; ")
SB.Append("document.getElementById('" & HiddenField1.ClientID & "').value = sendingID; ")
SB.Append("} ")
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "LoadLinkButton", SB.ToString, True)
Catch ex As Exception
Dim vError As New SendError
vError.MailError("1229", PageName, ex)
End Try
End Sub
On the RowDataBound event capture the ID we need and add it to the LinkButton ID (so now we know both the sending GridView and the selected row)
Private Sub AssessmentsMain_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim vID As Integer = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID"))
Dim LB As LinkButton = CType(e.Row.Cells(4).Controls(0), LinkButton)
LB.ID = "AssMain_" & vID
End If
Catch ex As Exception
Dim vError As New SendError
vError.MailError("840", PageName, ex)
ShowError()
End Try
End Sub
From the hidden button click we can recover all the data we need to make the async postback
Private Sub RaiseLinkButton_Click(sender As Object, e As EventArgs)
Try
Dim vFunction As New Functions
Dim vValue As String = HiddenField1.Value
Dim vSplit = vValue.Split("_")
Dim i As Integer = 0
For Count As Integer = 0 To vSplit.Length - 1
i += 1
Next
Dim DGName As String = vSplit(i - 2)
Select Case DGName
Case "AssMain"
Dim MV As MultiView = vFunction.FindControlRecursive(BodyMain, "AssessmentMultiView")
Dim GV As CustomControl.HAS_Gridview = vFunction.FindControlRecursive(BodyMain, "AssessmentDetailGV")
With GV
.DataSource = AssessmentsDetail_ReturnDataSet()
.DataBind()
.PageIndex = 0
End With
MV.ActiveViewIndex = 1
Dim vPanel As UpdatePanel = vFunction.FindControlRecursive(BodyMain, "AssessmentUpdatePanel")
vPanel.Update()
End Select
Catch ex As Exception
Dim vError As New SendError
vError.MailError("953", PageName, ex)
ShowError()
End Try
End Sub
I developed the following code for editing a GridView (following a tutorial written in C#), It goes into edit mode, but my edits do not take effect, here is my code:
aspx.vb code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Globalization
Partial Class MemberPages_editOutage
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim dt As New DataTable()
Dim connection As New SqlConnection("server='\SQLEXPRESS'; trusted_connection='true'; Database='OutagesMgt_db'")
Try
connection.Open()
Dim sqlStatement As String = "SELECT OutageDetailId, LocationName, Description, DetailDescription, CreateDate, StatusId FROM OutageDetail WHERE StatusId='1' ORDER BY CreateDate DESC"
Dim cmd As New SqlCommand(sqlStatement, connection)
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
MyDataGrid.DataSource = dt
MyDataGrid.DataBind()
End If
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Fetch Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
connection.Close()
End Try
End Sub
'edit command
Protected Sub MyDataGrid_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles MyDataGrid.RowEditing
'turn to edit mode
MyDataGrid.EditIndex = e.NewEditIndex
'Rebind the GridView to show the data in edit mode
BindGrid()
End Sub
'cancel command
Protected Sub MyDataGrid_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles MyDataGrid.RowCancelingEdit
' switch back to edit default mode
MyDataGrid.EditIndex = -1
'Rebind the GridView to show the data in edit mode
BindGrid()
End Sub
'Update Function
Private Sub UpdateRecord(ByVal SOutageDetailId As String, ByVal SDescription As String, ByVal SDetailDescription As String, ByVal SCreateDate As String, ByVal SstatusId As String)
Dim connection As New SqlConnection("server='\SQLEXPRESS'; trusted_connection='true'; Database='OutagesMgt_db'")
Dim sqlStatement As String = String.Empty
sqlStatement = "UPDATE OutageDetail SET #OutageDetailId = #OutageDetailId, LocationName = #LocationName, " & _
"Description = #Description, DetailDescription= #DetailDescription, " & _
"CreateDate = #CreateDate, StatusId = #StatusId WHERE OutageDetailId = #OutageDetailId"
connection.Open()
Dim cmd As New SqlCommand(sqlStatement, connection)
cmd.Parameters.Add(New SqlParameter("#OutageDetailId", SOutageDetailId))
cmd.Parameters.Add(New SqlParameter("#LocationName", SDescription))
cmd.Parameters.Add(New SqlParameter("#Description", SDescription))
cmd.Parameters.Add(New SqlParameter("#DetailDescription", SDetailDescription))
cmd.Parameters.Add(New SqlParameter("#CreateDate", SCreateDate))
cmd.Parameters.Add(New SqlParameter("#StatusId", SstatusId))
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
' MyDataGrid.EditIndex = -1
connection.Close()
BindGrid()
End Sub
'update command
Protected Sub MyDataGrid_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles MyDataGrid.RowUpdating
'Accessing Edited values from the GridView
Dim SOutageDetailId As String = MyDataGrid.Rows(e.RowIndex).Cells(0).Text
Dim SDescription As String = MyDataGrid.Rows(e.RowIndex).Cells(1).Text
Dim SDetailDescription As String = MyDataGrid.Rows(e.RowIndex).Cells(2).Text
Dim SCreateDate As String = MyDataGrid.Rows(e.RowIndex).Cells(3).Text
Dim SstatusId As String = MyDataGrid.Rows(e.RowIndex).Cells(4).Text
'Call the function to update the GridView
UpdateRecord(SOutageDetailId, SDescription, SDetailDescription, SCreateDate, SstatusId)
MyDataGrid.EditIndex = -1
'Rebind Gridview to reflect changes made
BindGrid()
End Sub
End Class
aspx code:
<asp:GridView id="MyDataGrid" runat="server"
Width="750px"
CssClass="gridViewEdit"
BackColor="White"
BorderColor="Black"
CellPadding="3"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#FFFFFF"
OnEditCommand="MyDataGrid_RowEditing"
OnCancelCommand="MyDataGrid_RowCancelingEdit"
OnUpdateCommand="MyDataGrid_RowUpdating"
DataKeyField="OutageDetailId"
Font-Names="Verdana">
<Columns>
<asp:CommandField ShowEditButton="True" EditText="Edit" CancelText="Cancel" UpdateText="Update" />
</Columns>
<HeaderStyle BackColor="White"></HeaderStyle>
</asp:GridView>
Could someone shed some light on what I am missing please.
The moment you hit the Edit, you go to get the ID of the line that must be update, and you get it from this line
Dim SOutageDetailId As String = MyDataGrid.Rows(e.RowIndex).Cells(0).Text
but on page load you have set
If Not IsPostBack Then
BindGrid()
End If
so on the post back, the grid up to the point you try to get the id from the cell, is empty.
Two ways, ether give again the data on post back, and make DataBind right after the update, or get the Index of the Grid View to make the Update, and not take the Cell.
For example, I will change your code to:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
BindGrid()
End Sub
Private Sub BindGrid()
Dim dt As New DataTable()
Dim connection As New SqlConnection("server='\SQLEXPRESS'; trusted_connection='true'; Database='OutagesMgt_db'")
Try
connection.Open()
Dim sqlStatement As String = "SELECT OutageDetailId, LocationName, Description, DetailDescription, CreateDate, StatusId FROM OutageDetail WHERE StatusId='1' ORDER BY CreateDate DESC"
Dim cmd As New SqlCommand(sqlStatement, connection)
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
MyDataGrid.DataSource = dt
If Not IsPostBack Then
MyDataGrid.DataBind()
End If
End If
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Fetch Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
connection.Close()
End Try
End Sub
[*] Assuming that you do not have other bugs on sql...
I have following code in page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GetDetails()
PopulateRepeater()
End If
End Sub
Sub PopulateRepeater()
Dim dt As DataTable = GetDetails()
Dim dtDoc As DataTable = objdoc.GetDocDetails(Session("RegID"))
If dtDoc.Rows.Count > 0 Then
Dim strUserName As String = dt.Rows(0)("Name")
Dim files As IList(Of FileInfo) = New List(Of FileInfo)()
Dim filters As String = "*.jpg;*.png;*.gif"
For Each filter As String In filters.Split(";"c)
Dim fit As FileInfo() = New DirectoryInfo(Me.Server.MapPath("../SiteImages/" & strUserName & "/" & Session("RegID") & "/")).GetFiles(filter)
For Each fi As FileInfo In fit
files.Add(fi)
Next
Next
strPath = Server.MapPath("../SiteImages/" & strUserName & "/" & Session("RegID") & "/")
Me.Repeater1.DataSource = files
Me.Repeater1.DataBind()
End If
End Sub
I have following code in itemdatabound
Dim ThViewr As Bright.WebControls.ThumbViewer = DirectCast(e.Item.FindControl("Th1"), Bright.WebControls.ThumbViewer)
Dim dtUser As DataTable = GetDetails()
Dim dtDoc As DataTable = objdoc.GetDocDetails(Session("RegID"))
Dim strUserName As String = dtUser.Rows(0)("Name")
If dtDoc.Rows.Count > 0 Then
For i As Integer = 0 To dtDoc.Rows.Count - 1
Dim ImagePath As String = "../SiteImages/" & strUserName & "/" & Session("RegID") & "/" + dtDoc.Rows(i)("ImageName")
ThViewr.ImageUrl = ImagePath
Next
End If
My aspx contains
<div style="clear:both;">
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<span style="padding:2px 10px 2px 10px">
<bri:ThumbViewer Id="Th1" runat="server" Height="100px" Width="100px"/>
</span>
</ItemTemplate>
</asp:Repeater>
</div>
If the imagePath ="../SiteImages/Ram/PR/First.jpg" Means the folder PR aontains exactly 3 images namely First.jpg,Second.jpg and Third.jpg.
Now with above code three images are coming but Third.jpg is repeating 3 times.First.jpg and Second.jpg is not coming.Can anybody help to resolve this.
The ItemDataBound event is raised once for every object in the bound list, so it will be fired three times in your case; once for each file. You should not loop over your data table, but rather grab the current item from the event args.
Update: looking closer at the code I find it somewhat confusing. You bind a list of FileInfo objects to the repeater, but fetch data from a DataTable when the items are bound. I am guessing that you want to show the files found, and I think that the following code in ItemDataBound will do that for you:
Dim ThViewr As Bright.WebControls.ThumbViewer = DirectCast(e.Item.FindControl("Th1"), Bright.WebControls.ThumbViewer)
Dim dtUser As DataTable = GetDetails()
Dim strUserName As String = dtUser.Rows(0)("Name")
Dim ImagePath As String = "../SiteImages/" & strUserName & "/" & Session("RegID") & "/" + DirectCast(e.Item.DataItem, FileInfo).Name
ThViewr.ImageUrl = ImagePath