I have tried to select radio button from selected value of a drop down like this
Dim ddlupd As DropDownList = CType(grid.HeaderRow.FindControl("dropdown"), DropDownList)
For Each gv As GridViewRow In grid.Rows
Dim rdo As RadioButtonList = CType(grid.Rows(gv.RowIndex).FindControl("list"), RadioButtonList)
Dim cat As Label = CType(grid.Rows(gv.RowIndex).FindControl("lblcat"), Label)
If cat.Text = ddlupd.SelectedItem.Text Then
rdo.SelectedValue = selflg.ToString()
ElseIf ddlupd.SelectedItem.Text = "Clear Selection" Then
rdo.ClearSelection()
ElseIf ddlupd.SelectedItem.Text = "Select All" Then
rdo.SelectedValue = selflg.ToString()
End If
Next
and there is template field in gridview like this
<asp:TemplateField HeaderText="Status">
<HeaderTemplate>
<asp:DropDownList ID="dropdown" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlupdGM1" BackColor="#3399FF" ForeColor="White">
<asp:ListItem>Select Category</asp:ListItem>
<asp:ListItem>Clear Selection</asp:ListItem>
<asp:ListItem Value="1">Cane Payment</asp:ListItem>
<asp:ListItem Value="2">Income Tax</asp:ListItem>
<asp:ListItem Value="3">Fund Transfer</asp:ListItem>
<asp:ListItem Value="4">Others</asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:RadioButtonList ID="chkStatusGM" runat="server" AutoPostBack="false" RepeatDirection="Horizontal" OnSelectedIndexChanged="chkStatus_OnCheckedChangedGM">
<asp:ListItem Value="5">Approve</asp:ListItem>
<asp:ListItem Value="0">Not Approved</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
Also I Am running a update command to database with selected values of radio button.Problem is that when select the radio button from drop down value of header template then no update runs due to null selection of radiobutton and when i manually select the radio button the update works fine.
Update
**
Protected Sub chkStatus_OnCheckedChangedGM(ByVal sender As Object, ByVal e As System.EventArgs)
Dim cmd As OleDbCommand = New OleDbCommand()
Dim chkStatusGM As RadioButtonList = CType(sender, RadioButtonList)
Dim row As GridViewRow = CType(chkStatusGM.NamingContainer, GridViewRow)
Dim bpvnum As String = row.Cells(4).Text
cmd.CommandText = "update sml.FND_01_11#wbg set sta_flg=:sta_flg where bpv_num=:bpv_num and bpv_dte=:bpv_dte"
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.Parameters.Add(":sta_flg", OleDbType.BigInt).Value = chkStatusGM.SelectedValue
cmd.Parameters.Add(":bpv_num", OleDbType.BigInt).Value = bpvnum
cmd.Parameters.Add(":bpv_dte", OleDbType.Date).Value = TreeView2.SelectedValue
Try
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
Response.Write(ex.ToString())
End Try
End Sub
**
Call the SelectedIndexChanged event of the radio button list (or whatever event handler you are using):
Dim ddlupd As DropDownList = CType(grid.HeaderRow.FindControl("dropdown"), DropDownList)
For Each gv As GridViewRow In grid.Rows
Dim rdo As RadioButtonList = CType(grid.Rows(gv.RowIndex).FindControl("list"), RadioButtonList)
Dim cat As Label = CType(grid.Rows(gv.RowIndex).FindControl("lblcat"), Label)
If cat.Text = ddlupd.SelectedItem.Text Then
rdo.SelectedValue = selflg.ToString()
ElseIf ddlupd.SelectedItem.Text = "Clear Selection" Then
rdo.ClearSelection()
ElseIf ddlupd.SelectedItem.Text = "Select All" Then
rdo.SelectedValue = selflg.ToString()
End If
' call the event handler similar to manually clicking an option
chkStatus_OnCheckedChangedGM(rdo, new System.EventArgs())
Next
Related
I need to get selected items on checkbox and set as string format like (value1,value2,value3) from the checkbox i selected
For Each row As GridViewRow In GridView1.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim CheckRow As CheckBox = (TryCast(row.Cells(1).FindControl("chckSelector"), CheckBox))
If CheckRow.Checked Then
Dim scode As String = TryCast(row.Cells(2).FindControl("lblsstorecode"), Label).Text
lbltest.Text = 'this i want to get the value like this (value1,value2,value3) from checkbox that i selected
End If
End If
Next
Depending on why you are using the GridView control, you might me able to accomplish this easier by using a CheckBoxList instead. In Asp.net what you describe is accomplished very easily with a CheckBoxList as follows:
In .aspx:
<asp:CheckBoxList ID="Itemlst" runat="server" RepeatColumns="1">
<asp:ListItem Value="">Item 1</asp:ListItem>
<asp:ListItem Value="">Item 2</asp:ListItem>
<asp:ListItem Value="">Item 3</asp:ListItem>
</asp:CheckBoxList>
</br>
<asp:Button ID="Button1" runat="server" Text="Button" />
</br>
<asp:TextBox ID="TextBox1" runat="server" Width="400"></asp:TextBox>
Then in the code behind:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim selected = New List(Of ListItem)
Dim itemcount As Integer
Dim csvlist As String = ""
For Each item As ListItem In Itemlst.Items
If item.Selected Then selected.Add(item)
Next
itemcount = selected.Count
For i = 0 To itemcount - 1
csvlist = csvlist & selected(i).ToString & ","
Next
csvlist = Mid(csvlist, 1, Len(csvlist) - 1)
TextBox1.Text = csvlist
End Sub
The Windows Forms CheckedListBox would probably work similar if you are developing a desktop application.
I'm creating a survey system. The creator must be able to create a question a decide what kind of control will give the answer (RadioButtonList, TextBox, etc...)
I have a data table (SQL) which stores the question, and the type of desired answer (dbo.Questions):
ID (int - PK)
IdForm (int - FK to dbo.Forms)
Question (varchar)
TypeOfAnswer (int)
And there's another data table that stores the user answer (dbo.Answers)
ID (int - PK)
QuestionId (int - FK to dbo.Questions.ID)
Answer (varchar)
UserId (int - FK to dbo.Users.ID)
Date (datetime)
So, one example of questions will be:
ID Question TypeOfAnswer
-----------------------------------------------------
1 What color do you like the most? 1
2 Are you happy with your bike? 2
3 What's your favorite ice cream flavor? 3
So the question ID.1 should have a RadioButtonList that will display Blue, Yellow, Green as a label and store 1, 2 or 3 as the value, according to the user's selection.
Question ID.2 sholud be RadioButtonList with only two answers, Yes, No for label and 1,2 for stored values.
Question ID3. should be a TextBox.
I'm having a really big struggle when printing the control to the view (on ASP.Net forms).
So far, I've created a dataset, and according to each row, it should print the question's label, and the user control that will store the answer, this is my code so far:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Dim ptipo As Integer = 2
Dim tcontrol1 As Control
tcontrol1 = LoadControl("/WebUSerControl.ascx")
Dim dt As New DataTable()
Dim connection As New SqlConnection(enchufalo1)
connection.Open()
Dim sqlCmd As New SqlCommand("SELECT * FROM [BORRAR_CL_Preguntas] WHERE ([IdFormato] = #IdFormato)", connection)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#IdFormato", Request.QueryString("iform"))
sqlDa.Fill(dt)
Dim ctipo As Integer
For Each Row As DataRow In dt.Rows
ctipo = Row("TypeOfAnswer")
If ctipo = 1 Then
Dim rbl As RadioButtonList = New RadioButtonList()
rbl.ID = "rbl_prg1"
rbl.Items.Add("1")
rbl.Items.Add("2")
rbl.Items.Add("3")
ph_print.Controls.Add(rbl)
lit_prg.Text += Row("Question")
lit_prg.Controls.Add(tcontrol1)
End If
Next
End Sub
Right now the ph_print placeholder is printing the radiobutton, but skipping the first question!! And I have not been able to add the question label nor HTML styling
Any help would be appreciated!
I came up with a solution for this issue...
Here's the front code:
<asp:Repeater ID="rpt_preguntas" runat="server" DataSourceID="DS01">
<ItemTemplate>
<div class="Col100">
<div class="Col60">
<%#Eval("Pregunta") %>
</div>
<div class="Col5"></div>
<div class="Col35">
<div runat="server" visible='<%# (Eval("Tipo").ToString() = "1") %>'>
<asp:RadioButtonList ID="resp_tipo1_rbl" runat="server" RepeatDirection="Horizontal" RepeatColumns="6" ValidationGroup="valrspX">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
<asp:ListItem Value="5">5</asp:ListItem>
<asp:ListItem Value="6">NS/NR</asp:ListItem>
</asp:RadioButtonList>
</div>
<div runat="server" visible='<%# (Eval("Tipo").ToString() = "2") %>'>
<asp:TextBox ID="tb_tipo2" runat="server"></asp:TextBox>
</div>
<div runat="server" visible='<%# (Eval("Tipo").ToString() = "3") %>'>
<asp:DropDownList ID="ddl_perros" runat="server">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="A">Azul enfermo</asp:ListItem>
<asp:ListItem Value="B">Blanco nigga</asp:ListItem>
<asp:ListItem Value="C">Café popó</asp:ListItem>
<asp:ListItem Value="D">Dorado blin blin</asp:ListItem>
</asp:DropDownList>
</div>
</div>
</div>
<br /><br />
<asp:Label ID="pregid" runat="server" Text='<%#Eval("ID") %>' Visible="false"></asp:Label>
</ItemTemplate>
</asp:Repeater>
And the back code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_enviar.Click
Try
Dim spregid As Integer
Dim spregrs As String
For Each elemento As RepeaterItem In rpt_preguntas.Items
Dim prg_id As Label = DirectCast(elemento.FindControl("pregid"), Label)
Dim stipo As Integer
Dim SqlCon0 As SqlConnection
Dim SqlCom0 As SqlCommand
Dim SqlDR0 As SqlDataReader
SqlCon0 = New SqlConnection(ConfigurationManager.ConnectionStrings("EnchufeUNICOC").ToString())
SqlCom0 = New SqlCommand("SELECT * FROM [dbo].[BORRAR_CL_Preguntas] WHERE([ID] = '" & prg_id.Text & "')", SqlCon0)
SqlCom0.CommandType = CommandType.Text
If SqlCon0.State = ConnectionState.Closed Then
SqlCon0.Open()
'Dim p0 As New SqlParameter("#cc", SqlDbType.VarChar)
'p0.Direction = ParameterDirection.Input
'p0.Value = num_cc
'SqlCom0.Parameters.Add(p0)
End If
SqlDR0 = SqlCom0.ExecuteReader()
While SqlDR0.Read()
stipo = SqlDR0("tipo")
End While
SqlDR0.Close()
SqlCon0.Close()
Dim respuesta As String
If stipo = 1 Then
Dim control_t1 As RadioButtonList = DirectCast(elemento.FindControl("resp_tipo1_rbl"), RadioButtonList)
respuesta = control_t1.SelectedValue
End If
If stipo = 2 Then
Dim control_t2 As TextBox = DirectCast(elemento.FindControl("tb_tipo2"), TextBox)
respuesta = control_t2.Text
End If
If stipo = 3 Then
Dim control_t3 As DropDownList = DirectCast(elemento.FindControl("ddl_perros"), DropDownList)
respuesta = control_t3.SelectedValue
End If
resultados.Text += "Pregunta ID: " & prg_id.Text & "<br/>Respuesta: " & respuesta & "<br/><br/>"
Next
Catch ex As Exception
resultados.Text = "La cagamos mano:<br/><br/>" & ex.ToString
End Try
End Sub
So it was solved by adding a conditional to the Repeater control in it's ItemTemplate!
I am trying to fill a text box with an ID of O1IDText when the selected value of a drop down list is changed. I get an error "Object reference not set to an instance of an object".
Here is my code in ASP of the drop down list:
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server" DataSourceID="SqlDataSource2" AppendDataBoundItems="true" OnDataBinding="DropDownlist1_DataBinding1" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" DataTextField="FullName" DataValueField="FullName" SelectedValue='<%# Bind("Official1") %>'>
</asp:DropDownList>
</EditItemTemplate>
Below is the code of my Textbox wihtin ASP:
<EditItemTemplate>
<asp:TextBox ID="O1IDText" runat="server" Text='<%# Bind("O1ID") %>'></asp:TextBox>
</EditItemTemplate>
And Finally my code behind in VB:
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddList As DropDownList = CType(sender, DropDownList)
RemoveHandler ddList.DataBinding, AddressOf DropDownlist1_DataBinding1
Dim O1IDText As TextBox = TryCast(FindControl("O1IDText"), TextBox)
Dim cmd As SqlCommand = con.CreateCommand()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Select ID from Official where [First Name] + ' ' + [Last Name]+ ' ' +[Email]+ ' ' +[Phone] = '" + ddList.SelectedValue + "'"
Dim dr As SqlDataReader
Try
con.Open()
dr = cmd.ExecuteReader()
dr.Read()
O1IDText.Text = dr("ID").ToString
Catch ex As Exception
con.Close()
End Try
The exception "Object reference not set to an instance of an object" happens during O1IDText.Text = dr("ID").ToString.
Assuming that the DropDownList and the TextBox are both in the same row or item, you can get the TextBox this way:
Dim O1DText As TextBox = CType(ddList.NamingContainer.FindControl("O1DText"), TextBox)
I have a GridView as below
<asp:GridView ID="gvChain" runat="server" Font-Size="Small" CellPadding="3" CellSpacing="1" GridLines="None" AutoGenerateColumns="False">
<headerstyle backcolor="#CCCCCC" />
<columns>
<asp:BoundField DataField="Department" HeaderText="Department" />
<asp:TemplateField HeaderText="Manager Level 1">
<ItemTemplate>
<asp:Label ID="lblManager1" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cbManager1" runat="server"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Manager Level 2">
<ItemTemplate>
<asp:Label ID="lblManager2" runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cbManager2" runat="server"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True">
<ControlStyle ForeColor="#009EDD" />
</asp:CommandField>
</columns>
</asp:GridView>
The BoundField 'Department' is being populated in the Page_Load as below which works fine and populates the GridView with a list of departments.
Dim dhandler As DepartmentHandler = New DepartmentHandler
Dim depts As New List(Of Department)
depts = dhandler.GetDepartmentList
gvChain.DataSource = depts
gvChain.DataBind()
I am then populating the ItemTemplates of the TemplateFields in the RowDAtaBound event as below. this is also working fine.
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblManager1 As Label = DirectCast(e.Row.FindControl("lblManager1"), Label)
Dim lblManager2 As Label = DirectCast(e.Row.FindControl("lblManager2"), Label)
Dim eHandler As EmployeeHandler = New EmployeeHandler
Dim deptCell As TableCell = e.Row.Cells(0)
Dim dept As Department = New Department
dept.Department = deptCell.Text
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
lblManager1.Text = mgr1.Name
lblManager2.Text = mgr2.Name
End If
What I now want to achieve is when clicking on the 'Edit' field of a row on the GridView, populate cbManager1 and cbManager2 with a list of Managers and set the SelectedValue of each DDL to the same values as I am retrieving in the item template. I can get the data with the below code in the RowEditing event of the GridView:
' Get the list of managers
Dim mgrs As New List(Of Manager)
mgrs = eHandler.GetManagerList
' Get the department name from the BoundField
Dim deptCell As TableCell = gvChain.Rows(e.NewEditIndex).Cells(0)
Dim dept As Department = New Department
dept.Department = deptCell.Text
' Pass the department name to the getManager1/2 functions to return the correct manager for that department
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
I have set breakpoints to check the data is being returned from the functions and the data is there as expected but where I am stuck is getting a reference on the DDLs in the EditItemTemplate so I can databind them and set the SelectedValue.
I have tried the below but this is giving a NullReference Exception:
Dim cbManager1 As DropDownList = TryCast(gvChain.Rows(e.NewEditIndex).FindControl("cbManager1"), DropDownList)
Dim cbManager2 As DropDownList = TryCast(gvChain.Rows(e.NewEditIndex).FindControl("cbManager2"), DropDownList)
I got round this in the end. I added the following code to the RowEditing event
gvChain.EditIndex = e.NewEditIndex
gvChain.DataBind()
I then did the following in the RowDataBound event
If e.Row.RowState = DataControlRowState.Edit Then
Dim cbManager1 As DropDownList = TryCast(e.Row.FindControl("cbManager1"), DropDownList)
Dim cbManager2 As DropDownList = TryCast(e.Row.FindControl("cbManager2"), DropDownList)
Dim eHandler As EmployeeHandler = New EmployeeHandler
Dim mgrs As New List(Of Manager)
mgrs = eHandler.GetManagerList
cbManager1.DataSource = mgrs
cbManager2.DataSource = mgrs
cbManager1.DataValueField = "Name"
cbManager1.DataTextField = "Name"
cbManager2.DataValueField = "Name"
cbManager2.DataValueField = "Name"
cbManager1.DataBind()
cbManager2.DataBind()
' Got rid of the bound field in the end and did it with a templatefield so needed to get the department from the label
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
Dim mgr1Name As String = mgr1.Name.ToUpper()
Dim mgr2Name As String = mgr2.Name.ToUpper()
cbManager1.SelectedValue = mgr1Name
cbManager2.SelectedValue = mgr2Name
End If
You could try something like this
If e.Row.RowState = DataControlRowState.Edit Then
Dim cbmanager As DropDownList = e.Row.FindControl("cbmanager1")
If Not cbmanager Is Nothing Then cbmanager.Items.Add(New ListItem("Test1", "Test1"))
End If
I have a DataGrid bound to a DataView which, among other columns has, an ID Column and ParentID Column, I need the user to be able to specify a ParentID using using a DropDownList (ComboBox).
Now, I have already added the DropDownList to the DataGrid like this:
<Columns>
[...]
<asp:TemplateColumn HeaderText="Parent" >
<ItemTemplate>
<asp:DropDownList ID="ddlParentID"
runat="server"
DataValueField="ID"
DataTextField="Short_Description"
Width="100%"
DataSource="<%# dsDV %> ">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
In the code-behind I have the following a method:
Protected dsDV As New DataView
Protected Sub PopulateDropDownList()
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(myConnString)
Dim comm As SqlClient.SqlCommand = New SqlClient.SqlCommand("SELECT * FROM myTable", conn)
comm.CommandType = CommandType.Text
Dim myTableTable As New DataTable
conn.Open()
myTableTable.Load(comm.ExecuteReader)
Me.dsDV = myTableTable.DefaultView
End Sub
That PopulateDropDownMethod is called on the form Load Event but, albeit DDLs do show, they show empty, as if no DataBinding is being made.
How can I properly bind the DDL with a dataSource in the codebehind? Or, if that's not the issue, how do I properly fill the DDL?
Update 1
After the first answer I went ahead and tried this (still no luck):
Protected Sub dg_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgData.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim ddl As DropDownList = CType(e.Item.Cells(3).FindControl("ddlParentID"), DropDownList)
Me.PopulateDropDownList(ddl)
End If
End Sub
Protected dsDV As New DataView
Protected Sub PopulateDropDownList(ddl As DropDownList)
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(myConnString)
Dim comm As SqlClient.SqlCommand = New SqlClient.SqlCommand("SELECT * FROM myTable", conn)
comm.CommandType = CommandType.Text
Dim myTableTable As New DataTable
conn.Open()
myTableTable.Load(comm.ExecuteReader)
ddl.DataSource = myTableTable.DefaultView
ddl.DataBind()
End Sub
Note that I also removed the call to PopulateDropDownList from the Form Load Event handler.
you may try to call ddlParent.DataBind() after setting the datasource.
I don't why but taking the binding code from the aspx to the aspx.vb fixed the issue, so it all looks like this now:
<asp:TemplateColumn HeaderText="Parent" >
<ItemTemplate>
<asp:DropDownList ID="ddlParentID" runat="server" Width="100%" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
And for the code-behind, for each row:
Dim ddl As DropDownList = CType(e.Item.Cells(3).FindControl("ddlParentID"), DropDownList)
ddl.DataValueField = "ID"
ddl.DataTextField = "Short_Description"
ddl.DataSource = myTable.DefaultView
ddl.DataBind()