Asp.net repeater databind on postback - asp.net

SOLUTION FOR FUTURE REFERENCE
Problem was the "tecnico" variable that became 0 at every postback, also to avoid any problem I get rid of global variables data1 and data2 and moved them inside the Bindrepeater routine, like this:
Dim data1, data2 As DateTime
If Len(ViewState("dataDa")) = 0 Then
data1 = GetDayFromWeek(Date.Today, DayOfWeek.Monday)
data2 = GetDayFromWeek(Date.Today, DayOfWeek.Sunday)
ViewState("dataDa") = data1
ViewState("dataA") = data2
Else
data1 = Date.ParseExact(ViewState("dataDa"), "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(ViewState("dataA"), "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
End If
ORIGINAL QUESTION
I'm having trouble with databind of a repeater on page load. I would make a sort of weekly calendar, so the repeater should show dates and for every day a nested repeater should show appointments. I made a simple week selector with a Previous/Next button to move through weeks. It work fine on first page load, but it shows nothing when I use the buttons to change active week.
I know the problem is the postback for sure, but I can't get around this... any help?
html:
<div id="divCalendario" class="panel" runat="Server">
<div id="divCalendarNavigator" style="display: block;" runat="server">
<div>
<%--<asp:Calendar runat="server" ID="calendar" SelectionMode="DayWeek" TitleStyle-ForeColor="#1f7872" TitleStyle-Font-Bold="true" PrevMonthText="<i class=icon-foo></i>" NextMonthText="<i class=icon-foo></i>" NextPrevStyle-Font-Names="FontAwesome" SelectWeekText="<i class=icon-foo></i>" SelectorStyle-Font-Names="FontAwesome" WeekendDayStyle-BackColor="LightGray" SelectedDayStyle-BackColor="#f3ef98" SelectedDayStyle-ForeColor="Black" SelectedDayStyle-Font-Bold="true" OnSelectionChanged="calendar_SelectionChanged"></asp:Calendar>--%>
<asp:LinkButton runat="server" ID="lnkPrevWeek" OnClick="lnkPrevWeek_Click"><i class="fa fa-arrow-circle-o-left" aria-hidden="true"></i></asp:LinkButton>
<asp:Literal ID="litData" runat="server"></asp:Literal>
<asp:LinkButton runat="server" ID="lnkNextWeek" OnClick="lnkNextWeek_Click"><i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></asp:LinkButton>
<asp:HiddenField runat="server" ID="hdnDa" /><asp:HiddenField runat="server" ID="hdnA" /><asp:HiddenField runat="server" ID="hdnSpostamento"/>
<asp:DropDownList ID="ddlTecnicoCal" runat="server" AppendDataBoundItems="true" CssClass="tendina" placeholder="Tecnico" AutoPostBack="true">
<%--<asp:ListItem Value="-1">Tutti</asp:ListItem>--%>
</asp:DropDownList>
</div>
</div>
<asp:Repeater ID="rptParent" runat="server">
<ItemTemplate>
<p style="margin-left: 10px"><b>
<asp:Label ID="lblDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "data", "{0:dd/MM/yyyy}")%>'></asp:Label></b></p>
<asp:Repeater ID="rptAppuntamenti" runat="server">
<ItemTemplate>
<%# Eval("id")%></td>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</div>
CODE:
Imports System.Data.SqlClient
Imports System.Globalization
Public Class Calendario
Inherits System.Web.UI.Page
Dim data1, data2 As DateTime
Dim tecnico As Integer
Dim utente As Utenti
Public Function GetDayFromWeek(week As DateTime, day As DayOfWeek) As DateTime
Dim startDay As DayOfWeek = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek
' get the beginning of the week
Dim diff As Integer = CInt(week.DayOfWeek) - CInt(startDay)
Dim beginingOfWeek As DateTime = week.AddDays(diff * -1)
' get the day we are looking for
diff = CInt(day) - CInt(startDay)
If diff < 0 Then
diff = 7 - CInt(startDay)
End If
Return beginingOfWeek.AddDays(diff)
End Function
Public Function datasql(ByVal dataini As Date) As String
Return dataini.Year & "-" & dataini.Month & "-" & dataini.Day
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
caricaTecnici()
Dim monday = GetDayFromWeek(Date.Today, DayOfWeek.Monday)
Dim sunday = GetDayFromWeek(Date.Today, DayOfWeek.Sunday)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
Dim dbVulcano As New dbVulcanoEntities
data1 = Date.ParseExact(monday, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(sunday, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
tecnico = Session("idUtente")
utente = dbVulcano.Utenti.Where(Function(u) u.IDUtente = tecnico).Single
End If
BindRepeater()
End Sub
Private Sub BindRepeater()
Dim constr As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Dim query As String = "Select distinct(statoRic.DataAss) as data
From StatoRic
INNER Join
(Richieste INNER JOIN Clienti
On clienti.IDCliente=Richieste.RFCliente)
On StatoRic.RFRic=Richieste.IDRic
join Utenti
On utenti.IDUtente=StatoRic.RFTecnico
WHERE(RFStato = 11 or RFStato = 12 Or rfstato = 13 Or rfstato = 41) And Attuale=1 and StatoRic.DataAss is not null and statoric.DataAss between #data1 and #data2 And RFTecnico=#tecnico
group by statoRic.DataAss order by statoRic.DataAss asc"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#data1", data1)
cmd.Parameters.AddWithValue("#data2", data2)
cmd.Parameters.AddWithValue("#tecnico", tecnico)
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
rptParent.DataSource = dt
rptParent.DataBind()
End Using
End Using
End Using
End Sub
Private Sub rptParent_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles rptParent.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim childRepeater As Repeater = e.Item.FindControl("rptAppuntamenti")
Dim lblDate As Label = e.Item.FindControl("lblDate")
'Dim lblTecnico As Label = e.Item.FindControl("lblTecnico")
Dim data As DateTime = Date.ParseExact(lblDate.Text, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
'lblTecnico.Text = utente.NomeExt
Dim constr As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Dim query As String = "Select statoric.id, (case when clienti.IDCliente = 796 then richieste.descr else clienti.RagSociale end) as RagSociale, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraDalle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraDalle % 100)),'00:00') as eventstart, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraAlle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraAlle % 100)),'00:30') as eventend, Utenti.Nome as tecnico, statoRic.DataAss as data
From StatoRic
INNER Join
(Richieste INNER JOIN Clienti
On clienti.IDCliente=Richieste.RFCliente)
On StatoRic.RFRic=Richieste.IDRic
join Utenti
On utenti.IDUtente=StatoRic.RFTecnico
WHERE(RFStato = 11 or RFStato = 12 Or rfstato = 13 Or rfstato = 41) And Attuale=1 and StatoRic.DataAss is not null And RFTecnico=#tecnico and statoric.DataAss = #data
order by statoRic.DataAss asc"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#data", data)
cmd.Parameters.AddWithValue("#tecnico", tecnico)
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
childRepeater.DataSource = dt
childRepeater.DataBind()
End Using
End Using
End Using
End If
End Sub
Sub caricaTecnici()
Dim Query As String = "SELECT nome,idutente FROM Utenti WHERE attivo=1"
Dim cmd As New SqlCommand(query)
ddlTecnicoCal.DataSource = GetData(cmd)
ddlTecnicoCal.DataTextField = "nome"
ddlTecnicoCal.DataValueField = "idutente"
ddlTecnicoCal.DataBind()
ddlTecnicoCal.SelectedIndex = ddlTecnicoCal.Items.IndexOf(ddlTecnicoCal.Items.FindByValue(Session("idUtente")))
End Sub
Private Function GetData(cmd As SqlCommand) As DataTable
Dim strConnString As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Using con As New SqlConnection(strConnString)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
Protected Sub lnkPrevWeek_Click(sender As Object, e As EventArgs)
data1 = Date.ParseExact(hdnDa.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(hdnA.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
Dim monday = data1.AddDays(-7)
Dim sunday = data2.AddDays(-7)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
BindRepeater()
End Sub
Protected Sub lnkNextWeek_Click(sender As Object, e As EventArgs)
data1 = Date.ParseExact(hdnDa.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(hdnA.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
Dim monday = data1.AddDays(7)
Dim sunday = data2.AddDays(7)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
BindRepeater()
End Sub
End Class
Thanks!

I think your problem could be your global variables not preserving their new value after postback:
Dim data1, data2 As DateTime
Dim tecnico As Integer
Dim utente As Utenti
Try to store the values inside Session variables or Viewstate instead.
For example:
Session("tecnico") = x
ViewState("utente") = y
I've had this issue in the past.
The global variable doesn't keep its value

Related

Textbox with textmode = date does not show data after executereader

I am using VS 2012 asp.net web project and VB.net as programming language.
I have on my form a textbox field that its textmode property is set to Date (Datepicker).
when I run the following code I can't retrieve the date saved in the record,
Protected Sub Srch_Click(sender As Object, e As EventArgs) Handles Srch.Click
Dim ARTSQLCON As SqlConnection = New SqlConnection("Data Source=EMBRYOLOGIST;Initial Catalog=ARTSQL;Integrated Security=True")
Try
ARTSQLCON.Open()
If Not Len(FilenumSrc.Text) = 0 Then
Dim sqlread = New SqlCommand
sqlread.CommandText = "SELECT Filenum, DOB FROM TblReg WHERE Filenum = " & FilenumSrc.Text
sqlread.Connection = ARTSQLCON
Dim dr As SqlDataReader
dr = sqlread.ExecuteReader
If dr.HasRows Then
dr.Read()
FileNumTxt.Text = dr.Item("Filenum")
DobTxt.Text = dr.Item("DOB")
dr.Close()
End If
End If
Catch ex As Exception
Finally
ARTSQLCON.Close()
End Try
end sub
Dim dt As DateTime = Convert.ToDateTime(dr.
Item("DOB").ToString())
DobTxt.Text = String.Format("{0:yyyy-MM-dd}", dt)
ref.: data binding

Dropdownlist in gridview reset to Default Instead of selected value

I have two GridView(SalesGView and ProdGView). SalesGView contains dropdowlist and textboxes.ProdGView is wrapped with ModalPopup and is populated by dropdownlist selection from ProdGView.
The issue is when i click button select on ProdGView, the dropdownlist in the SalesGView resets to default value (Electronics) instead of selected value.
I need help on how to correct this issue.
aspx code:
SalesGView Dropdownlist
<asp:DropDownList ID="CatCode" OnSelectedIndexChanged ="CatCode_SelectedIndexChanged" AutoPostBack="true" runat="server" />
ProdGView SelectRow
<asp:GridView ID="ProdGView" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" Text="Select" runat="server" OnClick="SelectRow" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
Private Sub SalesGView_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles SalesGView.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim ctrl As Control = e.Row.FindControl("CatCode")
If (Not (ctrl) Is Nothing) Then
Dim dd As DropDownList = CType(ctrl, DropDownList)
Dim connStr As String = ConfigurationManager.ConnectionStrings("SY_InventoryConnectionString").ConnectionString
Dim sqlda As SqlDataAdapter = New SqlDataAdapter
Dim com As SqlCommand = New SqlCommand
Dim dt As DataTable
Dim conn As SqlConnection = New SqlConnection(connStr)
dt = New DataTable
com.Connection = conn
com.CommandText = "SELECT CatName FROM Prod_Category"
sqlda = New SqlDataAdapter(com)
sqlda.Fill(dt)
dd.DataTextField = "CatName"
dd.DataValueField = "CatName"
dd.DataSource = dt
dd.DataBind()
End If
End If
Dim lb As DropDownList = TryCast(e.Row.FindControl("CatCode"), DropDownList)
ScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl(lb)
End Sub
Protected Sub CatCode_SelectedIndexChanged(sender As Object, e As EventArgs)
Me.ModalPopupExtender1.Show()
BindProdGrid()
End Sub
Protected Sub SelectRow(sender As Object, e As EventArgs)
Dim dt As New DataTable()
If ViewState("DataTable") Is Nothing Then
dt = New DataTable()
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Column2"), New DataColumn("Column4", GetType(String))})
Else
dt = DirectCast(ViewState("DataTable"), DataTable)
End If
Dim row As GridViewRow = TryCast(TryCast(sender, Button).NamingContainer, GridViewRow)
Dim desc As String = row.Cells(2).Text
Dim price As String = row.Cells(3).Text
dt.Rows.Add(desc, price)
Me.SalesGView.DataSource = dt
Me.SalesGView.DataBind()
ViewState("DataTable") = dt
End Sub
Private Sub BindProdGrid()
Dim conString As String = ConfigurationManager.ConnectionStrings("SY_InventoryConnectionString").ConnectionString
Dim rowIndex As Integer = 0
Dim catname As DropDownList = CType(SalesGView.Rows(rowIndex).Cells(1).FindControl("CatCode"), DropDownList)
Using con As New SqlConnection(conString)
Using cmd As New SqlCommand("select Product.CatID,Product.PName,Product.PDesc, " _
& " Product_Details.USP, Prod_Category.CatName " _
& " from Product inner join Product_Details on Product.CatID= Product_Details.CatID " _
& " inner join Prod_Category on Product_Details.CatID=Prod_Category.CatID where Prod_Category.CatName='" & (catname.SelectedItem.Text) & "' ")
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Dim dt As New DataTable()
sda.Fill(dt)
Me.ProdGView.DataSource = dt
Me.ProdGView.DataBind()
End Using
End Using
End Using
End Sub

getting value from datatable

Can anyone please tell me how to get value from datatable? I've only got one row and one column in the datatable and I need to get the value of the column to do calculations.
here's my script
<SCRIPT Language="VB" Runat="server">
Sub Page_Load(Source as object, e as EventArgs) handles me.load
Dim connectionstring As String = "DRIVER={MySQL ODBC 5.2 Unicode Driver}; SERVER=localhost; DATABASE=mydb; UID=andrew; PASSWORD=kh12345; OPTION=3"
Dim connectme As OdbcConnection = New OdbcConnection(connectionstring)
Dim sqlquery As String = "SELECT f_name, f_price from tbl_picture WHERE f_ID = 1"
Dim ODBCdataadapter As OdbcDataAdapter = New OdbcDataAdapter(sqlquery, connectme)
Dim ODBCdataset As DataSet = New DataSet()
ODBCdataadapter.Fill(ODBCdataset)
DataTable.DataSource = ODBCdataset
DataTable1.DataSource = ODBCdataset
Datatable.DataBind()
Datatable1.DataBind()
End Sub
</SCRIPT >
<ASP:Datagrid ID="Datatable1" Runat="server" AutoGenerateColumns="False"BorderStyle="None" GridLines="None">
<Columns>
<asp:BoundColumn
DataField="f_price"
ReadOnly="True"/>
</columns>
</asp:DataGrid>
and here's the calculation part
Private Sub CalculatePayment()
Dim c_loan_amount, c_Payment
Dim amount As String = Datatable1.Select("f_price")
c_loan_amount = amount - (amount * Down.Text * 0.01)
c_Payment = ((c_loan_amount * (Interest.Text * 0.01) * Year.Text) + c_loan_amount) / (Year.Text * 12)
Payment.Text = "RM " & Format(c_Payment, "#,##0.00")
End Sub
It should be the Dim amount as string part right? I'm kinda new, thanks in advance.
You need to define the row and item.
Try
Dim amount As String = Datatable1.tables(0).Rows(0).Item(1)
Actually you should rename datatable1 to dataset1 since a datatable is a possible member of a dataset. Its just to minimize confusion of what is what.
The Rows tells which row of the datatable. The item tells which index.
0 = f_name
1 = f_amount

Integer column in GridView is being sorted as a string

I have a GridView, which has a column as shown below:
<asp:TemplateField HeaderText="Vendor Path" SortExpression="DocumentTemplateFieldID" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="vendor" Height="10px" Width="60px" runat="server" Text='<%# Eval("DocumentTemplateFieldID") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
I allow sorting; however, it sorts it as if it were a string. In the database, it is an integer column.
How do I make my GridView accept that I'm really putting integers in there? I tried to convert it and that didn't work.
Code added:
Protected Sub TaskGridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs) Handles GridView1.Sorting
dsData = Session("dataTableView")
Dim sortExpression As String = e.SortExpression
Dim direction As String = String.Empty
If SortDirection = SortDirection.Ascending Then
SortDirection = SortDirection.Descending
direction = " DESC"
Else
SortDirection = SortDirection.Ascending
direction = " ASC"
End If
Dim table As DataTable = dsData
table.DefaultView.Sort = sortExpression + direction
GridView1.DataSource = table
GridView1.DataBind()
Session("dataTableView") = table
End Sub
Private Property SortDirection() As SortDirection
Get
If Session("sortDir") = Nothing Then
Session("sortDir") = SortDirection.Ascending
End If
Return CType(Session("sortDir"), SortDirection)
End Get
Set(ByVal value As SortDirection)
Session("sortDir") = value
End Set
End Property
Updated:
Public Function initialQuery(ByVal vendorID As String) As DataTable
Dim objConn As IDbConnection = Nothing
Dim dsData As New DataTable
Dim objParams(0) As IDbDataParameter
Try
objConn = DBAccess.GetConnection
objParams(0) = DBAccess.CreateParameter("DWSVendorID", DbType.String, vendorID, ParameterDirection.Input)
'Need to figure out how to add the below code:
If (Not IsNothing(vendorID) And Not vendorID = 0) Then
' strBlder.Append("WHERE B.DocumentProviderID = '" + vendorID.ToString + "' ")
End If
dsData = DBAccess.ExecuteDataTable(objConn, DataAccessHelper.Schema & "LLC.[DWSMappingToolInitialQuery]", objParams)
Finally
If Not objConn Is Nothing Then
DBAccess.CloseConnection(objConn)
End If
End Try
If dsData.Rows.Count > 0 Then
Return dsData
End If
Return Nothing
End Function

OnSelectedIndexChanged not working first selection, but will on subsequent selections

I have a listbox in a datagrid that is supposed to update upon selection change, and it does, but not on first try. only after it has posted back, after the first time it is clicked will it work as intended. any help appreciated.
Here is the front end portion of the datagrid with the listbox.
<asp:TemplateColumn HeaderText="Qty">
<ItemStyle HorizontalAlign="Center" Wrap="False" CssClass="grid" />
<HeaderStyle HorizontalAlign="Center" ForeColor="Black" Font-Bold="true" CssClass="grid" width="30" />
<ItemTemplate>
<asp:ListBox ID="lstQty" rows="1" runat="server" AutoPostBack="True" EnableViewState="True" OnSelectedIndexChanged="lstQtyUpdate" />
</ItemTemplate>
</asp:TemplateColumn>
Here is the page load section:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If Not IsPostBack Then
LoadCart()
cartList.Columns(0).Visible = False
If (cartList.Items.Count = 0) Then
cartList.Visible = False
lblEmptyMsg.Visible = True
Else
cartList.Visible = True
lblEmptyMsg.Visible = False
End If
End If
Catch ex As Exception
Errorlog(ex, "Cart.Page_Load()")
End Try
End Sub
This is the sub that is called with the onselectedindexchanged:
Protected Sub lstQtyUpdate(sender As Object, e As System.EventArgs)
Dim lb As New ListBox
lb = CType(sender, ListBox)
Dim thisID As String = lb.ClientID
Dim oiQty As Integer = ComFunctions.ConvertToInt(lb.SelectedItem.Value)
Dim oiID As Integer = 0
For Each item As DataGridItem In cartList.Items
lb = CType(item.FindControl("lstQty"), ListBox)
If (thisID = lb.ClientID) Then
oiID = ComFunctions.ConvertToInt(item.Cells(0).Text)
Exit For
End If
Next.....
Here is the binding for the datagrid, which may be the culprit.
Private Sub cartList_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles cartList.ItemDataBound
Try
Dim rbd As ImageButton
Dim lst As ListBox
Dim id As Integer = 0
Dim evTitle As String = String.Empty
Dim evImage As String = String.Empty
Dim capacity As Integer = 0
Dim soldseats As Integer = 0
Dim seatsleft As Integer = 0
Dim evdate As String = String.Empty
Dim evtimestart As String = String.Empty
Dim evtimeend As String = String.Empty
Dim EditLink As String = String.Empty
Dim DeletedLink As String = String.Empty
If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
id = DataBinder.Eval(e.Item.DataItem, "oi_id")
evTitle = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "title"))
evImage = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "image"))
evdate = ComFunctions.ConvertToDate(DataBinder.Eval(e.Item.DataItem, "eventsdatestart"))
capacity = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "capacity"))
seatsleft = (capacity - soldseats)
evtimestart = ComFunctions.Format_Time((DataBinder.Eval(e.Item.DataItem, "eventsdatestart")))
evtimeend = ComFunctions.Format_Time((DataBinder.Eval(e.Item.DataItem, "eventsdateend")))
Dim obj_DATA_Capacity As New DATA_Events()
soldseats = obj_DATA_Capacity.GetSeatsSold(id)
e.Item.Cells(0).Text = id
e.Item.Cells(1).Text = evTitle & "<br />" & evdate & " " & evtimestart & " - " & evtimeend
e.Item.Cells(2).Text = "<img src=""" & AppSettings("Events_ImagePath") & "/Thumb/" & evImage & """ width=""100"" />"
e.Item.Cells(3).Text = "$" & ComFunctions.ConvertToDecimal(DataBinder.Eval(e.Item.DataItem, "oi_price"), 2)
lst = CType(e.Item.FindControl("lstQty"), ListBox)
If seatsleft > 0 Then
'lst.Items.Add(0)
For I = 1 To seatsleft
lst.Items.Add(I)
Next
End If
lst.ID = id
lst.SelectedValue = ComFunctions.ConvertToInt(DataBinder.Eval(e.Item.DataItem, "oi_qty"))
rbd = CType(e.Item.FindControl("DeleteThis"), ImageButton)
rbd.CommandArgument = id
End If
Catch ex As Exception
Errorlog(ex, "quickCart.cartList_ItemDataBound()")
End Try
End Sub
I'm not sure why it does not work the first time, by the way, what does "not work" actually mean? But apart from that, your way to get the text of the first cell in the current DataGridItem is odd.
This is much more directly:
Dim lb = DirectCast(sender, ListBox)
Dim item = DirectCast(lb.NamingContainer, DataGridItem)
Dim oiID = Int32.Parse(item.Cells(0).Text)
Maybe it helps also get it working.

Resources