DataTable Not Binding to ASP:DropDownList - asp.net

I would think this code should be very simple and straight forward but I'm having issues. The sub below is called on the page load. It is nestled between similar functions that load other drop down lists. All the rest of the drop downs are populating but these are not. The other drop downs subs use the same With clause but are binding to a DataSet (of one table) that is populated with a stored procedure call to the database rather than binding to a static DataTable.
VB Code:
Private Sub LoadEquations()
Dim dtMain As DataTable
Dim dtGypsum As DataTable
Dim dr As DataRow
dtMain.Columns.Add("Text")
dtMain.Columns.Add("Value")
dr = dtMain.NewRow
dr.Item("Text") = " "
dr.Item("Value") = "0"
dtMain.Rows.Add(dr)
dtMain.AcceptChanges()
dr = dtMain.NewRow
dr.Item("Text") = "Build"
dr.Item("Value") = "B"
dtMain.Rows.Add(dr)
dtMain.AcceptChanges()
dr = dtMain.NewRow
dr.Item("Text") = "Maintain"
dr.Item("Value") = "M"
dtMain.Rows.Add(dr)
dtMain.AcceptChanges()
With Me.ddMainEquation
.DataSource = dtMain
.DataTextField = "Text"
.DataValueField = "Value"
.DataBind()
End With
dtGypsum.Columns.Add("Text")
dtGypsum.Columns.Add("Value")
dr = dtGypsum.NewRow
dr.Item("Text") = " "
dr.Item("Value") = "0"
dtGypsum.Rows.Add(dr)
dtGypsum.AcceptChanges()
dr = dtGypsum.NewRow
dr.Item("Text") = "pH Base"
dr.Item("Value") = "P"
dtGypsum.Rows.Add(dr)
dtGypsum.AcceptChanges()
dr = dtGypsum.NewRow
dr.Item("Text") = "% Sodium Base"
dr.Item("Value") = "S"
dtGypsum.Rows.Add(dr)
dtGypsum.AcceptChanges()
With Me.ddGypsumEquation
.DataSource = dtGypsum
.DataTextField = "Text"
.DataValueField = "Value"
.DataBind()
End With
End Sub
DNN / ASP Code:
<tr>
<td>
<asp:Label ID="lblMainEquation" runat="server"
CssClass="FormLabelLeft">Main Equation</asp:Label></td>
<td>
<asp:Label ID="lblGypsumEquation" runat="server"
CssClass="FormLabelLeft">Gypsum Equation</asp:Label></td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddMainEquation" TabIndex="34"
runat="server" CssClass="FormField"></asp:DropDownList></td>
<td>
<asp:DropDownList ID="ddGypsumEquation" TabIndex="34"
runat="server" CssClass="FormField"></asp:DropDownList></td>
</tr>
What am I missing? I am using an older DNN platform 2.0.

You should declare your datatable as a New object
Try below:
Private Sub LoadEquations()
Dim dtMain As New DataTable
Dim dtGypsum As New DataTable
Dim dr As DataRow
dtMain.Columns.Add("Text")
dtMain.Columns.Add("Value")
dr = dtMain.NewRow
dr.Item("Text") = " "
dr.Item("Value") = "0"
dtMain.Rows.Add(dr)
dr = dtMain.NewRow
dr.Item("Text") = "Build"
dr.Item("Value") = "B"
dtMain.Rows.Add(dr)
dr = dtMain.NewRow
dr.Item("Text") = "Maintain"
dr.Item("Value") = "M"
dtMain.Rows.Add(dr)
With ddMainEquation
.DataSource = dtMain
.DataTextField = "Text"
.DataValueField = "Value"
.DataBind()
End With
dtGypsum.Columns.Add("Text")
dtGypsum.Columns.Add("Value")
dr = dtGypsum.NewRow
dr.Item("Text") = " "
dr.Item("Value") = "0"
dtGypsum.Rows.Add(dr)
dr = dtGypsum.NewRow
dr.Item("Text") = "pH Base"
dr.Item("Value") = "P"
dtGypsum.Rows.Add(dr)
dr = dtGypsum.NewRow
dr.Item("Text") = "% Sodium Base"
dr.Item("Value") = "S"
dtGypsum.Rows.Add(dr)
With ddGypsumEquation
.DataSource = dtGypsum
.DataTextField = "Text"
.DataValueField = "Value"
.DataBind()
End With
End Sub
By the way, AcceptChanges() is not really required for each time after you add in a new row. Calling AcceptChanges after adding new row will actually turn the DataRowState of your newly added DataRow from Added to Unchanged. check this out.

Related

calculate monthly depreciation of an asset in asp.net using double line balance

