Allow only some check boxes to be checked. Loaded on page_load - asp.net

I am dynamically adding asp check boxes to my page based off of number of rows in my db table, by ID. Also the checkbox is being assigned an ID from the db table. I also two columns in my db table "numberOffered" and "numberAllowed". My idea is on page load only allow the user to check say 3 of the 10 check boxes shown. I have removed a lot of the code I thought would be unnecessary. Thank you very much in advance.
For Each Arow As Object In ATable.Rows
For Each Brow As Object In BTable.Rows
If Brow(1) = a_ID Then
If Brow(2) = b_ID Then
Dim cbShown As Integer = Arow(5)
Dim cbAllowed As Integer = Arow(6)
Dim checkBox As New CheckBox()
End If
End If
Next
Next
checkBox.ID = Crow(0)
divcontrol.Controls.Add(checkBox)
EDIT:
Full Page_load sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (Session("studentLoggedIn") Or Session("adminLoggedIn")) Then
Routines.LogOut()
End If
If Session("adminLoggedIn") = True Then
castVote.Enabled = False
castVote.CssClass = "btnDisabled"
Dim p As New HtmlGenericControl()
p.TagName = "p"
p.InnerText = "Vote button disabled. Only students may vote."
adminMsg.Controls.Add(p)
End If
Dim ballot_ID As Integer = CType(Session.Item("ballot_ID"), Integer)
Dim ballotName As String = CType(Session.Item("ballotName"), String)
Dim ballotsAdapter As New eVoteTableAdapters.ballotsTableAdapter()
Dim ballotsTable As New eVote.ballotsDataTable
ballotsTable = ballotsAdapter.GetDataBy3getBallotsByID(ballot_ID)
Dim sectionsAdapter As New eVoteTableAdapters.sectionsTableAdapter()
Dim sectionsTable As New eVote.sectionsDataTable
sectionsTable = sectionsAdapter.GetDataBygetsectionsByBallotID(ballot_ID)
Dim candidatesAdapter As New eVoteTableAdapters.candidatesTableAdapter()
Dim candidatesTable As New eVote.candidatesDataTable
candidatesTable = candidatesAdapter.GetDataBygetCandidatesByballotID(ballot_ID)
openBallotName.InnerText = ballotName
Dim section_ID
For Each row As Object In sectionsTable.Rows
If row(1) = ballot_ID Then
section_ID = row(0)
Dim sectionName As New HtmlGenericControl()
Dim sectionDescription As New HtmlGenericControl()
Dim divcontrol As New HtmlGenericControl()
Dim br As New HtmlGenericControl()
divcontrol.Attributes("ID") = section_ID
divcontrol.Attributes("runat") = "server"
divcontrol.Attributes("style") = "border: solid;"
divcontrol.TagName = "div"
br.TagName = "br"
sectionName.TagName = "h4"
sectionDescription.TagName = "p"
mainBallotDiv.Controls.Add(divcontrol)
mainBallotDiv.Controls.Add(br)
sectionName.InnerText = row(2)
sectionDescription.InnerText = row(3)
divcontrol.Controls.Add(sectionName)
divcontrol.Controls.Add(sectionDescription)
For Each Crow As Object In candidatesTable.Rows
If Crow(1) = ballot_ID Then
If Crow(2) = section_ID Then
Dim checkBox As New CheckBox()
Dim canImg As New Image()
Dim canName As New HtmlGenericControl()
Dim canBio As New HtmlGenericControl()
Dim rmImg As New Image()
Dim rmName As New HtmlGenericControl()
Dim rmBio As New HtmlGenericControl()
Dim canBytes As Byte() = Crow(6)
Dim canBase64String As String = Convert.ToBase64String(canBytes, 0, canBytes.Length)
Dim rmBytes As Byte() = Crow(11)
Dim rmBase64String As String = Convert.ToBase64String(rmBytes, 0, rmBytes.Length)
checkBox.ID = Crow(0)
canName.TagName = "h3"
canBio.TagName = "p"
rmName.TagName = "h3"
rmBio.TagName = "p"
canName.InnerText = Crow(4) & " " & Crow(5)
canBio.InnerText = Crow(7)
canImg.ImageUrl = Convert.ToString("data:image/png;base64,") & canBase64String
canImg.Height = 120
rmName.InnerText = Crow(9) & " " & Crow(10)
rmBio.InnerText = Crow(12)
rmImg.ImageUrl = Convert.ToString("data:image/png;base64,") & rmBase64String
rmImg.Height = 120
divcontrol.Controls.Add(checkBox)
divcontrol.Controls.Add(canImg)
divcontrol.Controls.Add(canName)
divcontrol.Controls.Add(canBio)
If row(4) = True Then
divcontrol.Controls.Add(rmImg)
divcontrol.Controls.Add(rmName)
divcontrol.Controls.Add(rmBio)
End If
End If
End If
Next
End If
Next
End Sub

