Dynamically changing a table cell background color in asp.net - asp.net

I have the following table row on my .aspx page:
<tr>
<td valign="bottom" style="width: 157px">Initial Requirements: </td>
<asp:Repeater ID="Repeater11" runat="server" DataSourceID="ObjectDataSource1">
<ItemTemplate>
<td valign="bottom" id="ReqStatus" runat="server" style="background-color: Gray">
<%#ReqStatus(CType(CType(Container.DataItem, System.Data.DataRowView).Row, DataSet1.DataTable1Row))%>
</td>
</ItemTemplate>
</asp:Repeater>
</tr>
In the code behind I have this function:
Protected Function ReqStatus(ByVal Project As DataSet1.DataTable1Row) As String
'Dim ReqTableCell As TableCell
'ReqTableCell = form1.FindControl("ReqStatus")
' Check the status of the Development Completed
Dim rightNow As Date = Now()
Dim dateDifference As TimeSpan
If Not Project.IsNull("Requirements_Target") Then
Dim ReqTargetDate As Date = Project.Requirements_Target
If Project.IsNull("Req_Date") Then
dateDifference = ReqTargetDate.Subtract(rightNow)
If dateDifference.Days > 0 Then
If dateDifference.Days >= 60 Then
'ReqTableCell.BackColor = Drawing.Color.Green
Return "<strong><font color='green'>" & dateDifference.Days & "</font></strong>"
ElseIf dateDifference.Days > 30 And dateDifference.Days < 60 Then
'ReqTableCell.BackColor = Drawing.Color.Yellow
Return "<strong><font color='yellow'>" & dateDifference.Days & "</font></strong>"
Else
'ReqTableCell.BackColor = Drawing.Color.Red
Return "<strong><font color='red'>" & dateDifference.Days & "</font></strong>"
End If
Else
'ReqTableCell.BackColor = Drawing.Color.Red
Dim pastDue As Int16 = (dateDifference.Days * -1)
Return "<strong><font color='red'>" & pastDue & "</font></strong> days past"
End If
End If
Else
End If
End Function
I can change the color of the return value based on conditional statements but cannot figure out the correct syntax to change the table cell back ground. My attempt is commented out.
How do I correctly declare the table cell? Findcontrol must not be the correct way.

Look this snipping of my solution:
TableRow tr = new TableRow();
TableCell tc = new TableCell { Text = "someText"};
tc.BackColor = ColorTranslator.FromHtml("#0000FF");
tc.ForeColor = ColorTranslator.FromHtml("#FFFFFF");
tc.Font.Bold = true;
tc.Font.Size = 16;
tr.Cells.Add(tc);
table.Rows.Add(tr);
After doing this and controlling all statements you can render the table in web page.

You can do that in Codebehind with full control (untested, only to give you the idea):
Private Sub Repeater1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
Select Case e.Item.ItemType
Case ListItemType.Item
Dim Project As DataSet1.DataTable1Row = DirectCast(DirectCast(e.Item.DataItem, System.Data.DataRowView).Row, DataSet1.DataTable1Row)
Dim tdReqStatus As HtmlTableCell = DirectCast(e.Item.FindControl("tdReqStatus"), HtmlTableCell)
Dim lblReqStatus As Label = DirectCast(e.Item.FindControl("lblReqStatus"), Label)
' Check the status of the Development Completed
Dim rightNow As Date = Now()
Dim dateDifference As TimeSpan
If Not Project.IsNull("Requirements_Target") Then
Dim ReqTargetDate As Date = Project.Requirements_Target
If Project.IsNull("Req_Date") Then
dateDifference = ReqTargetDate.Subtract(rightNow)
lblReqStatus.Font.Bold = True
If dateDifference.Days > 0 Then
If dateDifference.Days >= 60 Then
tdReqStatus.BgColor = "Green"
lblReqStatus.Text = dateDifference.Days.ToString
ElseIf dateDifference.Days > 30 And dateDifference.Days < 60 Then
tdReqStatus.BgColor = "Yellow"
lblReqStatus.Text = dateDifference.Days.ToString
Else
tdReqStatus.BgColor = "Red"
lblReqStatus.Text = dateDifference.Days.ToString
End If
Else
tdReqStatus.BgColor = "Red"
lblReqStatus.Text = (dateDifference.Days * -1).ToString
End If
End If
End If
End Select
End Sub
and on the aspx:
<table>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<tr>
<td valign="bottom" id="TdReqStatus" runat="server" >
<asp:label ID="lblReqStatus" runat="server" ></asp:label>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>

Related

Asp.net repeater databind on postback

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

Change cell in datagridview with databindings of SQL Server stored procedure