i have successfully been able to calculate a monthly depreciable amount of an asset using straight line formula
I'm having issues using the doubline balance line formular as I'm not getting my expected result
formula = (2* depreciation ) / lifeMonth
below is my backend code
Dim acquiredDate As DateTime = Convert.ToDateTime(2019, 11, 15)
Dim startMonth As DateTime = Convert.ToDateTime(2019, 11, 15)
Dim depreciation As Double = "10000"
Dim slavege As Double = "10"
Dim lifeMonth As Integer = "12"
Dim dt As DataTable = New DataTable()
dt.Columns.Add("Month")
dt.Columns.Add("Depreciation", GetType(Decimal))
dt.Columns.Add("Accumulated", GetType(Decimal))
dt.Columns.Add("BookValue", GetType(Decimal))
Dim i As Integer = 0
Dim depreciationExpense As Double = (2 * depreciation) / lifeMonth
Dim bookValue As Double = depreciation - depreciationExpense
Dim newDepreciationExpense As Double = 0
While startMonth < acquiredDate.AddMonths(lifeMonth)
Dim dr As DataRow = dt.NewRow()
dr("Month") = startMonth.ToString("MMM yyyy")
dr("Depreciation") = depreciationExpense
If i = 0 Then
dr("Accumulated") = Math.Round(depreciationExpense, 2)
dr("BookValue") = Math.Round(bookValue, 2)
newDepreciationExpense = depreciationExpense
Else
newDepreciationExpense = newDepreciationExpense + depreciationExpense
bookValue = bookValue - depreciationExpense
dr("Accumulated") = Math.Round(newDepreciationExpense, 2)
dr("BookValue") = Math.Round(bookValue, 2)
End If
dt.Rows.Add(dr)
startMonth = startMonth.AddMonths(1)
i += 1
End While
Me.gvData.DataSource = dt
Me.gvData.DataBind()
below is my front end(html)
<asp:GridView runat="server" ID="gvData" AutoGenerateColumns="false" CssClass="table table-bordered table-striped table-depreciation">
<Columns>
<asp:BoundField DataField="Month" HeaderText="Month" />
<asp:BoundField DataField="Depreciation" HeaderText="Depriciation Expenses" DataFormatString="{0:N2}" />
<asp:BoundField DataField="Accumulated" HeaderText="Accumulate Deprication at Month-End" DataFormatString="{0:N2}" />
<asp:BoundField DataField="BookValue" HeaderText="Book Value at Month-End" DataFormatString="{0:N2}" />
</Columns>
</asp:GridView>
the result I'm getting
my expected result

If statement using SqlDataReader value not working

