<asp:CheckBoxList Visible="false" runat="server" Width="500px" ID="tblAddlProperty"/>
I have a checkbox list like this, I need to store the checked values (single or Multiple) into a string. Could anyone please help me with this?
Ok, you don't quite mention how you fill out this CheckBox list.
but, say we have a list of Cities, and you need to select a bunch, and then return a string.
So, we could have this markup:
<div style="float:left">
<style> .butLabel label {margin-left:15px} </style>
<asp:CheckBoxList ID="ChkCity" runat="server" CssClass="butLabel"
DataValueField="id"
DataTextField="City" >
</asp:CheckBoxList>
</div>
<asp:Button ID="cmdDone" runat="server" Text="Confirm Cities" cssclass="btn"/>
Note VERY close: a combobox (dropdown list), a ListBox tend to have TWO values that the list can hold.
The "display" text - nice for the end user.
The "value" text - this can be say a PK id of the database in question. From your question, quite much sounds like you want the text.
So, code to fill out the above list can be say this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData
End If
End Sub
Sub LoadData()
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand("SELECT ID, City from City ORDER BY City", conn)
conn.Open()
ChkCity.DataSource = cmdSQL.ExecuteReader
ChkCity.DataBind()
End Using
End Using
End Sub
and now we have this:
Ok, and for our button code to get a "string" of values selected, we can do this:
Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click
Dim strCities As String = "" ' our city string result
For Each MySel As ListItem In ChkCity.Items
If MySel.Selected Then
If strCities <> "" Then strCities &= ","
strCities &= MySel.Text
End If
Next
Debug.Print(strCities)
End Sub
So, say we select the first 4 like this:
Then our output will have this:
Output:
Banff,Calgary,Canmore,Edmonton
Related
I am stuck into a asp.net use case where a listbox(id:l1) is getting populated from a query which returns say 3 columns(name, id, value), now the id is assigned to l1.datavaluefield="id" , but i want to store the value of name in a string variable based on which ever item I click on the listbox. How do i do this please help
I have no idea at all.
Well, it does not really matter if the query returns 3 columns, or 10 columns.
The list box only has provisions for 2 columns. So, in most cases, you store the "value" as the database "ID" column, and then you have a column for display of the 2nd column.
To get "other" columns - ones not included in the listbox?
you as a genreal rule have to use the "ID" and re-pull (use anohter query) to get those other columns.
So, say we have a list box, it will display ID, and HotelName (2 columns). it really does not matter if you feed the listbox 5 or 10 columns, it will still only use + store + have the 2 columns.
So, lets setup a list box, and when you click on the given hotel, we will display other columns from that table on the web page.
So, this list box, and a bit more to display the other columns:
<h4>Select Hotel</h4>
<asp:ListBox ID="ListBox1" runat="server"
DataValueField="ID"
DataTextField="HotelName"
AutoPostBack="true"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" Height="162px" Width="308px" >
</asp:ListBox>
<br />
<h4>Hotel Informaton</h4>
<div style="width: 303px; height: 185px;">
<div style="text-align: right">
HotelName: <asp:TextBox ID="txtHotel" runat="server"></asp:TextBox> <br />
City: <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
</div>
Descripiton:
<br />
<asp:TextBox ID="txtDesc" runat="server" TextMode="MultiLine" Height="83px" Width="290px"></asp:TextBox>
</div>
And our code behind is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData
End If
End Sub
Sub Loaddata()
Dim strSQL As string =
"SELECT ID, HotelName FROM tblHotelsA
ORDER BY HotelName"
Dim cmdSQL As New SqlCommand(strSQL)
ListBox1.DataSource = MyrstP(cmdSQL)
ListBox1.DataBind()
End Sub
Protected Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim PKID As Integer = ListBox1.SelectedItem.Value
Dim cmdSQL As New SqlCommand("SELECT * FROM tblHotelsA WHERE ID = #ID")
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID
Dim rstData As DataTable = MyrstP(cmdSQL)
With rstData.Rows(0)
txtHotel.Text = .Item("HotelName")
txtCity.Text = .Item("City")
txtDesc.Text = .Item("Description")
End With
End Sub
Public Function MyrstP(cmdSQL As SqlCommand) As DataTable
Dim rstData As New DataTable
Using mycon As New SqlConnection(GetConstr)
Using (cmdSQL)
cmdSQL.Connection = mycon
mycon.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
And now we get/see this:
So, note how we are free to get/use/have ANY column from the database. However, since the listbox ONLY holds those two columns, then we have to hit the database again based on the LB selecting, pull the additional columns, and at that point we are free to use/have/enjoy use of all database columns, not just the ones used in the bl
I'm trying to Filter GridView with Multiple 'DropDownList with Multi-Select' using jQuery Select2.
I'm following the codes from this link >> https://www.aspsnippets.com/questions/182622/Filter-GridView-with-multi-select-DropDownList-using-jQuery-Select2-Plugin-in-ASPNet-using-C-and-VBNet/ this can only filter gridview using one dropdown. My requirement is to filter gridview using two dropdowns with Multi-Select.
I'm getting stuck at 'condition1' and 'where' condition in the below code
Any help or lead to fix the below code is highly appreciated.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlCountries.DataBind()
End If
End Sub
Protected Sub OnSearch(ByVal sender As Object, ByVal e As EventArgs)
Dim query As String = " SELECT distinct([CUSTOMER_NAME_CMT]),[Acc Number] FROM dbo.MASTERDATA_PRO"
Dim condition As String = String.Empty
For Each item As String In hfSelected.Value.Split(","c)
condition += String.Format("'{0}',", item)
Next
Dim condition1 As String = String.Empty
For Each item As String In hfSelected_ACCNO.Value.Split(","c)
condition1 += String.Format("'{0}',", item)
Next
If Not String.IsNullOrEmpty(condition) Then
condition = String.Format(" WHERE CUSTOMER_NAME_CMT IN ({0}) ", condition.Substring(0, condition.Length - 1))
End If
If Not String.IsNullOrEmpty(condition1) Then
condition1 = String.Format(" and [Acc Number] IN ({0}) ", condition1.Substring(0, condition1.Length - 1))
End If
GridView1.DataSource = GetData(query & condition & condition1 )
GridView1.DataBind()
End Sub
Private Function GetData(ByVal query As String) As DataTable
Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand(query)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
cmd.Connection = con
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Using
End Function
End Class
Ok, unfortantly that example is a mess - and does not work correctly.
And it has extras things like that hidden field in the markup that's not even used.
However, there are "several issues that crop up"
First up?
Unfortantly the asp.net "dropdown" list control does not work if you want multi-select to work.
However, have no fear - just use the standard "HTML" "select" tag.
And MORE interesting, is that the select tag quite much supports darn near everything the DropDownList supports (they are actually much the same - the asp.net is based on it. In fact ALL of the settings are much the same, and you can even use data bound.
(for most dropdowns - yes, I recommend you continue to use dropDownList).
however, that "select2" jQuery add-in? It has issues.
So, here is working example. (we will select some Cities, and display hotels).
So, our markup looks like this:
<asp:Label ID="Label1" runat="server" Text="Select City(s) for Hotels" Style="float:left;margin-right:25px" Font-Size="Large"></asp:Label>
<select ID="cboCity" runat="server" Style="width:200px"
DataTextField="City"
DataValueField="City"
CssClass="form-control"
ClientIDMode="Static">
</select>
<asp:Button ID="Button1" runat="server" Text="Search" style="margin-left:25px"/>
</div>
<br />
<br />
<div style="clear:both;float:left;width:60%">
<asp:GridView ID="GridView1" runat="server" class="table table-hover" ></asp:GridView>
</div>
</form>
<script>
$(document).ready(function () {
$("#cboCity").select2({
placeholder: 'Select city(s)',
allowClear: true
});
});
</script>
our code behind can look like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' load our combo
Using cmdSQL As New SqlCommand("SELECT City from City ORDER BY City",
New SqlConnection(My.Settings.TEST4))
cmdSQL.Connection.Open()
cboCity.DataSource = cmdSQL.ExecuteReader
cboCity.DataBind()
cboCity.Multiple = True
End Using
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using cmdSQL As New SqlCommand("SELECT * FROM VHotels ",
New SqlConnection(My.Settings.TEST4))
Dim strWhere = ""
For Each MySelect As ListItem In cboCity.Items
If MySelect.Selected Then
With cmdSQL.Parameters
If strWhere <> "" Then strWhere &= ","
strWhere &= "#" & .Count
.Add("#" & .Count, SqlDbType.NVarChar).Value = MySelect.Value
End With
End If
Next
cmdSQL.Connection.Open()
cmdSQL.CommandText &= "WHERE City in (" & strWhere & ") ORDER BY HotelName"
GridView1.DataSource = cmdSQL.ExecuteReader
GridView1.DataBind()
End Using
End Sub
The results look like this:
Note carefull how we had to remove the select=multiple from the markup - it does not work if you do that - but in the page load when we load up the combo box, note the code setting cboCity.Multiple = True.
I have a dynamic GridView1 where header is different date. When a user click to a cell I need header text value to find the date details in my sql database.
GridView1 like:
LineName 05-28-21 05-29-21 05-30-21
L1 Style-1 Style-2 Style-3
L2 ab ad ak
If any idea please share. I am hanging on there from some days.
Hum, ok, we assume this markup:
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<asp:Button ID="cmdHeadClick" runat="server" Text="Headder fun"
ClientIDMode="Static" style="display:none" />
<asp:HiddenField ID="HeadClickValue" runat="server" ClientIDMode="Static" />
<script>
function GetHeaderText(hText) {
$('#HeadClickValue').val(hText)
$('#cmdHeadClick').click()
}
</script>
The code to fill this grid would be this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using cmdSQL As New SqlCommand("SELECT TOP 20 ID, HotelName, City from tblHotels",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
GridView1.DataSource = cmdSQL.ExecuteReader
GridView1.DataBind()
End Using
End Sub
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.Header Then
For Each MyCell As DataControlFieldCell In e.Row.Cells
MyCell.Attributes.Add("onclick", "GetHeaderText('" & MyCell.Text & "')")
Next
End If
End Sub
Protected Sub cmdHeadClick_Click(sender As Object, e As EventArgs) Handles cmdHeadClick.Click
Debug.Print("header text = " & HeadClickValue.Value)
End Sub
so the output looks like this:
An clicking on say hotel name in header outputs this:
Now I wired up a server side click event with above. But you can see that we do a simple data bind of the grid (data from sql server).
But, on RowDataBound event, we simple "inject" a click event for JavaScript code to run, and it passes the header cell text.
So, the JavaScript code now has the cell text value. At that point? Well, I shove the text into that hidden field, and THEN I click on my hidden button to run a server side click event that can now grab/get/use the text value of the header cell clicked.
I have an HTML table to display a set of records from database after user entered a patient code or during Page Load when the patient code is passed through Querystring. Each data row has a Delete link button which is created dynamically.
I'd like to have the table refreshed after deletion. However, whenever the link button is clicked, it will postback and all the records will be wiped out unless I reload the data. If I reload the data again after deletion, there will be 2 times data fetching and the table rows will be doubled.
The first 2 rows of the tables are defined on the ASPX for easier styling purpose. If I cleared the table when fetching the data, the first rows will be wiped out as well. I have another 8 tables on different pages created in the same manner, hence I'd rather find other solution rather than defining and styling the rows from code behind.
Any help will be greatly appreciated.
The codes I use are as follow:
ASPX
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblPatientCode" runat="server" Text="Patient Code : "></asp:Label>
<asp:TextBox ID="txtPatientCode" runat="server"></asp:TextBox>
<asp:Button ID="btnFind" runat="server" name="Date" Text="Find" Width="90" CssClass="ButtonNormal" />
<br /><br />
<table id="tblDoctorInformation" class="PatientDetailsTable" runat="server">
<tr><td colspan="2">DOCTOR INFORMATION</td></tr>
<tr>
<td>Doctor In Charge</td>
<td> </td>
</tr>
</table>
</div>
</form>
</body>
Code Behind:
Protected PM As New PatientManagement.Common
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GetPatient()
Else
If txtPatientCode.Text <> "" Then
GetPatient()
End If
End If
End Sub
Private Sub GetPatient()
Dim sPatientCode As String = ""
If IsPostBack Then
sPatientCode = Trim(txtPatientCode.Text)
Else
sPatientCode = Trim(Page.Request.QueryString("PatientCode"))
End If
If sPatientCode <> "" Then
Dim dr As SqlDataReader
dr = PM.ExecuteReader("SELECT LOGID,DOCTORNAME FROM PMV_DOCTORINCHARGE WHERE PATIENTCODE='" & sPatientCode & "'")
If dr.HasRows Then
Do While dr.Read
Dim tRow As New HtmlTableRow
Dim tCellDoctorName As New HtmlTableCell
Dim tCellModifyLink As New HtmlTableCell
Dim lb As New LinkButton
'Doctor Name
tCellDoctorName.InnerHtml = PM.GetString_TableCell(dr("DoctorName"))
tRow.Cells.Add(tCellDoctorName)
'Delete links
lb.Text = "Delete"
lb.Attributes.Add("AutoPostBack", False)
lb.CommandArgument = dr("LogID").ToString()
AddHandler lb.Click, AddressOf DeleteRecord
tCellModifyLink.Controls.Add(lb)
tCellModifyLink.Align = "Center"
tRow.Cells.Add(tCellModifyLink)
tblDoctorInformation.Rows.Add(tRow)
Loop
End If
End If
End Sub
Private Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
GetPatient()
End Sub
Protected Sub DeleteRecord(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lbNew As New LinkButton
Dim sResult As String = ""
Dim bResult As Boolean
lbNew = sender
bResult = PM.DeleteMultiRecord(lbNew.CommandArgument, lbNew.CommandName, Session.Item("UserID"), sResult)
If Not bResult Then
MsgBox(sResult, MsgBoxStyle.OkOnly, "Deletion was not successful")
Else
GetPatient()
End If
End Sub
Before Deleting a record, try to place a PatientID in Textbox and Delete the record, then Table will Display the records matching with the TextBox input.
The Problem is with PageLoad() method, if the TextBox is Empty And It is a Postback, then GetPatient() method will not be called. So try to modify the PageLoad() Method.
Better to remove IsPostBack condition in PageLoad().
I have searched around and it seems dynamic handler is best to be declared during PageInit. For my case, as the link button control needs to carry some values on the respective data row, it seems I can't avoid calling GetPatient to create controls.
To move on with the issue, I did a workaround by using Javascript. I created a hidLogID hidden field on ASPX page. I changed the link button to an <a> control and call a javascript function passing the dr("LogID"). The javascript function will assign the value to hidLogID and submit the page. PageLoad will call DeleteRecord()when hidLogID value is not blank. The value for hidLogID will be cleared on DeleteRecord().
Thank you for all the help!
I am learning asp.net and needed to have a CheckBoxList which items will be initially selected if the are in a CSV string from a database.
I have got it working although I just wondered if I have gone about it the best way as it seemed a little long winded?
Thanks for any help provided.
ASPX
<asp:CheckBoxList ID="rh_type" runat="server" CssClass="chkbox"
RepeatLayout="Flow" CausesValidation="True">
<asp:ListItem>House</asp:ListItem>
<asp:ListItem>Flat/Apartment</asp:ListItem>
<asp:ListItem>Bungalow</asp:ListItem>
<asp:ListItem>Any</asp:ListItem>
</asp:CheckBoxList>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
CODE
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim i As Integer
Dim str_rh_type As String = "House,Bungalow"
Dim split As String() = str_rh_type.Split(","c)
For Each s As String In split
'Response.Write(s & "<br />")
For i = 0 To rh_type.Items.Count - 1
If rh_type.Items(i).Text = s Then
rh_type.Items(i).Selected = True
End If
Next
Next s
End Sub
Thanks again
J.
Your code is functional but maybe some tweaking for maintainability would help. Also not sure you necessarily need nested loops to load your drop down items.
This should be just a reference point to make your own decisions on coding practices. Certainly what works for some doesn't work for others.
Here's how I'd code this...
ASP.NET Control:
<asp:CheckBoxList ID="CheckBoxListHomeType" runat="server"
CssClass="chkbox" RepeatLayout="Flow" CausesValidation="True" />
...
ID of CheckBoxListHomeType is easy to remember and intellisense will get me the rest of the way. (or another common approach would be cblHomeType as the ID). Getting intellisense to help on a name like rh_type may be just as easy but IDs that resemble what kind of control it is can really help when maintaining code
VB.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LoadHomeTypes()
End If
End Sub
Protected Sub LoadHomeTypes()
Dim houseTypes = "House,Bungalow,Flat/Apartment,Any"
For Each houseType As String In houseTypes.Split(",")
CheckBoxListHomeType.Items.Add(New ListItem(houseType))
Next
End Sub
Keeping the logic in a separate LoadHomeTypes function can make the code more readable.
Creating a new ListItem while iterating the list of homeTypes should remove the need to iterate over the CheckBoxList items, (if you need to clear out the existing ones you can add CheckBoxListHomeType.Items.Clear() to the top of the function)
the Not Page.IsPostBack check prevents the need for loading the drop down values every postback, unless you have need for them to change.
This is the good answers , try this
Dim ds As DataSet
ds = Insertstu.searchrec(txtsearch.Text)
txtnm.Text = ds.Tables(0).Rows(0)("stuname").ToString()
txtadd.Text = ds.Tables(0).Rows(0)("stuaddress").ToString()
txtph.Text = ds.Tables(0).Rows(0)("stuph").ToString()
rdobtnsex.Text = ds.Tables(0).Rows(0)("sex").ToString()
Dim arr As String()
Dim quali As String = ds.Tables(0).Rows(0)("qualified").ToString()
arr = quali.Split(",")
Dim i As Integer
For Each itm As String In arr
For i = 0 To chkqualify.Items.Count - 1
If chkqualify.Items(i).Text = itm Then
chkqualify.Items(i).Selected = True
End If
Next
Next
''chkqualify is checkboxlist id