In SQL Server, I created a dynamic SQL stored procedure to query for the production record and pivoted in each month
In ASP.net using VB.net, I have a page with a DataGrid to display the query results dynamically using the DataBound method
I have a textbox to change the value of specific cell in the DataGridView like the production order quantity
Problem: when I assigned a value from textbox to the cell of datagridview, there is no change at all.
It just refreshed and get the value of the SQL query from the stored procedure. It always invokes the DataBound method of the DataGrid.
Questions: what is the technique so that I can assign the value to cell of DataGridView which is has data binding to the dynamic SQL Server stored procedure? The thing here is I want to save the changes in the DataGrid to another Table as the transnational.
Here is aspx code:
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="GeneratePlan.aspx.vb" Inherits="GeneratePlan" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<style type="text/css">
.style1
{
width: 55px;
}
.style2
{
width: 7px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<div>
<table width="100%">
<tr >
<td style="text-align: right;" >
<asp:Button ID="btnSave" runat="server" Text="Save Plan" CssClass="button" /><asp:Button ID="btnExit" runat="server" Text="Exit" CssClass="button" />
</td>
</tr>
<tr>
<td class="tdHeaderSubSection">
<asp:Label ID="lblReq" runat="server" Text=">> Generate Plan"></asp:Label>
</td>
</tr>
</table>
</div>
<div>
<table width ="100%">
<tr>
<td class="style1">
<asp:Label ID="Label3" runat="server" Text="BU"></asp:Label></td>
<td class="style2">::</td>
<td>
<asp:DropDownList ID="ddlBU" CssClass="Data" runat="server" Height="16px"
Width="130px">
</asp:DropDownList>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<asp:Button ID="btnGenerate" CssClass="button" runat="server" Text="Generate" />
<asp:Button ID="btnMove" CssClass="button" runat="server"
Text="Move MC#" />
<asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td colspan ="3"> <asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager> </td>
</tr>
</table>
</div>
<div id ="planDtl">
<asp:GridView ID="grdPlanDtl" AutoGenerateColumns = "False"
runat="server" Font-Size="10px">
</asp:GridView>
</div>
<div>
</div>
</asp:Content>
Here is the vb.net code:
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles grdPlanDtl.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ItemCode As New Label()
ItemCode.ID = "ItemCode"
ItemCode.Text = TryCast(e.Row.DataItem, DataRowView).Row("ItemCode").ToString()
e.Row.Cells(1).Controls.Add(ItemCode)
ItemCode.Width = 100
Dim Description As New Label()
Description.ID = "Description"
Description.Text = TryCast(e.Row.DataItem, DataRowView).Row("Description").ToString()
e.Row.Cells(2).Controls.Add(Description)
Description.Width = 200
Dim WH As New Label()
WH.ID = "WH"
WH.Text = TryCast(e.Row.DataItem, DataRowView).Row("WH").ToString()
e.Row.Cells(3).Controls.Add(WH)
e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Center
WH.Width = 10
Dim Customer As New Label()
Customer.ID = "Customer"
Customer.Text = TryCast(e.Row.DataItem, DataRowView).Row("CustName").ToString()
e.Row.Cells(4).Controls.Add(Customer)
Customer.Width = 150
Dim ST As New Label()
ST.ID = "ST"
ST.Text = FormatNumber(TryCast(e.Row.DataItem, DataRowView).Row("Std.Time").ToString(), 2)
e.Row.Cells(5).Controls.Add(ST)
e.Row.Cells(5).HorizontalAlign = HorizontalAlign.Right
ST.Width = 30
Dim TON As New Label()
TON.ID = "TON"
TON.Text = TryCast(e.Row.DataItem, DataRowView).Row("Tonnage").ToString()
e.Row.Cells(6).Controls.Add(TON)
e.Row.Cells(6).HorizontalAlign = HorizontalAlign.Right
TON.Width = 40
Dim MachineNo As New Label()
MachineNo.ID = "MachineNo"
MachineNo.Text = TryCast(e.Row.DataItem, DataRowView).Row("MachineNo").ToString()
e.Row.Cells(7).Controls.Add(MachineNo)
MachineNo.Width = 50
Dim TRP As New Label()
TRP.ID = "TRP"
TRP.Text = TryCast(e.Row.DataItem, DataRowView).Row("TRP").ToString()
e.Row.Cells(10).Controls.Add(TRP)
TRP.Width = 50
Dim FixedMachine As New Label()
Dim strFix As String
FixedMachine.ID = "FixedMachine"
FixedMachine.Text = TryCast(e.Row.DataItem, DataRowView).Row("FixedMachine").ToString()
e.Row.Cells(8).Controls.Add(FixedMachine)
FixedMachine.Width = 50
Dim chkSel As New CheckBox
chkSel.ID = "Move"
chkSel.Checked = False
e.Row.Cells(0).Controls.Add(chkSel)
Dim row As GridViewRow = TryCast(FixedMachine.NamingContainer, GridViewRow)
strFix = TryCast(row.FindControl("FixedMachine"), Label).Text
If String.IsNullOrEmpty(strFix) Then
chkSel.Enabled = True
Else
chkSel.Enabled = True
' chkSel.Enabled = False
End If
' AddGrdColumn("AvailableTime", "Available Time", "Lable")
'getsum
strGrpMC = TON.Text & MachineNo.Text
For i As Integer = 0 To iLoopMonth - 1
Dim ShpOrd As New Label()
Dim ShpOrdBckOrd As New TextBox()
Dim PlanM1 As New TextBox()
Dim ActualM1 As New TextBox()
Dim BackOrder As New Label()
Dim NeedHr As New Label()
ShpOrd.ID = "ShpOrd"
ShpOrd.Text = TryCast(e.Row.DataItem, DataRowView).Row(arrayMonth(i)).ToString()
e.Row.Cells(11 + (9 * i) + i).Controls.Add(ShpOrd)
ShpOrd.Width = 50
ShpOrdBckOrd.ID = "ShpOrdBckOrd"
ShpOrdBckOrd.Text = ShpOrd.Text
e.Row.Cells(12 + (9 * i) + i).Controls.Add(ShpOrdBckOrd)
ShpOrdBckOrd.Width = 50
PlanM1.ID = "PlanM1"
PlanM1.Text = ""
e.Row.Cells(13 + (9 * i) + i).Controls.Add(PlanM1)
PlanM1.Width = 50
ActualM1.ID = "ActualM1"
ActualM1.Text = ""
ActualM1.AutoPostBack = True
AddHandler ActualM1.TextChanged, AddressOf txtAcutal_TextChanged
e.Row.Cells(14 + (9 * i) + i).Controls.Add(ActualM1)
ActualM1.Width = 50
BackOrder.ID = "BackOrder"
BackOrder.Text = ""
BackOrder.Text = GetBackOrder(ShpOrdBckOrd.Text, ActualM1.Text)
e.Row.Cells(15 + (9 * i) + i).Controls.Add(BackOrder)
BackOrder.Width = 50
NeedHr.ID = "NeedHr"
NeedHr.Text = GetNeedHr(ShpOrd.Text, PlanM1.Text, ST.Text, TRP.Text)
e.Row.Cells(16 + (9 * i) + i).Controls.Add(NeedHr)
NeedHr.Width = 50
' summary
' MsgBox("strGrpMC : " & strGrpMC)
' MsgBox("strTmpGrpMC : " & strTmpGrpMC)
strGrpMC = TON.Text & "-" & MachineNo.Text
If strGrpMC <> strTmpGrpMC Then
LodTmeTT = 0
BalTmeTT = 0
strTmpGrpMC = strGrpMC
strGrpMC = TON.Text & "-" & MachineNo.Text
LodTmeTT = LodTmeTT + Convert.ToDouble(ChkNull(GetNeedHr(ShpOrd.Text, PlanM1.Text, ST.Text, TRP.Text), 0))
Else
strTmpGrpMC = strGrpMC
strGrpMC = TON.Text & "-" & MachineNo.Text
LodTmeTT = LodTmeTT + Convert.ToDouble(ChkNull(GetNeedHr(ShpOrd.Text, PlanM1.Text, ST.Text, TRP.Text), 0))
End If
'("#,##0.00")
Dim AvailableTime As New TextBox()
AvailableTime.ID = "AvailableTime"
AvailableTime.Text = TryCast(e.Row.DataItem, DataRowView).Row("AvailableTime").ToString()
e.Row.Cells(18 + (9 * i) + i).Controls.Add(AvailableTime)
AvailableTime.Width = 50
Dim Loading As New Label()
Loading.ID = "Loading"
Loading.Text = LodTmeTT
e.Row.Cells(17 + (9 * i) + i).Controls.Add(Loading)
Loading.Width = 50
Loading.Text = LodTmeTT
Dim balTme As New Label()
balTme.ID = "balTme"
balTme.Text = GetBalTime(AvailableTime.Text, Loading.Text)
e.Row.Cells(19 + (9 * i) + i).Controls.Add(balTme)
balTme.Width = 50
Dim RatioTme As New Label()
RatioTme.ID = "RatioTme"
RatioTme.Text = GetLoadRatioTime(Loading.Text, AvailableTime.Text)
e.Row.Cells(20 + (9 * i) + i).Controls.Add(RatioTme)
RatioTme.Width = 50
Next
End If
End Sub

Code works when single user viewing but page goes crazy when multiple users are viewing same page

Below are the aspx and vb code file for the problem page. The problem page works when only one user is logged in and viewing. Although, when another user logs in and views the same page then this happens ard(i) <> xxz(i)
Then Response.Redirect("../vwall/vwall_tour.aspx?tour_id=" & ddlAvailableTours.SelectedValue)
End If
And the page reloads repetitively. So, ard(i) <> xxz(i) happens when multiple users are logged in viewing. How can one user be affected by another user viewing and making selections on the same page? Everything is fine with one user not when multiple users are playing around on this page.
<%# Page Language="VB" AutoEventWireup="false" CodeFile="vwall_tour.aspx.vb" Inherits="vwall_tour2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="../js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="../flowplayer/flowplayer-3.2.4.min.js" type="text/javascript"> </script>
<script type="text/javascript" src="../flowplayer/flowplayer-3.2.4.min.js"> </script>
<script type="text/javascript">
function OpenTourManager() {
document.location.href = 'manage_tours.aspx';
//document.location.href = 'manage_tours.aspx?tourid=' +
document.getElementById('ddlAvailableTours').options[document.getElementById('dd lAvailableTours').selectedIndex].value;
}
</script>
</head>
<body>
<form id="form1" style="height:100%; vertical-align:middle" runat="server">
<table border=0 cellpadding=0 cellspacing=0 width=100% background="../images/gray.jpg">
<tr>
<td><img src="../images/cyberco-banner.gif" height="35px" alt="CYBERCO" /></td>
<td><asp:Button runat="server" ID="btnSignOut" Text = "Sign Out" /></td>
<td><input type = "button" value ="Change Password" onclick="javascript: document.location.href = '../changepassword.aspx';" id="btnChangePass"/></td>
<td></td>
<td><asp:Label ID ="lblUsername" runat="server"> </asp:Label></td>
<td width="400px"> </td>
<td><asp:DropDownList ID = "ddlAvailableTours" runat="server" Width="250px" OnSelectedIndexChanged="SelectionChanged" AutoPostBack="True"></asp:DropDownList></td>
<td><asp:Button runat="server" id="btnSetDefaultTour" Text="Set as default" /></td>
<td><input type='button' value='Manage Video Wall' onclick="javascript: OpenTourManager(); "/></td>
<td><input type="hidden" id ="startstop" onclick= "javascript: vwallStartStop();" /></td><td>(Fullscreen-> F11)<!--<input type="button" value="Fullscreen mode" onclick=" toggleFull()" />--></td>
</tr>
</table>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" /><asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="5000" /><table border=0 cellspacing=0 cellpadding=0 id="main" style="height:100%; width:100%; padding:0px; margin:0px; background-color:#000000;">
<tr><td align=right style="vertical-align:top; border:0px; padding:0px;" align=top padding=0 valign=top class='header_row' id="tdheader">
<div id="header" class="style1">
<div id = "clockid" style="visibility:hidden; border:0px; padding:0px;" > clock</div>
<!---<table border=2 cellpadding=0 cellspacing=0 padding=0 style="text-align:center;height:564;width:100%;padding:0;margin:0;" bgcolor=#425081 >-->
<tr>
<td padding=0 width=0px" width=0%>
<asp:UpdatePanel ID="up_setdefault" UpdateMode="Conditional" runat="server" RenderMode="Inline">
<Triggers><asp:AsyncPostBackTrigger ControlID="Timer1" /></Triggers>
<ContentTemplate>
<asp:Label id="StockPrice" runat="server"></asp:Label>
<fieldset style="border:0; margin=0px; cellpadding=0; padding=0px; cellspacing=0; align=right; width=0px;" width=0%>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<!--</table>-->
<tr><td padding=0 style="border:0px; padding:0px;"> <asp:Literal runat="server" ID="litTableInner1"></asp:Literal></td></tr></table>
<!-- cut script -->
<asp:Literal runat="server" ID="litCreatePlayersScript"></asp:Literal>
<asp:Literal runat="server" ID="litCreateUpdateScript"></asp:Literal>
</form>
</body>
</html>
Then the vb code file...
Imports System.Data.SqlClient
Imports System.Data
Imports System.Net
Public Class vwall_tour2
Inherits System.Web.UI.Page
Public Shared xxz(9) As String
'Protected default_wstr As String = ConfigurationManager.AppSettings("default_wstr")
'Dim xxz = {"Off", "Off", "Off", "Off", "Off", "Off", "Off", "Off", "Off"}
Protected Sub vwall_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim thisUser As New cyberUser(User.Identity.Name, (ConfigurationManager.ConnectionStrings("timsConnectionString").ToString()))
Me.lblUsername.Text = User.Identity.Name
Dim auto_refresh_users As String()
auto_refresh_users = Split(ConfigurationManager.AppSettings("wall_logins_noexpire").ToString, ",")
Dim lausername As String
For Each lausername In auto_refresh_users
If Trim(lausername) = User.Identity.Name Then
Dim s As New StringBuilder
s.AppendLine("setTimeout ( 'reloadit();', reloadtime ); ")
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "loadAfterSigninFromVwall", s.ToString(), True)
Exit For
End If
Next
' if not found, will time out after 2 hrs and have to log in again
Dim selected_tour_id As Integer
If Not Page.IsPostBack Then
'btnAdmin.Visible = False
Dim ds As DataSet
ds = dataFetcher.fillDataset("User_SelectTours " & thisUser.userid, ConfigurationManager.ConnectionStrings("timsConnectionString").ConnectionString, False)
ddlAvailableTours.DataSource = ds
ddlAvailableTours.DataValueField = "tour_id"
ddlAvailableTours.DataTextField = "tour_name"
ddlAvailableTours.DataBind()
If Not Request.QueryString("tour_id") Is Nothing Then
Try
selected_tour_id = Convert.ToInt16(Request.QueryString("tour_id"))
Catch ex As Exception
selected_tour_id = ddlAvailableTours.Items(0).Value
End Try
ElseIf thisUser.default_tour_id <> -1 Then
selected_tour_id = thisUser.default_tour_id
Else
selected_tour_id = ddlAvailableTours.Items(0).Value
End If
Dim itemfound As Boolean = False
Dim item As ListItem
For Each item In ddlAvailableTours.Items
If item.Value = selected_tour_id Then
item.Selected = True
itemfound = True
Exit For
End If
Next
If Not itemfound Then 'default or querystring tour_id not found
ddlAvailableTours.SelectedIndex = -1
ddlAvailableTours.Items(0).Selected = True
End If
Me.ddlAvailableTours_SelectedIndexChanged(Nothing, Nothing)
End If ' notpostback
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
StockPrice.Text = DateTime.Now.ToLongTimeString()
'TimeOfPrice.Text = DateTime.Now.ToLongTimeString()
End Sub
Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs)
If User.Identity.IsAuthenticated Then
Dim thisUser As New cyberUser(User.Identity.Name, (ConfigurationManager.ConnectionStrings("timsConnectionString").ToString()))
''load the page
Dim selected_tour_id As Integer
selected_tour_id = ddlAvailableTours.SelectedValue
Dim t As user_Tour
For Each t In thisUser.user_Tours
If t.tour_id = selected_tour_id Then
StockPrice.Text = GetOverrideStatus(t)
Exit For
End If
Next
''''''
End If
End Sub
Function GetOverrideStatus(ByVal tour As user_Tour) As String
On Error Resume Next
Dim rstrf As New StringBuilder
'create the playlist string
Dim playlists As String()
Dim phaseitems As String()
Dim numPlayers As Integer = tour.num_cols * tour.num_rows
ReDim playlists(numPlayers - 1)
Dim dsd As DataSet
Dim stream_address As String
Dim VideoLabel As Object
Dim ard(9) As String
'ard = {"Off", "Off", "Off", "Off"}
Array.Clear(ard, 0, ard.Length)
For Each p In tour.phases
phaseitems = p.str_all_items.Split(",")
For i = 0 To numPlayers - 1
Dim s_id As String = phaseitems(i)
If p.tour_phase_id > 1 Then
playlists(i) &= ", "
End If
If Not s_id = "empty" And Not s_id = "" Then
dsd = dataFetcher.fillDataset("ListImageAllFields '" & s_id & "'", ConfigurationManager.ConnectionStrings("timsConnectionString").ConnectionString, False)
ard(i) = dsd.Tables(0).Rows(0).Item("active_override")
' rstrf.AppendLine("A" + ard(i))
' rstr.AppendLine(ard(i))
If ard(i) <> xxz(i) Then
'Response.Write("<script>window.opener.location.href = window.opener.location.href </script>")
Response.Redirect("/media_dev/vwall/vwall_tour.aspx?tour_id=" & ddlAvailableTours.SelectedValue)
End If
' If ds.Tables(0).Rows(0).Item("active_override") = "On" Then
'Response.Redirect("../default.aspx")
' End If
'playlists(i) &= "'" & stream_address & "'"
Else ' empty spot
'playlists(i) &= "'../images/tours/tour_empty_space.png'"
End If 's not blank
Next
Next
'If ard(0) <> xxz(0) Or ard(1) <> xxz(1) Or ard(2) <> xxz(2) Or ard(3) <> xxz(3) Then
'Response.Write("<script>window.opener.location.href = window.opener.location.href </script>")
'Response.Redirect("../vwall/vwall_tour.aspx?tour_id=" & ddlAvailableTours.SelectedValue)
' End If
'Return ard.ToString("C")
Return ard(0).ToString() + ard(1).ToString() + ard(2).ToString() + ard(3).ToString() + ard(4).ToString() + ard(5).ToString() + ard(6).ToString() + ard(7).ToString() + ard(8).ToString()
End Function
Sub writeTableString(ByVal tour As user_Tour)
Dim returnstr As New StringBuilder
Dim td_width, td_height As Integer
td_width = Math.Floor(100 / tour.num_cols)
td_height = Math.Floor(100 / tour.num_rows) 'was 90
Dim rstr As New StringBuilder
Dim countinner, countouter As Integer
countinner = 0
countouter = 0
Do
rstr.AppendLine("<tr>")
Do
rstr.AppendLine("<td style='width:" & td_width & "%; height:" & td_height & "%;'><a runat='server' id='player" & (countinner + (countouter * tour.num_cols)) & "' href='#'></a></td>")
countinner += 1
Loop Until countinner = tour.num_cols
rstr.AppendLine("</tr>")
countouter += 1
countinner = 0
Loop Until countouter = tour.num_rows
rstr.AppendLine("<script> document.getElementById('tdheader').colSpan='" & tour.num_cols & "';</script>")
Me.litTableInner1.Text = rstr.ToString
End Sub
Sub writeScriptForPlayers(ByVal tour As user_Tour)
On Error Resume Next
Dim rstr As New StringBuilder
'create the playlist string
Dim playlists As String()
Dim phaseitems As String()
Dim numPlayers As Integer = tour.num_cols * tour.num_rows
ReDim playlists(numPlayers - 1)
Dim ds As DataSet
Dim stream_address As String
Dim VideoLabel As Object
Array.Clear(xxz, 0, xxz.Length)
For Each p In tour.phases
phaseitems = p.str_all_items.Split(",")
For i = 0 To numPlayers - 1
Dim s_id As String = phaseitems(i)
If p.tour_phase_id > 1 Then
playlists(i) &= ", "
End If
If Not s_id = "empty" And Not s_id = "" Then
ds = dataFetcher.fillDataset("ListImageAllFields '" & s_id & "'", ConfigurationManager.ConnectionStrings("timsConnectionString").ConnectionString, False)
xxz(i) = ds.Tables(0).Rows(0).Item("active_override")
rstr.AppendLine("B" + xxz(i))
If ds.Tables(0).Rows(0).Item("active_override") = "Off" Then
If ds.Tables(0).Rows(0).Item("hq_viewcapable") = "Y" Then
If ds.Tables(0).Rows(0).Item("hq_firstresponder") = "Y" Then
stream_address = ds.Tables(0).Rows(0).Item("AddressRTMP_hq").ToString()
Else
stream_address = ds.Tables(0).Rows(0).Item("AddressRTMP").ToString()
End If
Else
stream_address = ds.Tables(0).Rows(0).Item("AddressRTMP").ToString()
End If
Else : stream_address = "../overridden.swf"
End If
playlists(i) &= "'" & stream_address & "'"
' Else ' empty spot
'playlists(i) &= "'../images/tours/tour_empty_space.png'"
End If 's not blank
Next
Next
' end creating playlist strings
Dim countinner, countouter As Integer
countinner = 0
countouter = 0
rstr.AppendLine("<script type='text/javascript'>")
Do
Do
countinner += 1
Loop Until countinner = tour.num_cols
countouter += 1
countinner = 0
Loop Until countouter = tour.num_rows
''write the players
countinner = 0
countouter = 0
Do
Do
rstr.AppendLine("flowplayer('player" & (countinner + (countouter * tour.num_cols)) & "', '../flowplayer/flowplayer.commercial-3.2.5.swf', { key: '#$34tg5y5y5hytr', logo: { url:'../images/CYBERLOGO.PNG', opacity: 0.65, top: 10, right: 10, fullscreenOnly: false }, playlist: [" & playlists(countinner + (countouter * tour.num_cols)) & "], clip: { provider: 'CYBERCO', live: true, onBegin: function () { clearTimer(); }, onBeforeFinish: function () { this.getPlugin('play').hide(); return false; } }, onLoad: function () { setTimer(); }, onPlaylistReplace: function () { setTimer(); }, onError: function () { error(); }, play:{ opacity:0.0, label:null, replayLabel: null }, onFinish: function(){ this.play(); }, plugins: { CYBERCO: { url: '../flowplayer/flowplayer.rtmp-3.2.3.swf', live: true, controls: { autoHide: true}}} })")
'logo: { url:'/first_resp/images/cyberco-banner.gif', opacity: 0.4, bottom: 20, right: 20 },
' rstr.AppendLine("flowplayer('player" & (countinner + (countouter * tour.num_cols)) & "', '../flowplayer/flowplayer.commercial-3.2.5.swf', { key: '#$34tg5y5y5hytr', logo: { url:'..images/CYBERLOGO.PNG', opacity: 0.65, top: 10, right: 10, fullscreenOnly: false }, playlist: [" & playlists(countinner + (countouter * tour.num_cols)) & "], clip: { provider: 'CYBERCO', live: true, onBegin: function () { clearTimer(); }, onBeforeFinish: function () { this.getPlugin('play').hide(); } }, onLoad: function () { setTimer(); }, onPlaylistReplace: function () { setTimer(); }, onError: function () { error(); }, plugins: { CYBERCO: { url: '../flowplayer/flowplayer.rtmp-3.2.3.swf', live: true, controls: { autoHide: true}}} })")
countinner += 1
Loop Until countinner = tour.num_cols
countouter += 1
countinner = 0
Loop Until countouter = tour.num_rows
rstr.AppendLine("</script>")
Me.litCreatePlayersScript.Text = rstr.ToString
End Sub
Public Function loadWallData(ByVal wstr As String) As DataSet
Try
'If Me.loggedin Then
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("timsConnectionString").ConnectionString)
Dim dsStreams As New DataSet
'add the quotes to the strings
wstr = wstr.Replace(",", "','")
wstr = "'" & wstr & "'"
Dim sqltext As String = "[User_SelectVWallStreams] " & wstr
Dim da As New SqlDataAdapter
Dim Command As New SqlCommand
Command = New SqlCommand(sqltext, conn)
'Command.CommandType = CommandType.StoredProcedure
da.SelectCommand = Command
da.Fill(dsStreams)
Return dsStreams
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function
Protected Sub SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Redirect("../vwall/vwall_tour.aspx?tour_id=" & ddlAvailableTours.SelectedValue)
End Sub
Protected Sub ddlAvailableTours_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlAvailableTours.SelectedIndexChanged
If User.Identity.IsAuthenticated Then
Dim thisUser As New cyberUser(User.Identity.Name, (ConfigurationManager.ConnectionStrings("timsConnectionString").ToString()))
''load the page
Dim selected_tour_id As Integer
selected_tour_id = ddlAvailableTours.SelectedValue
If selected_tour_id = thisUser.default_tour_id Then
Me.btnSetDefaultTour.Enabled = False
Else
Me.btnSetDefaultTour.Enabled = True
End If
Dim t As user_Tour
For Each t In thisUser.user_Tours
If t.tour_id = selected_tour_id Then
'selected_tour_id = ddlAvailableTours.SelectedValue
writeTableString(t)
writeScriptForPlayers(t)
' Response.Redirect("../vwall/vwall_tour.aspx?tour_id=" & selected_tour_id)
Exit For
End If
Next
End If
End Sub
Protected Sub btnSetDefaultTour_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSetDefaultTour.Click
If User.Identity.IsAuthenticated Then
Dim thisUser As New cyberUser(User.Identity.Name, (ConfigurationManager.ConnectionStrings("timsConnectionString").ToString()))
thisUser.UpdateDefaultTour(Me.ddlAvailableTours.SelectedValue)
Me.btnSetDefaultTour.Enabled = False
End If
End Sub
Protected Sub btnSignOut_Click(sender As Object, e As System.EventArgs) Handles btnSignOut.Click
FormsAuthentication.SignOut()
'delete the cookie (or will be infinite loop)
'delete the cookie
Dim aCookie As HttpCookie
If Request.Cookies("cyber_Load") Is Nothing Then
'Response.Cookies.Add(aCookie)
Response.Redirect("../default.aspx")
Else
aCookie = Request.Cookies("cyber_Load")
aCookie.Expires = DateTime.Now.AddDays(-1D)
Response.Cookies.Add(aCookie)
Response.Redirect("../default.aspx")
End If
End Sub
End Class
The reason for that is:
Public Shared xxz(9) As String
By declaring the variable as Shared, there only ever exists one instance of the variable, shared by all users. Whatever one user puts in the variable is visible to all other users.
You would rather store the array in the Session collection, so that each user can have one array of their own.
Declare the array variable as an instance variable, so that it's local to the current page, and don't create the actual array yet:
Public xxz As String()
In the beginning of the code, get the array from the Session collection, or create a new one if there is no array since before:
xxz = DirectCast(Session("xxz"), String())
If xxz Is Nothing Then
ReDim xxz(9)
Session("xxz") = xxz
End If

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.