I am working on a cart/basket page of an e-commerce site. Specifically: "-" link button to decrease quantity of selected product by 1 in the cart, and later the "+" link button to increase quantity of selected product by 1 in the cart.
For the "-" button I am doing:
Check the CategoryID of the product selected.
If the CategoryID = 3 or 4, then:
Check if the quantity of the selected product is more > 1.
Quantity = Quantity - 1.
Reduce the amount of HoursWork (used for booking slot length) for the selected product.
Product Stock + 1.
Reduce the weight (used for delivery price).
Else: label displays "Quantity cannot be changed for Detailing & Valeting services.
I am using a SqlDataReader to get the CategoryID, and then storing it as Integer in variable CategoryID.
I tested by displaying the variable contents in a label, and it collects the correct CategoryID - however the "If CategoryID = "3" or "4" Then... is not working, as all categoryIDs are running the IF section or the statement and not the ELSE section.
Protected Sub lDecrease_Click(ByVal sender As Object, ByVal e As EventArgs)
'get clicked button
Dim lnk As LinkButton = CType(sender, LinkButton)
'Get clicked button row
' Dim row As GridViewRow = CType(lnk.Parent.Parent, GridViewRow)
Dim row As GridViewRow = CType(lnk.NamingContainer, GridViewRow)
'Get row selected
Dim idx As Integer = row.RowIndex
'get CartID
Dim lblCartID As Label = CType(row.Cells(0).FindControl("lblCartID"), Label)
Dim SCCartID As String = lblCartID.Text.ToString
'get ProductID
Dim lblProductID As Label = CType(row.Cells(0).FindControl("lblProductID"), Label)
Dim SCProductID As String = lblProductID.Text.ToString
'get ProductName
Dim lblProduct As Label = CType(row.Cells(0).FindControl("lblProduct"), Label)
Dim SCProduct As String = lblProduct.Text.ToString
'get Size
Dim lblSize As Label = CType(row.Cells(0).FindControl("lblSize"), Label)
Dim SCSize As String = lblSize.Text.ToString
'get Price
Dim lblPrice As Label = CType(row.Cells(0).FindControl("lblPrice"), Label)
Dim SCPrice As String = lblPrice.Text.ToString
'get Quantity
Dim lblQuantity As Label = CType(row.Cells(0).FindControl("lblQuantity"), Label)
Dim SCQuantity As String = lblQuantity.Text.ToString
'get Subtotal
Dim lblSubtotal As Label = CType(row.Cells(0).FindControl("lblSubtotal"), Label)
Dim SCSubtotal As String = lblSubtotal.Text.ToString
'get HoursWork
Dim lblHoursWork As Label = CType(row.Cells(0).FindControl("lblHoursWork"), Label)
Dim SCHoursWork As String = lblHoursWork.Text.ToString
'get Weight
Dim lblWeight As Label = CType(row.Cells(0).FindControl("lblWeight"), Label)
Dim SCWeight As String = lblWeight.Text.ToString
Dim conn As SqlConnection = New SqlConnection(ConnectionString)
' start of category check
Dim cmd4 As SqlCommand = New SqlCommand
cmd4.CommandText = "SELECT products.CategoryID FROM products INNER JOIN Cart on products.ProductID = cart.ProductID WHERE cart.productID=#ProductID"
Dim ProductID2 As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
ProductID2.Value = SCProductID
cmd4.Parameters.Add(ProductID2)
cmd4.Connection = conn
conn.Open()
cmd4.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd4.ExecuteReader
Dim CategoryID As Integer
While reader.Read()
CategoryID = CType(reader.Item("CategoryID"), Integer)
End While
'Testing CategoryID value = success
lblNoStock.Visible = True
lblNoStock.Text = CategoryID
conn.Close()
'Nest IF statement based on Category ID 1,2, cannot be reduced in Quantity
If CategoryID = "3" Or "4" Then
' Run quantity check – And update if possible
Dim exists As Boolean = False
'cart quantity
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "Select Quantity from Cart where CartID = #CartID"
cmd.Connection = conn
' conn.Close()
conn.Open()
'rename cart id 5
Dim CartID5 As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID5.Value = SCCartID
cmd.Parameters.Add(CartID5)
'check if more than 1 in cart
exists = (CType(cmd.ExecuteScalar, Integer) > 1)
If exists Then
'show label to say no more in stock
lblNoStock.Visible = True
' lblNoStock.Text = "Available!"
conn.Close()
' update quantity & subtotal
Dim cmd1 As SqlCommand = New SqlCommand
cmd1.CommandText = "UPDATE Cart SET Quantity = Quantity - 1, Subtotal = #Subtotal - #Price WHERE CartID = #CartID"
'update hourswork
Dim cmd2 As SqlCommand = New SqlCommand
cmd2.CommandText = "UPDATE Cart SET HoursWork = (HoursWork - (Select Products.HoursWork FROM Products WHERE Products.ProductID = Cart.ProductID)) WHERE CartID = #CartID"
'UPDATE PRODUCTS STOCK + 1
'"UPDATE Products Set Stock = Stock + 1 WHERE ProductID = #ProductID"
Dim cmd3 As SqlCommand = New SqlCommand
'UPDATE weight
cmd3.CommandText = "UPDATE Cart SET Weight = (Weight - (Select Products.Weight FROM Products WHERE Products.ProductID = Cart.ProductID)) WHERE CartID = #CartID"
cmd1.Connection = conn
cmd2.Connection = conn
cmd3.Connection = conn
conn.Open()
Dim PProductID As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
PProductID.Value = SCProductID
cmd1.Parameters.Add(PProductID)
Dim Subtotal As SqlParameter = New SqlParameter("#Subtotal", SqlDbType.Decimal, 5)
Subtotal.Value = SCSubtotal
cmd1.Parameters.Add(Subtotal)
Dim Price As SqlParameter = New SqlParameter("#Price", SqlDbType.Decimal, 5)
Price.Value = SCPrice
cmd1.Parameters.Add(Price)
Dim CartID As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID.Value = SCCartID
cmd1.Parameters.Add(CartID)
Dim CartID2 As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID2.Value = SCCartID
cmd2.Parameters.Add(CartID2)
Dim CartID3 As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID3.Value = SCCartID
cmd3.Parameters.Add(CartID3)
Try
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
cmd3.ExecuteNonQuery()
cmd.ExecuteReader()
'show label to quantity updated
lblNoStock.Visible = True
' lblNoStock.Text = "Updated!"
Finally
conn.Close()
'Response.Redirect("Cart2.aspx")
End Try
Else
'show label to say no more in stock
lblNoStock.Visible = True
lblNoStock.Text = "Cannot reduce quantity: Remove from Cart!"
End If
' else
' lblNoStock.Visible = True
' lblNoStock.Text = "Cannot reduce quantity of Detailing/ Valeting services: Remove from Cart!"
Else
'Outer ELSE
'show label to say cannot change quantity
lblNoStock.Visible = True
lblNoStock.Text = "Quantity cannot be changed for Detailing and Valeting services!"
End If
End Sub
I am also having the same issue with the "+" link button to increase quantity of selected product by 1 in the cart. Reduced code:
Protected Sub lIncrease_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim conn As SqlConnection = New SqlConnection(ConnectionString)
Dim exists As Boolean = False
'Check available in Products table STOCK
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "Select Stock from Products where ProductID = #ProductID"
cmd.Connection = conn
conn.Open()
Dim ProductID As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
ProductID.Value = SCProductID
cmd.Parameters.Add(ProductID)
'check if more than 0 in stock
exists = (CType(cmd.ExecuteScalar, Integer) > 0)
If exists Then
conn.Close()
Dim cmd4 As SqlCommand = New SqlCommand
cmd4.CommandText = "SELECT products.CategoryID FROM products INNER JOIN Cart on products.ProductID = cart.ProductID WHERE cart.productID=#ProductID"
Dim ProductID2 As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
ProductID2.Value = SCProductID
cmd4.Parameters.Add(ProductID2)
cmd4.Connection = conn
conn.Open()
cmd4.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd4.ExecuteReader
Dim CategoryID As Integer
While reader.Read()
CategoryID = CType(reader.Item("CategoryID"), Integer)
End While
'Testing CategoryID value = success
' lblNoStock.Visible = True
'lblNoStock.Text = CategoryID
conn.Close()
'NESTED IF STATEMENT
If CategoryID = "3" Or "4" Then
' UPDATE cart QUANTITY & SUBTOTAL based on CartID
cmd1.CommandText = "UPDATE Cart SET Quantity = Quantity + 1, Subtotal = #Subtotal + #Price WHERE CartID = #CartID"
Dim cmd2 As SqlCommand = New SqlCommand
'UPDATE cart HOURSWORK
cmd2.CommandText = "/"
Dim cmd3 As SqlCommand = New SqlCommand
'UPDATE cart HOURSWORK
cmd3.CommandText = "/"
cmd1.Connection = conn
cmd2.Connection = conn
cmd3.Connection = conn
conn.Open()
//Declared Parameters
Try
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
cmd3.ExecuteNonQuery()
cmd.ExecuteReader()
Finally
conn.Close()
Response.Redirect("Cart2.aspx")
End Try
Else
'Nested ELSE
'show label to say cannot change quantity
lblNoStock.Visible = True
lblNoStock.Text = "Quantity cannot be changed for Detailing and Valeting services!"
End If
Else
'show label to say no more in stock
lblNoStock.Visible = True
lblNoStock.Text = "Sorry out of stock!"
End If
End Sub
Two tables:
CART (CartID, UserID, DateCreated, ProductID, ProductName, Size, Price, Quantity, Subtotal, HoursWork)
PRODUCTS (ProductID, Name, SDescription, Price, Size, Images, Thumbnail, Weight, LDescription, Stock, CategoryID, HoursWork)
All working correctly now.
Changed from:
Dim reader As SqlDataReader = cmd4.ExecuteReader
Dim CategoryID As Integer
While reader.Read()
CategoryID = CType(reader.Item("CategoryID"), Integer)
End While
conn.Close()
If CategoryID = "3" Or "4" Then
To:
Dim reader As SqlDataReader = cmd4.ExecuteReader
While reader.Read()
lblTest3.Text = CType(reader.Item("CategoryID"), Integer)
End While
conn.Close()
If lblTest3.Text.Contains("3") Or lblTest3.Text.Contains("4") Then