You will want a variable (integer) for the amount of checkboxes allowed, then another variable for the amount of checkboxes currently checked, finally a List containing the name of each checkbox, (have all these variables as class fields)
then in your event handler something like
Sub Check_Clicked(sender As Object, e As EventArgs)
checked += 1
If checked >= NumberAllowedChecked Then
For Each a As CheckBox In MyCheckBoxList
If Not CheckBox.Checked Then CheckBox.Enabled = False
Next
End If
End Sub
I am not overly familiar with VB but I think this should set you on the right track on how to implement it for yourself
Edit: you will want to add in logic for if a user unchecks a check box that it will subtract one from 'checked;

Related

Loop through checkbox ID's to see if any are checked

I have a ballot for a election system and I need to loop through all the checkboxes on the ballot to see if they are checked or unchecked. You can only select (for example) 1 of the 5 boxes available. I am stuck and can not for the life of me figure this out. The following code is my function that runs when the user clicks the submit button.
This code works and submit my ballot but does not check the number of checkboxes checked.
For Each row As Object In candidatesTable.Rows
If row(1) = ballot_ID Then
Dim checkBox_ID = row(0)
Dim CB As New CheckBox()
CB = mainBallotDiv.FindControl(checkBox_ID)
If CB.Checked Then
Dim addVote As Integer = row("votes")
addVote += 1
candidatesAdapter.addVoteToCandidate(addVote, row(0))
Dim section_ID As Integer = row(2)
Dim voter As String = userGnumber
Dim vote As Integer = checkBox_ID
Dim hasVoted As Boolean = True
votesAdapter.InsertVotes(ballot_ID, section_ID, voter, vote, hasVoted)
End If
End If
Next
Response.Redirect("~/voting/voted.aspx")
I have added a couple things to try and get this to run correctly but no luck, my code currently is the following.
Dim checkedCount As Integer
For Each row As Object In candidatesTable.Rows
If row(1) = ballot_ID Then
Dim checkBox_ID = row(0)
Dim CB As New CheckBox()
CB = mainBallotDiv.FindControl(checkBox_ID)
Dim section_idFromCB As Integer = candidatesAdapter.getsectionIDfromcandidateID(CB.ID)
Dim voteLimit As Integer = sectionsAdapter.votesbysectionid(section_idFromCB)
If CB.Checked Then
checkedCount += 1
Debug.Write(checkedCount)
If checkedCount > voteLimit Then
' error
Response.Write("<script language=""javascript"">alert('You can not select that many check boxes.');</script>")
Response.Redirect(Request.RawUrl)
Else
' pass
For Each Nrow As Object In candidatesTable.Rows
If Nrow(1) = ballot_ID Then
Dim NcheckBox_ID = row(0)
Dim NCB As New CheckBox()
NCB = mainBallotDiv.FindControl(NcheckBox_ID)
If NCB.Checked Then
Dim addVote As Integer = row("votes")
addVote += 1
candidatesAdapter.addVoteToCandidate(addVote, row(0))
Dim section_ID As Integer = row(2)
Dim voter As String = userGnumber
Dim vote As Integer = checkBox_ID
Dim hasVoted As Boolean = True
votesAdapter.InsertVotes(ballot_ID, section_ID, voter, vote, hasVoted)
End If
End If
Next
Response.Redirect("~/voting/voted.aspx")
End If
End If
End If
Next
Any help would be appreciated, and thanks in advance.
Here is my recommendation...
You can put them in a List(Of CheckBox) then you can access them anytime as needed as well as get any property you would need.
Dim lstChecked As New List(Of CheckBox)
lstChecked = divcontrol.Controls.OfType(Of CheckBox).Where(Function(ch) ch.Checked = True).ToList
lstChecked would be any CheckBox that would be checked...
For Each checkBox In Me.Controls.OfType(Of CheckBox)
' do something
Next

