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
Related
<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
I have a GridView. I want the content of the cells, the actual detail data, to be html-encoded. But I want to keep the raw HTML in the heading.
That is, the heading in this case is the name of a language and the ISO code, for example "English (EN)". I want the name and code on separate lines, so I'm specifying the heading as "English<br/>(EN)".
But for the content, I want to see any HTML. If it says "<p>foobar</p>" I want the p-tags to display.
If I say "htmlencode=false", then the heading doesn't get encoded, but neither does the data.
Is there any way to say, html-encode the data, but not the heading?
If it matters, I'm building the columns in code rather than with tags in the ASP file, depending on which languages I find in my data. So here's how I'm creating the column:
For Each row As DataRow In ds.Tables(0).Rows
Dim iso2 = row("language")
Dim name = row("name")
... other code ...
Dim head = String.Format("{0}<br/>({1})", name, iso2)
gvSnippets.Columns.Add(New BoundField With {.HeaderText = head, .DataField = iso2, .HtmlEncode = False})
... other code ...
End For
(My first draft did not set HtmlEncode.)
Curious observation: In my first couple of test runs, the data did not include any HTML or entities, and the HTML in the heading was NOT encoded, I got the line break and not "<br/>". Then I did a test where there were entities in the data and the entities got html-encoded ... and so did the header. So like, ASP is apparently saying that by default, if the data has no HTML but the heading does, then don't HTML-encode the heading. But if the data has HTML, then HTML-encode both the data and the heading. So like, it's deciding dynamically whether to html-encode the heading or not.
In reply to #fnostro, here's the markup for the GridView:
<asp:GridView ID="gvSnippets" runat="server" AutoGenerateColumns="False" SkinID="skin3" EmptyDataText="No records found" Visible="false">
</asp:GridView>
There is no <Columns> markup. I build the columns completely in code. I haven't tested if the same behavior occurs in what I assume is the more normal case where you specify columns with markup.
Add these lines of code to the beginning of your loop
row("language") = HttpUtility.HtmlEncode(dr("language"))
row("name") = HttpUtility.HtmlEncode(dr("name"))
Based on my reading of the information provided in your post I have the following suggestions:
You should isolate data formatting from raw data.
Your DataTable is the data source for the GridView. The DataTable should contain only raw data, completely unformatted and unadulterated.
The DataTable gets bound to the Gridview by setting the GridView DataSource and making a call to DataBind(). Calling gvSnippets.Databind() will trigger all the databinding events associated with Gridviews which will allow you to:
Manage simple formatting and binding in the GridView Columns in the aspx markup.
Handle more complicated formatting in the code behind for specific GridView events like the RowDataBound event.
Regarding the GridView Header: HeaderText appears once at the top of the Gridview and is stored internally in GridView.HeaderRow, not on a per row basis even though every bound field has a HeaderText property.
Example excerpt gvSnippets Markup per your update:
<asp:GridView ID="gvSnippets" runat="server"
AutoGenerateColumns="False" SkinID="skin3"
EmptyDataText="No records found" Visible="false">
</asp:GridView>
Then you can do things like this in the Code Behind:
Public Class __JunkWebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Fill Dataset first, then:
gvSnippets.DataSource = ds.Tables(0)
' Add Columns...
gvSnippets.Columns.Add(...)
gvSnippets.Columns.Add(...)
gvSnippets.Columns.Add(...)
. . .
' This will trigger data binding events
gvSnippets.DataBind();
End Sub
Private Property HeaderTextLanguage As String
Private Property HeaderTextLanguageIso As String
Dim NeedHeaderText As Boolean = False
Private Sub gvSnippets_DataBinding(sender As Object, e As EventArgs) Handles gvSnippets.DataBinding
NeedHeaderText = True
End Sub
Private Sub gvSnippets_DataBound(sender As Object, e As EventArgs) Handles gvSnippets.DataBound
Dim this As GridView = sender
this.Columns(0).HeaderText = String.Format("{0}<br>({1})", HeaderTextLanguage, HeaderTextLanguageIso)
End Sub
Private Sub gvSnippets_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gvSnippets.RowDataBound
Dim this As GridView = sender
Dim drv As DataRowView = e.Row.DataItem
If e.Row.RowType = DataControlRowType.DataRow Then
If NeedHeaderText Then
HeaderTextLanguage = drv("language")
HeaderTextLanguageIso = drv("iso")
NeedHeaderText = False
End If
e.Row.Cells(0).Text = Server.HtmlEncode(drv("Somefieldnameofyours"))
End If
End Sub
End Class
Addendum Dealing with Dynamic cells
For a GridView defined as:
<asp:GridView ID="gvSnippets" runat="server"
AutoGenerateColumns="False">
</asp:GridView>
I don't know how you're populating your ds but I'm using a SqlDataSource to fill a table in the Code Behind. Note there is no GridView DataSourceID above:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="select top 10 user_id, user_name, user_logon, 'English' as language, 'en' as iso from tbl_users"
ConnectionString='<%$ ConnectionStrings:MyConnectionString %>'>
</asp:SqlDataSource>
Then in the Code Behind I can do this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GetDataSetAndPopulate(gvSnippets)
End Sub
Private Sub GetDataSetAndPopulate(gv As GridView)
Dim view As DataView = SqlDataSource1.Select(DataSourceSelectArguments.Empty)
Dim table As DataTable = view.ToTable()
Dim ds As DataSet = New DataSet()
ds.Tables.Add(table)
For Each dc As DataColumn In ds.Tables(0).Columns
Dim field As New BoundField
field.DataField = dc.ColumnName
field.HeaderText = dc.ColumnName
gv.Columns.Add(field)
Next
gv.DataSource = ds
gv.DataBind()
End Sub
And now the Gridview is populated dynamically and you can still handle all the formatting during the DataBinding events as needed.
Here's a solution I came up with that works in my particular case.
I am building the data to populate the GridView in code. I create a DataTable, add columns to it, and then populate those columns. Like:
dim dslang=GetListOfLanguages()
dim dtgv=new DataTable()
for each row as DataRow in dslang.tables(0).rows
dim language_name=row("name")
dim language_code=row("code")
dtgv.columns.add(String.format("{0}<br/>({1})",language_name, language_code)
end for
... bunch of other stuff ...
... inside a loop that reads the data ...
dim outrow=dtgv.NewRow()
... get data for a specific language ...
outrow(language_code)=text
... later ...
my_gridview.datasource=dtgv
my_gridview.databind()
So my solution:
When creating the GridView, set HtmlEncode=false. This makes the header display correctly.
When populating the data, say
outrow(language_code)=HttpUtility.HtmlEncode(text)
So I add the data to the datatable that will ultimately be used as the datasource for the gridview already encoded, so I don't need to rely on the Gridview encoding it.
I consider this a mediocre solution, as it only works because I am populating GridView from a DataTable that I build with code. If I was populating the GridView directly from a DataSource specified in markup, or from a DataSet created by a database query, there'd be no convenient place to put the HttpUtility.HtmlEncode call.
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'm trying to get a drop down list control to work in FormView. I need to have the list be a filtered view of a certain table and still be bound to a field in the data I'm editing. I've tried setting the item data programatically, ant that works but then the data binding
doesn't work, It tries to insert null into the database.
This is the code I've tried. I've also tried doing the same thing in several other events, it still tries to insert null into the database.
<asp:DropDownList ID="lstManagers" runat="server"
OnDataBound ="ManagersLoad"
SelectedValue='<%# Bind("UserName") %>' Width="100%"
DataSourceID="TimeOff" DataTextField="UserName" DataValueField="UserName">
</asp:DropDownList>
Protected Sub ManagersLoad(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lst As DropDownList = FormView1.FindControl("lstManagers")
'get list of managers
Using ef As New TimeOffData.TimeOffEntities
For Each item As ListItem In lst.Items
Dim li As ListItem = item
item.Text = (From x In ef.TimeOffUsers Where x.UserName = li.Value Select x.FirstName & " " & x.LastName).FirstOrDefault
Next
End Using
End Sub
I took all the data binding stuff of the control and just decide it would be easier to do it manually. I've changed the code to this,
Protected Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInserting
Dim lst As DropDownList = FormView1.FindControl("lstManagers")
e.Values.Item("ManagerName") = lst.SelectedValue
End Sub
Protected Sub ManagersLoad(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lst As DropDownList = FormView1.FindControl("lstManagers")
'get list of managers
Using ef As New TimeOffData.TimeOffEntities
Dim mng = From x In ef.TimeOffUsers Where x.IsManager = True
For Each item In mng
lst.Items.Add(New ListItem(item.FirstName & " " & item.LastName, item.UserName))
Next
End Using
End Sub
I'm working on an ASP.NET website where I am using an asp:repeater with paging done through a VB.NET code-behind file. I'm having trouble with the database connection though. As far as I can tell, the paging is working, but I can't get the data to be certain.
The database is a Microsoft Access database. The function that should be accessing the database is:
Dim pagedData As New PagedDataSource
Sub Page_Load(ByVal obj As Object, ByVal e As EventArgs)
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;Data Source=App_Data/ArtDatabase.mdb")
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT ArtID, FileLocation, Title, UserName, ArtDate FROM Art ORDER BY Art.ArtDate DESC", strConnect)
objOleDBAdapter.Fill(DS, "Art")
Return DS.Tables("Art").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 2
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (Not pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()
End Sub
The ASP.NET is:
<asp:Repeater ID="ArtRepeater" runat="server">
<HeaderTemplate>
<h2>Items in Selected Category:</h2>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" ID="HyperLink"
NavigateUrl='<%# Eval("ArtID", "ArtPiece.aspx?ArtID={0}") %>'>
<img src="<%# Eval("FileLocation") %>"
alt="<%# DataBinder.Eval(Container.DataItem, "Title") %>t"/> <br />
<%# DataBinder.Eval(Container.DataItem, "Title") %>
</asp:HyperLink>
</li>
</ItemTemplate>
</asp:Repeater>
If you need help with Connection Strings, this site is the ultimate resource!
http://www.connectionstrings.com/
Are you creating the connection string by hand? If so...don't do that! Use the Server Explorer to create your connection. Then highlight it and go to the Properties window, and you'll see the connection string it uses.
Also, using the Server Explorer will let you browse through your tables and even open them up to see your data. At least that'll tell you for certain whether your data is accessible.
Problem solved! Pretty much banging my head against the wall now considering how simple it was. It was the Page_Load, I changed it to the following:
Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
doPaging()
End Sub
And voila, it works!
Also, for the connection string, I ended up using:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\ArtDatabase.mdb
Which works great.
Thanks for your help and input guys!