VB.Net save excel file only in program debugging

I got a problem which is not an error in writing data to Excel file from VB.NET.
The code to save data in Excel file is as the following:
Sub WriteToExcel(ByVal dt As DataTable)
Dim excel_app As New Excel.ApplicationClass()
excel_app.Visible = True
Dim workbook As Excel.Workbook = excel_app.Workbooks.Open(Filename:=FileUpload1.PostedFile.FileName)
Dim sheet_name As String = "rptSyncADandITSM"
Dim sheet As Excel.Worksheet = FindSheet(workbook, sheet_name)
sheet.Cells(1, "AF") = "Status"
sheet.Cells(1, "AG") = "Message"
sheet.Range("AF" & 1).Style.VerticalAlignment = VerticalAlign.Top
sheet.Range("AF1").Style.HorizontalAlignment = HorizontalAlign.Center
sheet.Range("AF1").ColumnWidth = 10
sheet.Range("AG1").Style.VerticalAlignment = VerticalAlign.Top
sheet.Range("AG1").Style.HorizontalAlignment = HorizontalAlign.Center
sheet.Range("AG1").ColumnWidth = 15
Dim header_range As Excel.Range = sheet.Range("AF1", "AG1")
header_range.Font.Bold = True
header_range.Font.Color = System.Drawing.ColorTranslator.ToOle(Drawing.Color.Black)
Dim borders As Excel.Borders = header_range.Borders
borders.LineStyle = Excel.XlLineStyle.xlContinuous
borders.Weight = 1.9R
For Each dr As DataRow In dt.Rows
Dim value_range As Excel.Range = sheet.Range("AF" & dr(0).ToString, "AG" & dr(0).ToString)
If Not dr.IsNull(0) Then
sheet.Range("AF" & dr(0).ToString).Style.VerticalAlignment = VerticalAlign.Top
sheet.Range("AF" & dr(0).ToString).Style.HorizontalAlignment = HorizontalAlign.Center
sheet.Range("AF" & dr(0).ToString).ColumnWidth = 10
sheet.Range("AG" & dr(0).ToString).Style.VerticalAlignment = VerticalAlign.Top
sheet.Range("AG" & dr(0).ToString).Style.HorizontalAlignment = HorizontalAlign.Center
sheet.Range("AG" & dr(0).ToString).ColumnWidth = 15
Dim values(0, 1) As String
values(0, 0) = dr(1).ToString
values(0, 1) = dr(2).ToString
value_range.Value2 = values
End If
Dim value_borders As Excel.Borders = value_range.Borders
value_borders.LineStyle = Excel.XlLineStyle.xlContinuous
value_borders.Weight = 2.0R
Next
workbook.Save()
workbook.Close()
'workbook.Close(SaveChanges:=True)
excel_app.Quit()
End Sub
I reference these codes from this
But it only works when i debug the program. In runtime(not debugging) doesn't work to save.

Accessing a button control inside an asp.net Ajax accordion panel