Error: An exception of type 'System.Data.SqlClient.SqlException' occured in System.Data.dll but was not handled in user code

I'm new to ASP.NET and building a little dynamic website for a salesdepartment to registere their sales for salescompetions.
I have a page, after one is logged in, that consists of a couple of comboboxes/dropdowns and at the buttom a 'SUBMIT' button which I want to trigger a new record in the database with all the selected data. everything seems to go fine for a second but eventually the following error message appears:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Invalid column name 'KunderID'.
Invalid column name 'KundeTypeID'.
Invalid column name 'MachineModellID'.
Invalid column name 'AntallID'.
Invalid column name 'BrukerID'.
It points to the following part (The line starting with MBExec =) in the DBConnection.vb file:
Public Shared Function MBExec(ByVal SQL As String) As String
Dim cmd As New SqlCommand(SQL, MBConn)
MBExec = Convert.ToString(cmd.ExecuteScalar())
cmd.Connection.Close()
End Function
On the sourcecode og the relevant page the relevant part of it is the following (bottom line starting with MBExec) whereby I cannot see that the columnsnames are wrong:
Protected Sub RegisterSale(sender As Object, e As EventArgs)
Dim KundeNavn As DropDownList = DropDownListKundeNavn
Dim TypeKunde As DropDownList = DropDownListTypeKunde
Dim MachineModell As DropDownList = DropDownListMachineModell
Dim Antall As DropDownList = DropDownListAntall
Dim Bruker As DropDownList = DropDownListBruker
If KundeNavn.SelectedItem.Text = "Velg" Then
Dim msg = "Select or add a new customer"
Dim msgTittle = "Missing Customer Name"
MsgBox(msg, MsgBoxStyle.Critical, msgTittle)
Exit Sub
Else
Dim msg1 = "Are you sure to continue?"
Dim title = "Confirm Sale Registration"
Dim style = MsgBoxStyle.YesNo
Dim responce = MsgBox(msg1, style, title)
If responce = MsgBoxResult.Yes Then
Dim msg = "Thank you for your efforts, you are closer to becoming a sales champion!"
Dim msgTittle = "Your Sale has been recorded"
MsgBox(msg, MsgBoxStyle.Information, msgTittle)
'Varibles to hold the DataValueField from the dropboxes
Dim KundeID As Integer
Dim TypeKundeID As Integer
Dim MachineModellID As Integer
Dim AntallID As Integer
Dim BrukerID As Integer
'Converts the DataValueField to an Integer
KundeID = Convert.ToInt32(KundeNavn.SelectedValue.ToString())
TypeKundeID = Convert.ToInt32(TypeKunde.SelectedValue.ToString())
MachineModellID = Convert.ToInt32(MachineModell.SelectedValue.ToString())
AntallID = Convert.ToInt32(Antall.SelectedValue.ToString())
BrukerID = Convert.ToInt32(Bruker.SelectedValue.ToString())
MBExec("INSERT INTO KyoceraSalgReg(KunderID, KundeTypeID, MachineModellID, AntallID, BrukerID) Values (KunderID, KundeTypeID, MachineModellID, AntallID, BrukerID)")
Exit Sub
Else
Exit Sub
End If
End If
End Sub
I would very much appreciate if anybody could help me in the right direction here. If I understand it correctly, somehow the column names are not recognized and I just don't see why.
Cheers:)
Update 1:
MBExec looks like this:
Public Shared Function MBExec(ByVal SQL As String) As String
Dim cmd As New SqlCommand(SQL, MBConn)
MBExec = Convert.ToString(cmd.ExecuteScalar())
cmd.Connection.Close()
End Function
And KunderID datatype is string, selection made from a DropDownList
Try this approach:
MBExec("INSERT INTO KyoceraSalgReg(KunderID, KundeTypeID, MachineModellID, AntallID, BrukerID) Values (#KunderID, #KundeTypeID, #MachineModellID, #AntallID, #BrukerID)")
Use parameterized query to add the values:
cmd.Parameter.AddWithValue("#KunderID", KunderID)
AddWithValue
You may need to make separate instances of the SqlParameter - Example
Protected Sub RegisterSale(sender As Object, e As EventArgs)
Dim KundeNavn As DropDownList = DropDownListKundeNavn
Dim TypeKunde As DropDownList = DropDownListTypeKunde
Dim MachineModell As DropDownList = DropDownListMachineModell
Dim Antall As DropDownList = DropDownListAntall
Dim Bruker As DropDownList = DropDownListBruker
'Varibles to hold the DataValueField from the dropboxes
Dim KunderID As Integer = Convert.ToInt32(KundeNavn.SelectedValue.ToString())
Dim TypeKundeID As Integer = Convert.ToInt32(TypeKunde.SelectedValue.ToString())
Dim MachineModellID As Integer = Convert.ToInt32(MachineModell.SelectedValue.ToString())
Dim AntallID As Integer = Convert.ToInt32(Antall.SelectedValue.ToString())
Dim BrukerID As Integer = Convert.ToInt32(Bruker.SelectedValue.ToString())
'Sets the Selected values from dropdownlist
Dim ParamKunderID = New SqlParameter()
ParamKunderID.ParameterName = "#KunderID"
ParamKunderID.Value = KunderID
Dim ParamTypeID = New SqlParameter
ParamTypeID.ParameterName = "#KundeTypeID"
ParamTypeID.Value = TypeKundeID
Dim ParamMachineModellID = New SqlParameter()
ParamMachineModellID.ParameterName = "#MachineModellID"
ParamMachineModellID.Value = MachineModellID
Dim ParamAntallID = New SqlParameter
ParamAntallID.ParameterName = "#AntallID"
ParamAntallID.Value = AntallID
Dim ParamBrukerID = New SqlParameter
ParamBrukerID.ParameterName = "#BrukerID"
ParamBrukerID.Value = BrukerID
If KundeNavn.SelectedItem.Text = "Velg" Then
Dim msg = "Velg eller legge til en ny kunde"
Dim msgTittle = "Mangler Kundenavn"
MsgBox(msg, MsgBoxStyle.Critical, msgTittle)
Exit Sub
Else
Dim msg1 = "Er du sikker på at du vil fortsette?"
Dim title = "Bekrefte salg registrering"
Dim style = MsgBoxStyle.YesNo
Dim responce = MsgBox(msg1, style, title)
If responce = MsgBoxResult.Yes Then
MBExec("INSERT INTO KyoceraSalgReg(KunderID, KundeTypeID, MachineModellID, AntallID, BrukerID)" & " Values " & "(" & KunderID & "," & TypeKundeID & "," & MachineModellID & "," & AntallID & "," & BrukerID & ")")
Dim msg = "Takk for din innsats, du er nærmere å bli et Salg Mester!"
Dim msgtittle = "Din salget er registrert"
MsgBox(msg, MsgBoxStyle.Information, msgtittle)
End If
End If
End Sub

