I have radio button like below
<dx:ASPxRadioButtonList ID="radClaimType" runat="server" RepeatDirection="Horizontal" AutoPostBack="true" ValueType="System.String" Border-BorderStyle="None">
<Items>
<dx:ListEditItem Text="Expenses" Value="1" />
<dx:ListEditItem Text="Travel" Value="2" />
</Items>
</dx:ASPxRadioButtonList>
How do I select/check the radio button based on the value that I have inserted in database ?
Here is my code behind
Dim dt As New Datatable
Dim strSelect As String = "SELECT claim_type FROM detail_table WHERE id = '30'"
Dim myconn As New clsConnection
Try
myconn.OpenConnection()
myconn.FillDataTable(dt, strSelect)
myconn.CloseConnection()
If dt.Rows.Count > 0 Then
If dt.Rows(0).Item("claim_type") = 1 Then
radClaimType.SelectedIndex = 1
ElseIf dt.Rows(0).Item("claim_type") = 2 Then
radClaimType.SelectedIndex = 2
End If
radClaimType.Enabled = False
End If
Catch ex As Exception
MsgBox("Error")
myconn.CloseConnection()
End Try
The result is like this which is incorrect because the claim_type value for id = '30' is 1 which is Expense. I have debug the code and the value for claim_type is indeed 1 but the radio button does not checked/selected to Expense. How do I correct this ?
You should tag what 3rd party control library you are using here.
Anyway, as a general rule, the asp.net RB-list can be set by "index", starting at 0, or you can set by value.
So, for your code, then this:
radClaimType.SelectedValue = dt.Rows(0).Item("claim_type")
You do NOT want to set by index, since the RB list could have ANY values, and
0 = first one
1 = 2nd one
etc. etc. etc.
So, index starts at 0
but, you want to set the RB by "value", and hence:
radClaimType.SelectedValue = dt.Rows(0).Item("claim_type")
You can check your documentaton for that control (I don't have it).
But, you don't need a "if/then" here. You can set the value of the RB, and it should then select/display the value corectly
so with this:
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
RepeatDirection="Horizontal" AutoPostBack="true" >
<asp:ListItem Value="100">Expenses</asp:ListItem>
<asp:ListItem Value="200">Travel</asp:ListItem>
</asp:RadioButtonList>
Then I can set 0 (first) or 1 (second) using "indexing" like this:
RadioButtonList1.SelectedIndex = 0 ' would select the 100
RadioButtonList1.SelectedIndex = 1 ' would select the 200
Or, by value
RadioButtonList1.SelectedValue = 100 ' would select the first one
Related
The problem I'm having is when a user skips over cycle time, even with the required field validator in place it allows to to still submit and crash the page. I tried setting an initial value but that didn't work.
<div class="col-lg-4" style="text-align: left;">
<label for="txtCycle_Time">Cycle Time (format mm:ss) :</label>
<asp:TextBox ID="txtCycle_Time" MaxLength="5" CssClass="form-control" runat="server"></asp:TextBox>
<ajaxToolkit:MaskedEditExtender ID="txtCycle_Time_MaskedEditExtender" AutoComplete="true" MaskType="Time" AcceptAMPM="false" runat="server" MessageValidatorTip="true" TargetControlID="txtCycle_Time" Mask="99:99" ClearMaskOnLostFocus="false" />
<asp:RequiredFieldValidator ID="txtCycle_Time_RequiredFieldValidator" runat="server" InitialValue="00:00" Text="Please Enter Cycle Time" ControlToValidate="txtCycle_Time" ValidationGroup="Input" Font-Italic="True" ForeColor="Red" />
</div>
Dim Cycle_Time_Sec As Integer = 0
Dim My_Time As String = ""
My_Time = txtCycle_Time.Text
Dim Min As String = My_Time.Substring(0, 2)
Dim Sec As String = My_Time.Substring(3, 2)
Cycle_Time_Sec = Min * 60 + Sec
You could try a server side validation on postback:
Dim Cycle_Time_Sec As Integer = 0
Dim My_Time As String = ""
//Validation here
If txtCycle_Time.Text is null Then return "Please type time value!"
My_Time = txtCycle_Time.Text
Dim Min As String = My_Time.Substring(0, 2)
Dim Sec As String = My_Time.Substring(3, 2)
Cycle_Time_Sec = Min * 60 + Sec
Wrote this to fix the issue, now form works as intended.
If (txtCycle_Time.Text.Trim = "__:__" Or txtCycle_Time.Text.Trim = "__:__ AM"
Or txtCycle_Time.Text.Trim = "__:__ PM") Then ScriptManager.RegisterStartupScript(Me, Me.GetType(), "Cycle_Time_Error", "Cycle_Time_Error();", True)
Exit Sub
End If
I have radio button list. asp code:
Auditing: <asp:RadioButtonList ID="RBLAudit" runat="server" Font-Bold="true" RepeatDirection="Horizontal" RepeatLayout="Flow" TextAlign="Left">
<asp:ListItem Value="true" Text=" Audited" Selected="True"/>
<asp:ListItem Value="false" Text=" Not Audited "/>
<asp:ListItem Value="" Text="ALL"/>
</asp:RadioButtonList>
and I have RDLC Report with Boolean parameter as bellow:
I want to pass null value when select ALL option of radio button list.
I try this code behind
If (RBLAudit.SelectedValue <> "") Then
p9 = New ReportParameter("State", RBLAudit.SelectedValue)
ElseIf (RBLAudit.SelectedValue = "") Then
p9 = New ReportParameter("State", DBNull.Value.ToString())
End If
Dim RepParams() As ReportParameter = {p1, p2, p3, p4, p5, p6, p7, p8, p9}
but this not work when RBLAudit.SelectedValue = "" . The error is "The value provided for the report parameter 'State' is not valid for its type."
How to pass null value for this Boolean parameter?
finally it works after very much trying and failing...
If (RBLAudit.SelectedValue <> "") Then
p9 = New ReportParameter("State", RBLAudit.SelectedValue)
ElseIf (RBLAudit.SelectedValue = "") Then
p9 = New ReportParameter("State", New String() {Nothing})
End If
any other idea?
i have a question to do...
So, i have 2 radiobuttons called "Em Vigor" and "Anulada"
2 radiobutton when i click, they refresh a datatable, and i cant refresh the datatable with my SQL code. I did this:
<form runat="server">
<asp:RadioButton ID="FXvigor" Text="Em Vigor" runat="server" />
<asp:RadioButton ID="FXanulada" Text="Anulada" runat="server" />
</form>
These are the 2 buttons that i have created, and these are 2 if's with SQL commands. But i have search ong google and i cant refresh any of them.
So this is the code:
While FXanulada.Checked = True
FXvigor.Checked = False
If Not Rs.IsClosed Then Rs.Close()
Cmd = New SqlCommand("SELECT tbClientes_Apolices_Bem_Tipos.descrit as tipo, SOURCE.descrit, SOURCE.bem_id, tbClientes_Apolices.apolice_main_id, tbClientes_Apolices.apolice_id, tbClientes_Apolices.apolice_no, tbClientes_Apolices_Tipos.descrit AS apolice_tipo, tbClientes_Apolices.data_inicio, tbClientes_Apolices.data_termo, tbContactos.chave AS seguradora, tbRamos.descrit AS ramo, CASE WHEN nvigor=0 THEN 'Em vigor' WHEN nvigor <> 0 THEN 'Não está em vigor' END AS nvigor_descrit, tbClientes_Apolices.premio_total, SOURCE.tipo_bem_id, SOURCE.apolice_link_id, nvigor FROM (SELECT tbClientes_Apolices_Bem_links.descrit, tbClientes_Apolices_Bem_links.bem_id, tbClientes_Apolices_Bem_links.tipo_bem_id, tbClientes_Apolices.apolice_main_id, MAX(tbClientes_Apolices.apolice_id) as apolice_id, MAX(tbClientes_Apolices_Bem_links.apolice_link_id) as apolice_link_id FROM tbClientes_Apolices_Bem_links LEFT JOIN tbClientes_Apolices ON tbClientes_Apolices_Bem_links.apolice_id = tbClientes_Apolices.apolice_id WHERE tbClientes_Apolices.contacto_id = " & contacto_id.ToString & " GROUP BY tbClientes_Apolices_Bem_links.descrit, tbClientes_Apolices_Bem_links.bem_id, tbClientes_Apolices_Bem_links.tipo_bem_id, tbClientes_Apolices.apolice_main_id ) AS SOURCE LEFT JOIN tbClientes_Apolices ON SOURCE.apolice_id = tbClientes_Apolices.apolice_id LEFT JOIN tbClientes_Apolices_Tipos ON tbClientes_Apolices.tipo_id = tbClientes_Apolices_Tipos.tipo_id LEFT JOIN tbContactos ON tbClientes_Apolices.seguradora_id = tbContactos.contacto_id LEFT JOIN tbSeguradoras_Ramos ON tbClientes_Apolices.ramo_id = tbSeguradoras_Ramos.ramo_id LEFT JOIN tbRamos ON tbSeguradoras_Ramos.ramo_descrit_id = tbRamos.ramo_descrit_id LEFT JOIN tbClientes_Apolices_Bem_Tipos ON SOURCE.tipo_bem_id = tbClientes_Apolices_Bem_Tipos.tipo_bem_id ORDER BY SOURCE.descrit, SOURCE.bem_id, tbClientes_Apolices.data_inicio, tbRamos.descrit", CDSI.SQLServer)
Rs = Cmd.ExecuteReader()
End While
While FXvigor.Checked = True
FXanulada.Checked = False
If Not Rs.IsClosed Then Rs.Close()
Cmd = New SqlCommand("SELECT tbClientes_Apolices.*, tbContactos.chave AS seguradora, tbRamos.ramo_descrit_id, tbRamos.descrit AS ramo, tbClientes_Apolices_Tipos.descrit AS tipo, tmpClientes.nome_union AS cliente, CASE WHEN apolice_no = '' THEN 'PROPOSTA' WHEN apolice_no IS NULL THEN 'PROPOSTA' ELSE apolice_no END AS apolice_no_descrit, CASE WHEN nvigor=0 THEN 'Em vigor' WHEN nvigor<>0 THEN 'Não está em vigor' END AS nvigor_descrit, tbClientes.tipo_id as tipo_cliente_id, risco1.risco, tbClientes_Apolices_Permitions.group_code, tbClientes_Apolices_Permitions.user_code FROM (SELECT MAX(apolice_id) as apolice_id FROM tbClientes_Apolices GROUP BY apolice_main_id) AS A1 LEFT JOIN tbClientes_Apolices ON A1.apolice_id = tbClientes_Apolices.apolice_id LEFT OUTER JOIN tbContactos AS tmpClientes ON tbClientes_Apolices.contacto_id = tmpClientes.contacto_id LEFT OUTER JOIN tbClientes_Apolices_Permitions ON tbClientes_Apolices.apolice_main_id = tbClientes_Apolices_Permitions.apolice_main_id LEFT OUTER JOIN tbClientes ON tbClientes_Apolices.contacto_id = tbClientes.contacto_id LEFT JOIN (SELECT apolice_id, MIN(descrit) as risco FROM tbClientes_Apolices_Bem_Links WHERE predefinido <> 0 GROUP BY apolice_id ) AS Risco1 ON A1.apolice_id = Risco1.apolice_id, tbContactos, tbSeguradoras_Ramos, tbRamos, tbClientes_Apolices_Tipos WHERE tbClientes_Apolices.nvigor <> 0 AND tbClientes_Apolices.ramo_id = tbSeguradoras_Ramos.ramo_id AND tbSeguradoras_Ramos.ramo_descrit_id = tbRamos.ramo_descrit_id AND tbClientes_Apolices.seguradora_id = tbContactos.contacto_id AND tbClientes_Apolices.tipo_id = tbClientes_Apolices_Tipos.tipo_id AND tbClientes_Apolices.contacto_id=" & contacto_id.ToString & " ORDER BY tbClientes_Apolices.data_inicio DESC", CDSI.SQLServer)
Rs = Cmd.ExecuteReader()
End While
To execute code on the server side you need to declare an event handler for your radiobuttons and set the AutoPostBack property to True otherwise the Radiobutton will post their new state only when the page is submitted again
<form runat="server">
<asp:RadioButton ID="FXvigor" Text="Em Vigor" runat="server" AutoPostBack="True"
OnCheckedChanged="FXvigor_CheckedChanged"/>
<asp:RadioButton ID="FXanulada" Text="Anulada" runat="server" AutoPostBack="True"
OnCheckedChanged="FXanulada_CheckedChanged"/>
</form>
Protected Sub FXVigor_CheckedChanged(sender as object,e as System.EventArgs)
if FXVigor.Checked = True Then
....
End If
End Sub
Protected Sub FXanulada_CheckedChanged(sender as object,e as System.EventArgs)
if FXanulada.Checked = True Then
....
End If
End Sub
I have problem linking 2 datatables using a pID. It isn't an automated number. The thing is, I have to save the pID number into the database when I select an option in a drop down list. But the options shown are course names (Text).
After selecting from the drop down list, input text into a textbox and then click on a button to save both the pID number and description into the database. In 1 database table, it has the course name and pID number. The 2nd database table has the pID number and description(Save info into here).
I'm only able the save the selectedindex, which isn't the pID number.
.aspx.vb Code
Dim OdbcCon As New System.Data.Odbc.OdbcConnection
Dim cmd As New OdbcCommand
OdbcCon.Open()
cmd.Connection = OdbcCon
cmd.CommandText = " insert into StdBookInfo(pID,Description) values ('" & DropDownListStudent.SelectedIndex & "','" & TextBox1.Text & "') "
cmd.ExecuteNonQuery()
Code for drop down list:
sqlcmd3 = "select Course_code + ' - ' + package from StudentPackage order by pID asc "
sqlcmd4 = "select pID from StudentPackage order by Course_code,package asc "
cmd3.Connection = OdbcCon
cmd3.CommandText = sqlcmd3
DropDownListStudent.Items.Add("")
reader3 = cmd3.ExecuteReader
While reader3.Read
DropDownListStudent.Items.Add(reader3.Item(0).ToString)
End While
DropDownListStudent.SelectedIndex = -1
reader3.Close()
cmd3.Dispose()
cmd4.Connection = OdbcCon
cmd4.CommandText = sqlcmd4
reader4 = cmd4.ExecuteReader
I = 0
While reader4.Read
pID(I) = reader4.Item(0)
I = I + 1
End While
reader4.Close()
cmd4.Dispose()
OdbcCon.Close()
You need to set the Text and Value properties of each item of DropDownList, then use SelectedValue instead SelectedIndex.
<asp:DropDownList id="DropDownListStudent" Runat="Server">
<asp:ListItem Text="Item 1" Value="1"/>
<asp:ListItem Text="Item 2" Value="2"/>
<asp:ListItem Text="Item 3" Value="3"/>
<asp:ListItem Text="Item 4" Value="4"/>
<asp:ListItem Text="Item 5" Value="5"/>
</asp:DropDownList>
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