HELP! Get value of dynamic control radio button!

I am looking into create a dynamic survey as posted in Get User Input From Dynamic Controls but with some different environment.
Below is what i am trying to do:
First when the user click the button, it will populate a dynamic table with radio button for the survey questionnaire inside a placeholder. However, I was unable to get its value (for score calculation) after clicking the submit button.
All the dynamic controls was gone.
Beside i am using an ajax extension (updatePanel) for the development and
I have been look into viewstate but I have no idea with it.
Does anyone have any ideas?
Here i included some of my code:
Page
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnTest" runat="server" Text="Take Test" OnClick="btnTest_Click" Visible="False" />
<asp:Label ID="lblTestErrMsg" runat="server"
ForeColor="Red"></asp:Label><br />
<table id="tblTest" runat="server" style="width: 100%">
<tr>
<td>
<asp:PlaceHolder ID="phQuestionnaire" runat="server"></asp:PlaceHolder>
<br />
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblResult" runat="server"></asp:Label></td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Create Dynamic Table function
*v_dtTable and v_dtTable2 contains the data from database
Private Sub CreateDynamicTable(ByVal v_dtTable As Data.DataTable, ByVal v_dtTable2 As Data.DataTable)
Me.phQuestionnaire.Controls.Clear()
Dim cols As Integer = v_dtTable.Rows.Count + 2
Dim rows As Integer = v_dtTable2.Rows.Count + 1
Dim mid As Integer = v_dtTable.Rows.Count / 2
Dim tbl As Table = New Table()
tbl.ID = "tblQs"
tbl.BorderWidth = 1
tbl.CellPadding = 0
tbl.CellSpacing = 0
tbl.Width = 500
tbl.EnableViewState = True
Me.phQuestionnaire.Controls.Add(tbl)
For i As Integer = 0 To rows - 1
Dim tr As TableRow = New TableRow()
Dim rowCnt As Integer = 1
Dim colCnt As Integer = 0
For j As Integer = 0 To cols - 1
Dim tc As TableCell = New TableCell()
tc.BorderWidth = 1
Dim lbl As Label = New Label()
Dim bol As Boolean = False
If i = 0 Then
If j = 0 Then
tc.Text = "No."
ElseIf j = 1 Then
tc.Text = "Question"
Else
tc.Text = v_dtTable.Rows(j - 2).Item("scoreName")
tc.HorizontalAlign = HorizontalAlign.Center
End If
tc.BackColor = Drawing.Color.DeepSkyBlue
tc.ForeColor = Drawing.Color.White
Else
If v_dtTable2.Rows(i - 1).Item("isHeader") Then
bol = True
tc.Text = v_dtTable2.Rows(i - 1).Item("TestQuestion")
tc.Style("font-weight") = "bold"
ElseIf j = 0 Then
tc.Text = rowCnt
rowCnt += 1
ElseIf j = 1 Then
tc.Text = v_dtTable2.Rows(i - 1).Item("TestQuestion")
Else
Dim rBtn As RadioButton = New RadioButton
rBtn.GroupName = "rBtn" & rowCnt
rBtn.ID = "rBtn_" & rowCnt & "_" & colCnt
rBtn.InputAttributes("value") = v_dtTable.Rows(j - 2).Item("scoreValue")
colCnt += 1
If j = mid + 2 Then
rBtn.Checked = True
End If
tc.Controls.Add(rBtn)
tc.HorizontalAlign = HorizontalAlign.Center
End If
End If
If bol Then
tc.ColumnSpan = cols - 1
tr.Cells.Add(tc)
Exit For
Else
tr.Cells.Add(tc)
End If
Next j
tbl.Rows.Add(tr)
Next i
End Sub
Calculate Score function
Private Sub subCalculateScore()
Dim tblQs As Table = CType(Me.phQuestionnaire.FindControl("tblQs"), Table)
Dim rb As New RadioButton
Dim score As Integer = 0
If Me.phQuestionnaire.FindControl("tblQs") Is Nothing Then
Else
For Each tr As TableRow In tblQs.Rows
For Each tc As TableCell In tr.Cells
For Each c As Control In tc.Controls
If c.GetType.ToString = rb.GetType.ToString Then
Dim rBtn As RadioButton = CType(c, RadioButton)
If rBtn.Checked Then
Dim strScore As String = rBtn.InputAttributes("value")
score += CInt(strScore)
End If
End If
Next
Next
Next
End If
Me.Label1.Text = score
End Sub
View source for the dynamic generated table
<table id="tblQs" cellspacing="0" cellpadding="0" border="0" style="border-width:1px;border-style:solid;width:500px;border-collapse:collapse;"><tr>
<td style="border-width:1px;border-style:solid;"><span>No.</span></td>
<td style="border-width:1px;border-style:solid;"><span>Question</span></td>
<td style="border-width:1px;border-style:solid;"><span>dislike</span></td>
<td style="border-width:1px;border-style:solid;"><span>normal</span></td>
<td style="border-width:1px;border-style:solid;"><span>like</span></td>
<td style="border-width:1px;border-style:solid;"><span>vry likes</span></td></tr><tr>
<td style="border-width:1px;border-style:solid;"><span>1</span></td>
<td style="border-width:1px;border-style:solid;"><span>question 1</span></td>
<td style="border-width:1px;border-style:solid;">
<input id="rBtn_1_0" type="radio" name="rBtn1" value="rBtn_1_0" value="0" /></td>
<td style="border-width:1px;border-style:solid;">
<input id="rBtn_1_1" type="radio" name="rBtn1" value="rBtn_1_1" value="1" /></td>
<td style="border-width:1px;border-style:solid;">
<input id="rBtn_1_2" type="radio" name="rBtn1" value="rBtn_1_2" checked="checked" value="2" /></td>
<td style="border-width:1px;border-style:solid;">
<input id="rBtn_1_3" type="radio" name="rBtn1" value="rBtn_1_3" value="3" /></td></tr></table>
If the names of the generated radio button groups are predictable enough, you could get their values by inspecting the Request.Form collection. Assuming the group names are rBtn1, rBtn2, etc, the post data will look something like rBtn1=6&rBtn2=7. That means you can do this:
Dim i as Integer
Dim score as Integer = 0
For i = 1 To expectedNumRows
score += CInt(Request.Form("rBtn" & i))
Next
This will help you work around the fact that the controls that were generated before no-longer exist. You should poke around in the debugger and inspect the Request.Form collection so you can get familiar with what's in there.
(my apologies if my VB.NET is incorrect; I'm used to C#)
Thank you Jacob for his solution.
I am able to calculate the score by making some modification for the ID assignment.
I added its value at the back of the id since the value generated is the same with the ID as shown in the view source
rBtn.ID = "rBtn[" & rowCnt & "][" & colCnt & "]_" & value (eg. rBtn[1][0]_2 )
Then, i used substring to get and calculate the score as shown in the subCalculateScore function below:
Private Function subCalulateScore() As Integer
Dim score As Integer = 0
Dim expectedNumRows As Integer = Me.qsNum.Text
For i As Integer = 1 To expectedNumRows
Dim strBtn As String = Request.Form("rBtn" & i)
If Not strBtn Is Nothing Then
If strBtn.LastIndexOf("_") <> -1 Then
Dim strScore As String = strBtn.Substring(strBtn.LastIndexOf("_") + 1)
score += CInt(strScore)
End If
End If
Next
Return score
End Function
Haha.. sound like a lousy way to do it :p
Once again, thanks for your help, Jacob.
Always welcome for any other solution ^^
I figured out yesterday that you can actually make your app work like normal by loading the control tree right after the loadviewstateevent is fired. if you override the loadviewstate event, call mybase.loadviewstate and then put your own code to regenerate the controls right after it, the values for those controls will be available on page load. In one of my apps I use a viewstate field to hold the ID or the array info that can be used to recreate those controls.
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
MyBase.LoadViewState(savedState)
If IsPostBack Then
CreateMyControls()
End If
End Sub

Resources