Accessing multiple dynamic controls values

I am adding multiple controls dynamically based on a dropdownlist that the user selects. i.e. if the user selects 3 then 3 sets of the controls are added. My problem is not in adding the controls, I can add them fine, I haven't added all my code but the main parts to understand what I am doing.
Once the controls have been created, the relevant info is captured. On the Update click I need to access the values of these dynamic controls by looping through in the correct order and retrieve the values and write to the database. I can't seem to access them correctly.
Hopefully I am making sense. Any help would be appreciated. Thanks
''Loop through first set of controls and get values and then the next set etc..
Dim Description as string = ''Get Textbox value
Dim Type as string = ''Get RadComboBox value
Dim XFieldName as string = ''Get RadComboBox value
Dim Colour as string = ''Get RadColorPicker value
Below is my Code:
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RecreateControlsTxt("txt", "TextBox")
RecreateControlsChart("comboChart", "RadComboBox")
RecreateControls("combo", "RadComboBox")
RecreateControlsCP("cp", "RadColorPicker")
End Sub
Protected Sub AddControls_Click(sender As Object, e As EventArgs) Handles AddControls.Click
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateTextbox("txt-" & Convert.ToString(i + 1))
Next
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateComboChart("comboChart-" & Convert.ToString(i + 1))
Next
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateComboField("combo-" & Convert.ToString(i + 1))
Next
For i As Integer = 0 To ddlFieldNames.SelectedIndex
CreateColourPicker("cp-" & Convert.ToString(i + 1))
Next
End Sub
Private Sub CreateTextbox(ByVal ID As String)
Dim txt As New TextBox()
txt.ID = ID
txt.Height = 20
Me.divDesc.Controls.Add(txt)
End Sub
Private Sub CreateComboField(ByVal ID As String)
Dim combo As New RadComboBox()
combo.ID = ID
combo.DataSource = Me.odsChartsSeriesField
combo.DataTextField = "FieldNames"
combo.DataValueField = "FieldNames"
combo.DataBind()
Me.divField.Controls.Add(combo)
End Sub
Private Sub CreateComboChart(ByVal ID As String)
Dim comboChart As New RadComboBox()
comboChart.ID = ID
Dim item1 As New RadComboBoxItem()
item1.Text = "Line"
item1.Value = "smoothedLine"
item1.ImageUrl = ("Images/linechart.png")
comboChart.Items.Add(item1)
Dim item2 As New RadComboBoxItem()
item2.Text = "Column"
item2.Value = "column"
item2.ImageUrl = ("Images/bar chart.png")
comboChart.Items.Add(item2)
Dim item3 As New RadComboBoxItem()
item3.Text = "Pie"
item3.Value = "pie"
item3.ImageUrl = ("Images/pie chart.jpg")
comboChart.Items.Add(item3)
Me.divChart.Controls.Add(comboChart)
End Sub
Private Sub CreateColourPicker(ByVal ID As String)
Dim cp As New RadColorPicker()
cp.ID = ID
cp.ShowIcon = True
cp.Style("padding-top") = "1px"
cp.CssClass = "CustomHeight"
Me.divCol.Controls.Add(cp)
End Sub
Protected Sub Update_Click(sender As Object, e As EventArgs) Handles Update.Click
Try
Dim alltxt = divDesc.Controls.OfType(Of TextBox)()
Dim allcomboChart = divChart.Controls.OfType(Of RadComboBox)()
Dim allcomboField = divField.Controls.OfType(Of RadComboBox)()
Dim allcp = divCol.Controls.OfType(Of RadColorPicker)()
''Loop through first set of controls and get values and then the next etc..
Dim Description as string = ''Get Textbox value
Dim Type as string = ''Get RadComboBox value
Dim XFieldName as string = ''Get RadComboBox value
Dim Colour as string = ''Get RadColorPicker value
If Page.IsValid Then
Dim da As New dsSVTableAdapters.Chart
Dim Result As String = da.Series(60, Description, Type, Colour, "YFieldName", XFieldName)
End If
Catch ex As Exception
lblResult.Text = ex.Message
End Try
End Sub
You have a repeated set of controls. Therefore you need a corresponding repeated set of variables that store these values.
I suggest creating a class where you can store a variable (or property) set.
Public Class ControlSet
Public Property Description As String
Public Property Type As String
Public Property XFieldName As String
Public Property Colour As String
End Class
Create an array that holds these values
Dim Values = New ControlSet(ddlFieldNames.SelectedIndex) {}
And retrieve the values in a loop
For i As Integer = 0 To Values.Length - 1
Values(i).Description = CType(divDesc.FindControl("txt-" & Convert.ToString(i + 1)), TextBox).Text
Values(i).Type = CType(divChart.FindControl("comboChart-" & Convert.ToString(i + 1)), RadComboBox).SelectedValue
Values(i).XFieldName = ...
...
Next
Also use the ID of the control; this helps to avoid confusion in case you have several controls of the same type.
you can use .FindControl(string id) method, and you should keep the controls count in your view state or session:
Protected Sub Update_Click(sender As Object, e As EventArgs) Handles Update.Click
Try
''Loop through first set of controls and get values and then the next etc..
For i As Integer = 0 To controlsCount - 1
Dim Description as string = ((TextBox)divDesc.FindControl("txt-" & Convert.ToString(i + 1))).Text ''Get Textbox value
Dim Type as string = ((RadComboBox)divChart.FindControl("comboChart-" & Convert.ToString(i + 1))).SelectedValue ''Get RadComboBox value
Dim XFieldName as string = ((RadComboBox)divField.FindControl("combo-" & Convert.ToString(i + 1))).SelectedValue ''Get RadComboBox value
Dim Colour as string = ((RadColorPicker)divField.FindControl("cp-" & Convert.ToString(i + 1))).SelectedValue ''Get RadColorPicker value
If Page.IsValid Then
Dim da As New dsSVTableAdapters.Chart
Dim Result As String = da.Series(60, Description, Type, Colour, "YFieldName", XFieldName)
Next
End If
Catch ex As Exception
lblResult.Text = ex.Message
End Try
End Sub