I have a problem, my accordion panel with a dynamically generated accordion panes, with dynamically generated controls like my "btnVoucherProcess" button.
Now I am trying to access my button (btnVoucherProcess) using the "Find control" method as follows:
For i As Int32 = 0 To acAccomodation.Panes.Count - 1
Dim btnVoucherProcess As Button CType(acAccomodation.FindControl("btnVoucherProcess" & i), Button) 'New Button("btnVoucherProcess" & i)
btnVoucherProcess.Text = "Saved " & i
Next
This code throws an error if I run it,the error tells me that my button is null. How do I access my button (btnVoucherProcess) inside an accordion.
Thanks in advance.
===========
here is the entire code
The code is called in page_load
The code that is called in page_load Private Sub emptyDaysAddMode(ByVal duration As Integer)
For i As Integer = 0 To duration - 1
Dim pn As New AjaxControlToolkit.AccordionPane()
pn.ID = "Pane" & i
pn.HeaderContainer.Controls.Add(accomodation(i, "", "", "", txtMarkup.Text, 0, 0, 0, 0, 0, 0))
pn.ContentContainer.Controls.Add(accomodationDetails(i))
acAccomodation.Panes.Add(pn)
'drRow(0) = i + 1
'dtExcel.Rows.Add(drRow)
Next
End Sub
Function accomodation(ByVal i As Int32, ByVal ID As String, ByVal dteDate As String, ByVal strDescription As String, ByVal Markup As Double, ByVal SGL As Int32, ByVal Twin As Int32, ByVal Triple As Int32, ByVal Child As Int32, ByVal Teen As Int32, ByVal ChildOR As Int32) As Table
accomodation = New Table()
Dim myTableRow As New TableRow
myTableRow.Width = Unit.Percentage(100)
Dim dayCell As New TableCell
Dim txtDay As TextBox = New TextBox
txtDay.ID = "txtDate" & i
txtDay.Text = dteDate
If txtDay.Text = "" And txtArrival.Text <> "" Then txtDay.Text = DateAdd("d", i, CType(txtArrival.Text, Date))
txtDay.Width = Unit.Pixel(70)
dayCell.Controls.Add(txtDay)
Dim lblAccID As Label = New Label
lblAccID.ID = "lblAccID" & i
lblAccID.Text = ID
lblAccID.Visible = False
dayCell.Controls.Add(lblAccID)
myTableRow.Cells.Add(dayCell)
Dim hotelRateCell As New TableCell
Dim txtHotelRate As TextBox = New TextBox
txtHotelRate.ID = "txtHotelRate" & i
txtHotelRate.Text = strDescription
txtHotelRate.Width = Unit.Pixel(295)
txtHotelRate.Attributes.Add("onkeyup", "javascript:Complete(this, event," & i & ")")
hotelRateCell.Controls.Add(txtHotelRate)
myTableRow.Cells.Add(hotelRateCell)
Dim markupCell As New TableCell
Dim txtmarkup As TextBox = New TextBox
txtmarkup.ID = "txtMarkup" & i
txtmarkup.Width = Unit.Pixel(35)
txtmarkup.Text = Markup
If txtmarkup.Text = 0 Then txtmarkup.Text = txtQuotationMarkup.Text
txtmarkup.Attributes.Add("onchange", "javascript:accomodationCalc(" & i & ")")
markupCell.Controls.Add(txtmarkup)
myTableRow.Cells.Add(markupCell)
Dim nightCell As New TableCell
Dim txtnight As TextBox = New TextBox
txtnight.ID = "txtnight" & i
txtnight.Text = 1
txtnight.Width = Unit.Pixel(25)
txtnight.Attributes.Add("onchange", "javascript:accomodationCalc(" & i & ")")
nightCell.Controls.Add(txtnight)
myTableRow.Cells.Add(nightCell)
Dim sglCell As New TableCell
Dim txtSGL As TextBox = New TextBox
txtSGL.ID = "txtSGL" & i
txtSGL.Width = Unit.Pixel(25)
txtSGL.Text = SGL
txtSGL.Attributes.Add("onchange", "javascript:accomodationCalc(" & i & ")")
sglCell.Controls.Add(txtSGL)
myTableRow.Cells.Add(sglCell)
Dim DBLCell As New TableCell
Dim txtDBL As TextBox = New TextBox
txtDBL.ID = "txtDBL" & i
txtDBL.Width = Unit.Pixel(25)
txtDBL.Text = Twin
txtDBL.Attributes.Add("onchange", "javascript:accomodationCalc(" & i & ")")
DBLCell.Controls.Add(txtDBL)
myTableRow.Cells.Add(DBLCell)
Dim trpCell As New TableCell
Dim txtTRP As TextBox = New TextBox
txtTRP.ID = "txtTRP" & i
txtTRP.Width = Unit.Pixel(25)
txtTRP.Text = Triple
txtTRP.Attributes.Add("onchange", "javascript:accomodationCalc(" & i & ")")
trpCell.Controls.Add(txtTRP)
myTableRow.Cells.Add(trpCell)
Dim chdCell As New TableCell
Dim txtCHD As TextBox = New TextBox
txtCHD.ID = "txtCHD" & i
txtCHD.Width = Unit.Pixel(25)
txtCHD.Text = Child
txtCHD.Attributes.Add("onchange", "javascript:accomodationCalc(" & i & ")")
chdCell.Controls.Add(txtCHD)
myTableRow.Cells.Add(chdCell)
Dim tnCell As New TableCell
Dim txtTN As TextBox = New TextBox
txtTN.ID = "txtTN" & i
txtTN.Width = Unit.Pixel(25)
txtTN.Text = Teen
txtTN.Attributes.Add("onchange", "javascript:accomodationCalc(" & i & ")")
tnCell.Controls.Add(txtTN)
myTableRow.Cells.Add(tnCell)
Dim childOWRCell As New TableCell
Dim txtChildOWR As TextBox = New TextBox
txtChildOWR.ID = "txtchildOWR" & i
txtChildOWR.Width = Unit.Pixel(25)
txtChildOWR.Text = ChildOR
txtChildOWR.Attributes.Add("onchange", "javascript:accomodationCalc(" & i & ")")
childOWRCell.Controls.Add(txtChildOWR)
myTableRow.Cells.Add(childOWRCell)
Dim CostCell As New TableCell
Dim txtCost As TextBox = New TextBox
txtCost.ID = "txtCost" & i
txtCost.Width = Unit.Pixel(55)
txtCost.Enabled = False
CostCell.Controls.Add(txtCost)
myTableRow.Cells.Add(CostCell)
Dim SaleCell As New TableCell
Dim txtSale As TextBox = New TextBox
txtSale.ID = "txtSale" & i
txtSale.Width = Unit.Pixel(55)
txtSale.Enabled = False
SaleCell.Controls.Add(txtSale)
myTableRow.Cells.Add(SaleCell)
Dim ProfitCell As New TableCell
Dim txtProfit As TextBox = New TextBox
txtProfit.ID = "txtProfit" & i
txtProfit.Width = Unit.Pixel(60)
txtProfit.Enabled = False
ProfitCell.Controls.Add(txtProfit)
myTableRow.Cells.Add(ProfitCell)
Dim deleteCell As New TableCell
Dim chkAccDelete As CheckBox = New CheckBox
chkAccDelete.ID = "chkAccDelete" & i
chkAccDelete.Width = Unit.Pixel(60)
deleteCell.Controls.Add(chkAccDelete)
myTableRow.Cells.Add(deleteCell)
accomodation.Rows.Add(myTableRow)
Return accomodation
End Function
Function accomodationDetails(ByVal i As Int32) As Table
accomodationDetails = New Table()
accomodationDetails.BorderColor = Color.Black
accomodationDetails.BorderStyle = BorderStyle.Solid
'------1st Row
Dim tableRow1 As New TableRow
Dim mycell1 As New TableCell
mycell1.Text = "Description"
mycell1.BackColor = Color.Gray
'Dim tb As TextBox = New TextBox
tableRow1.Cells.Add(mycell1)
Dim mycell2 As New TableCell
mycell2.Text = "Single"
mycell2.BackColor = Color.Gray
tableRow1.Cells.Add(mycell2)
Dim mycell3 As New TableCell
mycell3.Text = "Double"
mycell3.BackColor = Color.Gray
tableRow1.Cells.Add(mycell3)
Dim mycell4 As New TableCell
mycell4.Text = "Triple"
mycell4.BackColor = Color.Gray
tableRow1.Cells.Add(mycell4)
Dim mycell5 As New TableCell
mycell5.Text = "Child"
mycell5.BackColor = Color.Gray
tableRow1.Cells.Add(mycell5)
Dim mycell6 As New TableCell
mycell6.Text = "Teen"
mycell6.BackColor = Color.Gray
tableRow1.Cells.Add(mycell6)
Dim mycell7 As New TableCell
mycell7.Text = "Child(OR)"
mycell7.BackColor = Color.Gray
tableRow1.Cells.Add(mycell7)
accomodationDetails.Rows.Add(tableRow1)
'------2nd Row
Dim tableRow2 As New TableRow
Dim mycell1R2 As New TableCell
mycell1R2.Text = "Cost"
tableRow2.Cells.Add(mycell1R2)
Dim mycell2R2 As New TableCell
Dim txtSingle As TextBox = New TextBox
txtSingle.ID = "txtSingle" & i
txtSingle.Width = Unit.Pixel(60)
mycell2R2.Controls.Add(txtSingle)
tableRow2.Cells.Add(mycell2R2)
Dim mycell3R2 As New TableCell
Dim txtDouble As TextBox = New TextBox
txtDouble.ID = "txtDouble" & i
txtDouble.Width = Unit.Pixel(60)
mycell3R2.Controls.Add(txtDouble)
tableRow2.Cells.Add(mycell3R2)
accomodationDetails.Rows.Add(tableRow2)
Dim mycell4R2 As New TableCell
Dim txtTriple As TextBox = New TextBox
txtTriple.ID = "txtTriple" & i
txtTriple.Width = Unit.Pixel(60)
mycell4R2.Controls.Add(txtTriple)
tableRow2.Cells.Add(mycell4R2)
accomodationDetails.Rows.Add(tableRow2)
Dim mycell5R2 As New TableCell
Dim txtChild As TextBox = New TextBox
txtChild.ID = "txtChild" & i
txtChild.Width = Unit.Pixel(60)
mycell5R2.Controls.Add(txtChild)
tableRow2.Cells.Add(mycell5R2)
accomodationDetails.Rows.Add(tableRow2)
Dim mycell6R2 As New TableCell
Dim txtTeen As TextBox = New TextBox
txtTeen.ID = "txtTeen" & i
txtTeen.Width = Unit.Pixel(60)
mycell6R2.Controls.Add(txtTeen)
tableRow2.Cells.Add(mycell6R2)
Dim mycell7R2 As New TableCell
Dim txtChildOR As TextBox = New TextBox
txtChildOR.ID = "txtChildOR" & i
txtChildOR.Width = Unit.Pixel(60)
mycell7R2.Controls.Add(txtChildOR)
tableRow2.Cells.Add(mycell7R2)
accomodationDetails.Rows.Add(tableRow2)
'------3rd Row
Dim tableRow3 As New TableRow
Dim mycell1R3 As New TableCell
mycell1R3.Text = "Sales"
tableRow3.Cells.Add(mycell1R3)
Dim mycell2R3 As New TableCell
Dim txtSingleSale As TextBox = New TextBox
txtSingleSale.ID = "txtSingleSale" & i
txtSingleSale.Width = Unit.Pixel(60)
mycell2R3.Controls.Add(txtSingleSale)
tableRow3.Cells.Add(mycell2R3)
Dim mycell3R3 As New TableCell
Dim txtDoubleSale As TextBox = New TextBox
txtDoubleSale.ID = "txtDoubleSale" & i
txtDoubleSale.Width = Unit.Pixel(60)
mycell3R3.Controls.Add(txtDoubleSale)
tableRow3.Cells.Add(mycell3R3)
Dim mycell4R3 As New TableCell
Dim txtTripleSale As TextBox = New TextBox
txtTripleSale.ID = "txtTripleSale" & i
txtTripleSale.Width = Unit.Pixel(60)
mycell4R3.Controls.Add(txtTripleSale)
tableRow3.Cells.Add(mycell4R3)
Dim mycell5R3 As New TableCell
Dim txtChildSale As TextBox = New TextBox
txtChildSale.ID = "txtChildSale" & i
txtChildSale.Width = Unit.Pixel(60)
mycell5R3.Controls.Add(txtChildSale)
tableRow3.Cells.Add(mycell5R3)
Dim mycell6R3 As New TableCell
Dim txtTeenSale As TextBox = New TextBox
txtTeenSale.ID = "txtTeenSale" & i
txtTeenSale.Width = Unit.Pixel(60)
mycell6R3.Controls.Add(txtTeenSale)
tableRow3.Cells.Add(mycell6R3)
Dim mycell7R3 As New TableCell
Dim txtChildORSale As TextBox = New TextBox
txtChildORSale.ID = "txtChildORSale" & i
txtChildORSale.Width = Unit.Pixel(60)
mycell7R3.Controls.Add(txtChildORSale)
tableRow3.Cells.Add(mycell7R3)
accomodationDetails.Rows.Add(tableRow3)
'-----4th Row
Dim tableRow4 As New TableRow
Dim mycell1R4 As New TableCell
mycell1R4.Text = "Voucher remarks"
tableRow4.Cells.Add(mycell1R4)
Dim mycell2R4 As New TableCell
mycell2R4.ColumnSpan = "6"
Dim txtVoucherRemarks As TextBox = New TextBox
txtVoucherRemarks.ID = "txtVoucherRemarks" & i
txtVoucherRemarks.Width = Unit.Pixel(420)
txtVoucherRemarks.TextMode = TextBoxMode.MultiLine
mycell2R4.Controls.Add(txtVoucherRemarks)
tableRow4.Cells.Add(mycell2R4)
accomodationDetails.Rows.Add(tableRow4)
'------5th Row
Dim tableRow5 As New TableRow
Dim mycell1R5 As New TableCell
Dim chkPark As New CheckBox
chkPark.ID = "chkPark" & i
chkPark.Text = "Include park fees."
mycell1R5.Text = ""
mycell1R5.Controls.Add(chkPark)
tableRow5.Cells.Add(mycell1R5)
Dim mycell2R5 As New TableCell
mycell2R5.ColumnSpan = "2"
Dim btnVoucherProcess As Button = New Button
btnVoucherProcess.ID = "btnVoucherProcess" & i
btnVoucherProcess.Width = Unit.Pixel(120)
btnVoucherProcess.Text = "Book"
mycell2R5.Controls.Add(btnVoucherProcess)
tableRow5.Cells.Add(mycell2R5)
Dim mycell3R5 As New TableCell
mycell3R5.ColumnSpan = "2"
Dim btnVoucherCancel As Button = New Button
btnVoucherCancel.ID = "btnVoucherCancel" & i
btnVoucherCancel.Width = Unit.Pixel(120)
btnVoucherCancel.Text = "Cancel voucher"
mycell3R5.Controls.Add(btnVoucherCancel)
tableRow5.Cells.Add(mycell3R5)
Dim mycell4R5 As New TableCell
mycell4R5.ColumnSpan = "2"
Dim btnVoucherPrint As Button = New Button
btnVoucherPrint.ID = "btnVoucherPrint" & i
btnVoucherPrint.Width = Unit.Pixel(120)
btnVoucherPrint.Text = "Print voucher"
mycell4R5.Controls.Add(btnVoucherPrint)
tableRow5.Cells.Add(mycell4R5)
accomodationDetails.Rows.Add(tableRow5)
Return accomodationDetails
End Function
This following code is triggered by the button outside the accordion
Protected Sub btnSaveAccomodation_Click(sender As Object, e As System.EventArgs) Handles btnSaveAccomodation.Click
For i As Int32 = 0 To acAccomodation.Panes.Count - 1
'For Each i As In Me.cdTransport.Items
' Dim btnVoucherProcess As Button = CType(acAccomodation.FindControl("btnVoucherProcess" & i), Button) 'New Button("btnVoucherProcess" & i)
Dim controlName As String = "btnVoucherProcess" & i
Dim btnVoucherProcess As Button = CType(acAccomodation.Panes(i).ContentContainer.FindControl("btnVoucherProcess" & i), Button)
btnVoucherProcess.Text = "Saved " & i
'Dim cboDay As DropDownList = CType(i.FindControl("cboDay"), DropDownList)
Next
End Sub
If you are dynamically rendering the controls, and later, you are trying to access the dynamic controls through an event handler, e.g. a button's Click method implementation, you'll get nothing.
For finding always the dynamically generated controls, you should always create them in your Page_Load event. Always. So that the event handler that tries to access your dynamic controls will find them and, I can't explain why but, this dynamic controls will contain the values that were entered by the user on client side.