(ASP.NET) SQL Data Reader returning Null Values

I am connecting to a database and then using an SQLDataReader to parse through those results and then put those results into variables that I can use at a latter time. The problem is that all of my "results.items" are returning null values. The DataReader is however, showing the proper field count when I debug.
Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "editPost" Then
'Remove DataGrid'''''''''
GridView1.Visible = False
'''''''''''''''''''''''''
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = GridView1.Rows(index)
Dim ID As String = GridView1.Rows(index).Cells(0).Text
''''''''''''''''''''''''''''''''''''''''CREATE Controls for Placeholder
Dim editEditor As New CuteEditor.Editor
Dim hiddenID As New HiddenField
hiddenID.ID = "hiddenID"
hiddenID.Value = ID
editEditor.ID = "editEditor"
Dim subjectTXT As New TextBox
subjectTXT.ID = "editorSubject"
Dim br As New Literal
Dim submitChanges As New Button
Dim sbjLabel As New Label
submitChanges.ID = "submitChanges"
submitChanges.Text = " Submit Changes "
submitChanges.Height = 40
submitChanges.Width = 300
sbjLabel.Text = "Subject: "
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
editEditor.AutoConfigure = CuteEditor.AutoConfigure.Simple
br.Text = "<br/><br/>"
plcEditor.Controls.Add(hiddenID)
plcEditor.Controls.Add(sbjLabel)
plcEditor.Controls.Add(subjectTXT)
subjectTXT.Width = "100"
subjectTXT.Height = "25"
subjectTXT.CssClass = "editInput"
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(editEditor)
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(submitChanges)
submitChanges.OnClientClick = UpdatePost()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim connStr As String = ConfigurationManager.ConnectionStrings("oakfratnewsConnectionString").ConnectionString
Dim nCon As New SqlConnection(connStr)
Dim addCon As New SqlConnection(connStr)
Dim addCom As New SqlCommand("SELECT * FROM [News] WHERE ([ID] = #ID)", addCon)
addCom.Parameters.AddWithValue("#ID", ID)
addCon.Open()
addCom.ExecuteNonQuery()
Dim results As SqlDataReader
results = addCom.ExecuteReader
While results.Read()
Dim editText As String = results.Item("Content")
Dim Subject As String = results.Item("Subject")
editEditor.Text = editText
subjectTXT.Text = Subject
End While
End If
End Sub
Where do you get the ID value?
"addCom.Parameters.AddWithValue("#ID", ID) "
Remove "addCom.ExecuteNonQuery() "
Why using
Dim editText As String = results.Item("Content")
I define before the loop the variable and then read it in this way
Dim editText As String
While results.Read()
editText = results("Content") ' without .items
...
End While

Dynamic tables with hyperlinks

I want to build a table based on data in a recordset with a hyperlink that calls a method which takes the message id from the link and redirects to another page to view the message. I've tried HTMLAnchors, LinkButtons but none seem to work.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim iUserID As Integer
Dim sMsgId, sMsgSubject, sMsgDateSent, sMsgRead, sMsgFrom, sFirstname As String
iUserID = Session("UserID")
Dim cn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString)
Dim cmd As New SqlCommand()
Dim tblRow As TableRow
Dim tblCell1 As TableCell
Dim tblCell2 As TableCell
Dim tblCell3 As TableCell
Dim tblCell4 As TableCell
tblRow = New TableRow
tblCell1 = New TableCell
tblCell1.Text = ""
tblRow.Cells.Add(tblCell1)
tblCell2 = New TableCell
tblCell2.Text = "From"
tblRow.Cells.Add(tblCell2)
tblCell3 = New TableCell
tblCell3.Text = "Subject"
tblRow.Cells.Add(tblCell3)
tblCell4 = New TableCell
tblCell4.Text = "Received"
tblRow.Cells.Add(tblCell4)
tblMessages.Rows.Add(tblRow)
tblCell1 = Nothing
tblCell2 = Nothing
tblCell3 = Nothing
tblRow = Nothing
cmd.CommandText = "SELECT msg.msg_id, msg.msg_usr_from, usr.usr_firstname, msg.msg_subject, msg.msg_date_sent, msg.msg_read FROM messages msg inner join users usr on msg.msg_usr_to = usr.usr_id WHERE msg.msg_usr_to='" & iUserID & "'"
cmd.Connection = cn
cn.Open()
Dim r As SqlDataReader = cmd.ExecuteReader
Dim objControl As Button
While r.Read()
tblCell1 = New TableCell
tblCell2 = New TableCell
tblCell3 = New TableCell
tblCell4 = New TableCell
tblRow = New TableRow
sMsgId = CStr(r("msg_id"))
sMsgFrom = CStr(r("msg_usr_from"))
sFirstname = CStr(r("usr_firstname"))
sMsgSubject = CStr(r("msg_subject"))
sMsgDateSent = CStr(r("msg_date_sent"))
sMsgRead = CStr(r("msg_read"))
If sMsgRead = "N" Then
tblCell1.Text = "<img width=30px src=images/new_email.png>"
Else
tblCell1.Text = "<img width=30px src=images/email_open.png>"
End If
Dim objLinkbutton As
tblRow.Cells.Add(tblCell1)
tblCell2.Text = sFirstname
tblRow.Cells.Add(tblCell2)
tblCell3.controls.add( HYPERLINK HERE!!!
tblRow.Cells.Add(tblCell3)
tblCell4.Text = FormatDateTime(sMsgDateSent, DateFormat.LongDate)
tblRow.Cells.Add(tblCell4)
If sMsgRead = "N" Then
tblCell2.Font.Bold = True
tblCell3.Font.Bold = True
tblCell4.Font.Bold = True
End If
tblMessages.Rows.Add(tblRow)
tblCell1 = Nothing
tblCell2 = Nothing
tblCell3 = Nothing
tblCell4 = Nothing
tblRow = Nothing
End While
r.Close()
cn.Close()
cn = Nothing
r = Nothing
cmd = Nothing
End Sub
Protected Sub viewmessage(messageid As String)
Context.Items("messageid") = "messageid"
Server.Transfer("viewmessage.aspx")
End Sub
End Class
You have two choices, as I see it.
Massage the data set so it contains the complete URI, with the ID, and then bind to a grid
Use a routine to create the URI and then bind the grid via row binding
Continuing hand binding the table, using hyperlink controls
All are easy enough to do, but the #3 option is the least "ASP.NET" like. I am not fond of hand building tables, when I can do the same with a control, simply by either a) altering the data before bind or b) stopping on the row binding event and adding information.
Use query string to store the id value of the selected link and redirect to the page you want.
try something like this:
Dim a As New HyperLink()
a.Text = "your text"
a.NavigateUrl = "yourPage.aspx?idMsg=" + r["msg_id"]
tblCell3.controls.add(a)

Resources