asp:Table change row color programmatically

I am learning .net and building a table from code behind and attempting to change alternate row colors.
I have it working but at he moment only using Drawing.Color when I would like to use a hexidecimal value, is there a way of doing this?
Here is the code thats doing it at the moment:
If j Mod 2 = 1 Then
r.BackColor = Drawing.Color.Aquamarine
'Table1.Rows(j).Cells(i).CssClass = "odd"
Else
r.BackColor = Drawing.Color.Blue
'Table1.Rows(j).Cells(i).CssClass = "even"
End If
Here is full code:
' declare variables
Dim numrows As Integer
Dim numcells As Integer
Dim i As Integer
Dim j As Integer
Dim r As TableRow
Dim c As TableCell
Dim hc As TableHeaderCell
'Dim datepickJS As String
' generate rows and cells
numrows = CaseTotal
' column count
numcells = 7
r = New TableRow()
c = New TableCell()
'' validation creation
'Dim newValidatorSummary As New ValidationSummary()
'newValidatorSummary.CssClass = "form-error"
'c.Controls.Add(newValidatorSummary)
'c.ColumnSpan = 5
'r.Cells.Add(c)
'Table1.Rows.Add(r)
r = New TableRow()
' header row and titles
hc = New TableHeaderCell()
hc.Controls.Add(New LiteralControl("Case Ref"))
r.Cells.Add(hc)
hc = New TableHeaderCell()
hc.Controls.Add(New LiteralControl("Name"))
r.Cells.Add(hc)
hc = New TableHeaderCell()
hc.Controls.Add(New LiteralControl("Company"))
r.Cells.Add(hc)
hc = New TableHeaderCell()
hc.Controls.Add(New LiteralControl("Last Updated"))
r.Cells.Add(hc)
hc = New TableHeaderCell()
hc.Controls.Add(New LiteralControl("Order Date"))
r.Cells.Add(hc)
hc = New TableHeaderCell()
hc.Controls.Add(New LiteralControl(" "))
r.Cells.Add(hc)
hc = New TableHeaderCell()
hc.Controls.Add(New LiteralControl(" "))
r.Cells.Add(hc)
Table1.Rows.Add(r)
r.BackColor = Drawing.Color.AntiqueWhite
For j = 0 To numrows - 1
r = New TableRow()
'Table1.Rows(j).Cells(i).CssClass = "tablehead"
'row data
Dim ClientName, Company As String
Dim OrderDate As Date
ClientName = dsCases.Tables("CaseList").Rows(j).Item("firstname") & " " & dsCases.Tables("CaseList").Rows(j).Item("lastname")
Company = dsCases.Tables("CaseList").Rows(j).Item("company")
OrderDate = dsCases.Tables("CaseList").Rows(j).Item("CaseSent")
'create details button
Dim btnDetails As New Button()
btnDetails.Text = "Details"
btnDetails.ID = "btnDetails"
btnDetails.Width = "60"
btnDetails.Font.Size = "8"
'AddHandler btnSubmit.Click, AddressOf sendDetails_Click
'create schedule button
Dim btnSchedule As New Button()
btnSchedule.Text = "Schedule"
btnSchedule.ID = "btnSchedule"
btnSchedule.Width = "60"
btnSchedule.Font.Size = "8"
'AddHandler btnSubmit.Click, AddressOf sendDetails_Click
For i = 0 To numcells - 1
Dim iMod As Integer
iMod = j Mod 2
c = New TableCell()
If i = 0 Then
c.Controls.Add(New LiteralControl(iMod & " "))
c.Controls.Add(New LiteralControl(UserId))
ElseIf i = 1 Then
c.Controls.Add(New LiteralControl(ClientName))
ElseIf i = 2 Then
c.Controls.Add(New LiteralControl(Company))
ElseIf i = 3 Then
ElseIf i = 4 Then
c.Controls.Add(New LiteralControl(FormatDateTime(OrderDate, DateFormat.ShortDate)))
ElseIf i = 5 Then
c.Controls.Add(btnDetails)
ElseIf i = 6 Then
c.Controls.Add(btnSchedule)
End If
r.Cells.Add(c)
Next i
Table1.Rows.Add(r)
If j Mod 2 = 1 Then
r.BackColor = Drawing.Color.Aquamarine
'Table1.Rows(j).Cells(i).CssClass = "odd"
Else
r.BackColor = Drawing.Color.Blue
'Table1.Rows(j).Cells(i).CssClass = "even"
End If
Next j
r = New TableRow()
' footer row
c = New TableCell()
c.ColumnSpan = 7
c.HorizontalAlign = HorizontalAlign.Right
r.Cells.Add(c)
Table1.Rows.Add(r)
Thanks for any help.
J.
You can use the ColorTranslator class like this:
r.BackColor = ColorTranslator.FromHtml("#0000FF")
Documentation here: http://msdn.microsoft.com/en-us/library/system.drawing.colortranslator.fromhtml.aspx

Resources