I'm trying to loop trough a bunch of checkboxes that start with a specific id.
This bit of code seems normal, but it doesn't find anything :
Dim childc As Control
Dim c as Control
For Each c In Me.Page.Controls
For Each childc In c.Controls
If TypeOf childc Is CheckBox Then
If CType(childc, CheckBox).Checked Then
If childc.ID.StartsWith("ctl00_indexBody_ID_ACTIVITE_") Then
i = i + 1
Alerte(CType(childc, CheckBox).Text)
strSQL = "INSERT INTO A_ACTIVITES VALUES("
strSQL += Me.ID_PRESTATAIRE.Text + "," + childc.ID + ","
strSQL += ")"
oWebConnection.Execute(strSQL)
End If
End If
End If
Next
Next
it breacks in the second line saying that
it's impossible to cast an objet of type 'ASP.masterpage_master' to 'System.Web.UI.WebControls.CheckBox
Thank's for your help
Declare c and childc as Control, not CheckBox.
The declaration of c is not visible but I think you made the same mistake.
I found a solution
Protected Sub GererActivite(ByVal oControls As ControlCollection)
Dim oControl As Control
For Each oControl In oControls
If oControl.HasControls Then
GererActivite(oControl.Controls) ' récursivité
ElseIf TypeOf oControl Is CheckBox Then
If CType(oControl, CheckBox).Checked Then
If CType(oControl, CheckBox).Text.StartsWith("ctl00_indexBody_ID_ACTIVITE_") Then
End If
End If
End If
Next
End Sub
This function runs trough a control Collection, and if a control of this collection has controls, i run trough these controls with the same function untill it finds a control that hasn't controls and if it is a checkbox, i can check on it as i wish.
It worked like a charm.
In fact it's my bosses idea i'm just bragging around, lol.
Hope it will help others.
Related
I am creating a query for a SqlDataSource in ASP.NET from code behind.
My code is as following:
Dim SqlDataSource1 As New SqlDataSource()
Dim SQL As String
' If Not IsPostBack Then
SqlDataSource1.ID = "sqlexpsearch"
Me.Page.Controls.Add(SqlDataSource1)
Dim connectionString As String
Dim connection As SqlConnection
connectionString = ConfigurationManager.ConnectionStrings("exam2ndconnection").ToString
connection = New SqlConnection(connectionString)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("exam2ndconnection").ConnectionString
If opname.Checked = True Then
SQL = "select SRNO,tr_date as Date ,MailMethod,SpeedId,Content,ExYear,Exroll as No,NAME,Address from dispatch where name = '%'+ #srname +'%' OR ADDRESS ='%'+ #srname +'%' order by TR_DAte DESC,NAME "
SqlDataSource1.SelectParameters.Add("#srname", UCase(txtitem.Text))
SqlDataSource1.SelectCommand = SQL
End If
If opchno.Checked Then
SqlDataSource1.SelectCommand = "select SRNO,tr_date as Date ,MailMethod,SpeedId,Content,ExYear,Exroll as No,NAME,Address from dispatch where rtrim(exroll) ='" & txtitem.Text & "' order by tr_Date,exroll desc"
End If
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
I get this error:
Must declare the scalar variable "#srname".
on the line of code:
Gridview1.DataBind()
Please help to resolve this problem.
I would avoid trying to inject (add) a sql datasource into a page. (they don't persist anyway - you would have to re-inject each time).
However, DO keep in mind that any data aware control ALWAYS will automatic persist for you anyway.
The above information is thus great, since then you don't even have to bother with the sql data source. This is especially so in your example - you want to fill out a dropdown list, a grid view - whatever. In those cases? Just shove into that control a datatable - and your off to the races.
As noted, a lot of us use + prefer using code in place of a data source on the page - I find them rather messy and a pain to work with anyway.
In fact, what I will often do is say drop in a listbox, or even a grid view. I then use the wizard to create new data source - lay out the grid real nice and fast. I then go into the markup, remove the data source conrol that appears in the page.
Also, don't forget to remove the DataSourceID = from the Gridview markup (or whatever control you using).
This lets me still use the wizards to create the gridview, listview etc. but then I delete that extra junk, and wind up with a nice clean page without all that extra stuff in the page - (which is a pain to control from code anyway).
So, say for your example?
Try coding it this way:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using conn As New SqlConnection(ConnectionStrings("exam2ndconnection").ConnectionString)
Dim strSQL As String = ""
strSQL = "SELECT SRNO, tr_date as Date, MailMethod, SpeedId, Content, ExYear, Exroll as No, " &
"[Name], Address FROM dispatch "
Dim strWhere As String = ""
Using cmdSQL As New SqlCommand(strSQL, conn)
If opName.Checked Then
strWhere = "([Name] Like '%'+ #srname +'%' OR ADDRESS = '%'+ #srname +'%') "
cmdSQL.Parameters.Add("#srname", SqlDbType.NVarChar).Value = txtitem.Text
End If
If opchno.Checked Then
If strWhere <> "" Then strWhere &= " AND "
strWhere &= "(Rtrim(exroll) = #exroll)"
cmdSQL.Parameters.Add("#exroll", SqlDbType.NVarChar).Value = txtitem.Text
End If
If strWhere <> "" Then
cmdSQL.CommandText &= " WHERE " & strWhere
End If
' add our sorting
cmdSQL.CommandText &= " ORDER BY tr_Date, exroll DESC"
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rstData
GridView1.DataBind()
End Using
End Using
End Sub
A few things:
YES DO NOT forget to put the load of such data inside of the PostBack = false.
Load the results into a datatable (there are several reasons for this, but one BIG reason is that the row data bound event will have full use of that data row - including the WHOLE data row - even columns that are NOT part of the gridview.
note careful in above.
If you don't check "opname", then the criteria is not added.
if you don't check "opchno", then the criteria is not added.
if you check either one - the criteria for that option is added
so, if you check none, no criteria
if you check both, then you get both filters. So this allows you add even more options, and they are ALL optional - and we "clumative" can build up selection criteria this way.
Trying to use checkbox lists in (calendar booking system). The checkbox should be disabled and red if there are any data in the database against the date and hour. This all work perfectly here is the code. Using vb.net
OK i found a way how to clear the checkboxes
Dim i As Integer
Dim chboxItem As ListItem
For Each chboxItem In CheckBoxListMon.Items
i += 1
If (i Mod 1 = 0) Then
chboxItem.Enabled = True
End If
Next
Protected Sub Page_LoadComplete(sender As Object, e As EventArgs) Handles Me.LoadComplete
Try
strQuery = "SELECT BookingDate, checkBoxItem, BookRegUserID,Booked FROM bookings INNER JOIN checkboxitems where checkBoxItem = BookingTime"
MySQLCmd = New MySqlCommand(strQuery, dbCon)
dbCon.Open()
DR = MySQLCmd.ExecuteReader
While DR.Read
bookDate = DR.Item("BookingDate")
bookTime = DR.Item("checkBoxItem")
bookRegID = DR.Item("BookRegUserID")
booked = DR.Item("Booked")
Dim test As String = bookTime.ToString()
Select Case True
Case bookDate = lblMonday.Text And CheckBoxListMon.Items.FindByValue(test) IsNot Nothing
CheckBoxListMon.Items.FindByValue(bookTime).Enabled = False
CheckBoxListMon.Items.FindByValue(bookTime).Attributes.Add("Style", "color: red;")
End Select
End While
DR.Close()
dbCon.Close()
Catch ex As Exception
End Try
End Sub
When the page load it would not change the ones from the database. But when i reload the page it will actually work perfect.
Where can i put the check just to be sure that they are already in the memory.
Any help will be much appreciated. Thanks all.
Petr
You need to refresh the data when another week is selected because you are using the same controls for each week. You should be able to do this in whatever control you are using to toggle through the weeks.
Page_LoadComplete can only be expedted to fire each time a page has completed loading, that is why your controls work when going to another page and back.
Note: This code actually codes from a tutorial book I'm reading at the moment, so you can imagine this is frustrating me greatly! I'm building a basic shopping cart, using VB.NET 4, Visual Studio 2010 and MS SQL Server R2 2008. The code below is supposed to remove items from the cart, by reading a session variable, editing it to remove the appropriate ProductID and return the amending string to the session variable. It is then supposed to rebind the data to the gridview (gvCart) to refresh the data...but it seems here there is an error.
Every time I build the site in Visual Studio, it validates fine. But every time I run the site, and attempt to use the remove button it gives me the error:
Incorrect syntax near ')'.
with the IDE pointing me toward the final parenthesis.
I have been pulling my hair out at this for a good 4 hours now, any advice appreciated!
Protected Sub gvCart_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvCart.SelectedIndexChanged
'This method is hooked to the Remove button & is removing items from the cart
Dim strProductId As String = gvCart.SelectedRow.Cells(1).Text
If Session("Cart") IsNot Nothing Then
'Remove selected ProductID from Session string and retrieve session string
Dim strCart As String = Session("Cart").ToString()
Dim arIDs As String() = strCart.Split(",")
'Iterate through ID's in the 'Cart' array and rebuild the string leaving out the selected ID
strCart = String.Empty
For Each str As String In arIDs
'use Trim to remove leading and trailing spaces
If str.Trim() <> strProductId.Trim() Then
strCart += str + ", "
End If
Next
'Remove trailing space and comma
If strCart.Length > 1 Then
strCart = strCart.Trim()
strCart = strCart.Substring(0, strCart.Length - 1)
End If
'Put back into session var
Session("Cart") = strCart
'Rebind gvCart, which forces the sqldatasource to requery
gvCart.DataBind()
End If
End Sub
[EDIT]
I am also including the code that runs for the event sqlCart_Selecting for completion sake:
Protected Sub sqlCart_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles sqlCart.Selecting
Trace.Warn("sqlCart_Selecting") 'aids debugging
Dim strCart As String = String.Empty
If Session("Cart") IsNot Nothing Then
strCart = Session("Cart").ToString
e.Command.CommandText &= " WHERE product.ProductID IN (" + strCart + ") AND culture.CultureID = 'en'"
Else
e.Cancel = True
End If
End Sub
[EDIT]
Also including the SQL query used by the gridview 'gvCart' and the code for displaying the carts contents on another page
<asp:SqlDataSource ID="sqlCart" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" SelectCommand="SELECT product.ProductID, product.Name, product.ProductNumber, product.Color, subcat.Name AS SubcategoryName, cat.Name AS CategoryName, description.Description FROM Production.Product product JOIN Production.ProductSubcategory subcat ON product.ProductSubcategoryID = subcat.ProductSubcategoryID JOIN Production.ProductCategory cat ON subcat.ProductCategoryID = cat.ProductCategoryID JOIN Production.ProductModel model on product.ProductModelID = model.ProductModelID JOIN Production.ProductModelProductDescriptionCulture culture ON model.ProductModelID = culture.ProductModelID JOIN Production.ProductDescription description ON culture.ProductDescriptionID = description.ProductDescriptionID"></asp:SqlDataSource>
Protected Sub btnAddToCart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddToCart.Click
'The contents of the cart will be saved in a Session object as a string of coma-delimited values of ProductID's
Dim strCart As String = String.Empty
Dim strProductID As String = gvProducts.SelectedDataKey.Value.ToString()
If Session("Cart") Is Nothing Then
strCart = strProductID
Else
strCart = Session("Cart").ToString() + ", " + strProductID
End If
Session("Cart") = strCart
lblCart.Text = strCart
End Sub
I will take a shot here, since you are not showing us everything (the SQL query for instance).
But it feels like the SQL query is using IN clause. And it appears to be failing when the cart goes empty.
Since Session("Cart") contains the comma separated values of the product IDs, an empty list would make the following SQL query fail:
select id, name
from products
where id in ()
with the message:
Incorrect syntax near ')'.
You have to show us the portion of code that's reloading the query from Session("Cart"). The query should be reassembled.
But there's one trick you can use! If your product ids are numeric and always greater than zero, change this line:
strCart = String.Empty
to this:
strCart = '-1, '
Update
I will really teach how to fish on this one. :) the problem is here:
Dim strCart As String = String.Empty
If Session("Cart") IsNot Nothing Then
strCart = Session("Cart").ToString
e.Command.CommandText &= " WHERE product.ProductID IN (" + strCart + ") AND culture.CultureID = 'en'"
Else
e.Cancel = True
End If
When cart is empty, Session("Cart") is not Nothing but it's an empty string (provided that you removed the -1 workaround). If Session("Cart") is an empty string the where clause should be " WHERE culture.CultureID = 'en'" only, no mention to product ids. God speed!
For Each Control In Page.Header.Controls
How can I do something as above, at the moment getting the error
"Control is a Type and Cannot be used as an expression"
The Complete Code is as follows
Try
' I only do this on my production servers, so I declare those here.'
If Request.ServerVariables("server_name") = "www.myproductionurl.com" Then
' Allow scripts and css to logged in CMS users'
Dim checkLogin As New Controls.Login
If checkLogin.IsLoggedIn <> True Then
For Each Control In Page.Header.Controls
If Control.GetType.Name = "EktronJsControl" Or Control.GetType.Name = "EktronCssControl" Or Control.GetType.Name = "EktronModalCss" Then
Page.Header.Controls.Remove(Control)
Else
' Removes the extra bubble inline style stuff that wasn't put in a CSS.''
Dim litControl As LiteralControl = Control
If litControl.Text = Nothing Then
litControl.Text = ""
End If
' Removing blank.css file'
Dim htmlLink As HtmlLink = Control
If htmlLink.Href = "/css/blank.css" Then
Page.Header.Controls.Remove(Control)
End If
End If
Next
End If
End If
Catch ex As Exception
End Try`
Sadly... VB.NET compiler says you cannot use "Control" as variable name because "Control" is a type too!!
Just use another identifier :)
Since "Control" is a Class, it can not be used as a variable name. Either change it to another variable name, or surround it in square brackets ... [Control]
The brackets will tell the compiler to treat it as a variable rather than class name.
Change Control variable name to something else.
For Each ctrl In Page.Header.Controls
or
For Each ctrl As Control In Page.Header.Controls
The error message says it all: The word Control is a Type so you need to use something else.
UPDATE in response to comments.
You cannot remove the controls while your using a For Each loop to iterate through them.
Consider changing the code to something like:
For i as Integer = Page.Header.Controls.Length -1 to 0 Step -1
Dim ctrl As Control = CType(Page.Header.Control(i),Control)
If ctrl.GetType.Name = "EktronJsControl" Or ctrl.GetType.Name = "EktronCssControl" Or ctrl.GetType.Name = "EktronModalCss" Then
Page.Header.Controls.Remove(ctrl)
Else
Dim litControl As LiteralControl = ctrl
If litControl.Text = Nothing Then
litControl.Text = ""
End If
End If
Next
Or you could keep a reference to the controls to be removed and remove them after the loop.
Dim removables = New List(Of Control)
For Each ctrl In Page.Header.Controls
If ctrl.GetType.Name = "EktronJsControl" Or ctrl.GetType.Name = "EktronCssControl" Or ctrl.GetType.Name = "EktronModalCss" Then
removables.Add(ctrl)
Else
Dim litControl As LiteralControl = ctrl
If litControl.Text = Nothing Then
litControl.Text = ""
End If
End If
Next
For Each c In removables
Page.Header.Controls.Remove(c)
Next
Also, its unlikely that ctrl will be able to be converted into a LiteralControl and an HtmlLink so you need to add extra checks to determine which it is.
First, I'd like to say I'm sorry that you're working with Ektron :(. I feel your pain.
The syntax of your loop is wrong, you need to specify a variable for your loop. The syntax is:
For Each [variable] As [type] In [collection]
So, change your loop to:
For Each ctrl as Control In Page.Header.Controls
And change all the references for the variable Control in your code to be ctrl.
For more info, see the MSDN article on For Each.
Make a list of Controls to remove after you have enumerated then remove them.
Dim controlsToRemove As New List(Of Control)
For Each ctrl In Page.Header.Controls
If ctrl.GetType.Name = "EktronJsControl" Or ctrl.GetType.Name = "EktronCssControl" Or ctrl.GetType.Name = "EktronModalCss" Then
Page.Header.Controls.Remove(ctrl)
Else
Dim litControl As LiteralControl = ctrl
If litControl.Text = Nothing Then
litControl.Text = ""
End If
Dim htmlLink As HtmlLink = ctrl
If htmlLink.Href = "/css/blank.css" Then
'Page.Header.Controls.Remove(ctrl)
controlsToRemove.Add(ctrl)
End If
End If
Next
For Each ctrlToRemove In controlsToRemove
Page.Header.Controls.Remove(ctrlToRemove )
Next
I have a table that I'm creating in code behind with the final column containing a HTML checkbox with runat="server".
The code I'm using to do this is:
Do While reader.HasRows
Do While reader.Read
Dim tNewRow As New HtmlTableRow
Dim cellSKU, cellDESCR, cellDept1, cellDeptGrp1, cellDeptRng1, cellStand, cellBoard, cellSelect As New HtmlTableCell
cellSKU.InnerHtml = "<a href='edit.aspx?edit=" & reader("SKUN") & "'>" & reader("SKUN") & "</a>"
cellDESCR.InnerText = reader("DESCR")
cellDept1.InnerText = reader("DPT1")
cellDeptGrp1.InnerText = reader("GRP1")
cellDeptRng1.InnerText = reader("RNG1")
cellBoard.InnerText = reader("BOARD")
cellStand.InnerText = reader("STAND")
cellSelect.InnerHtml = "<input type='checkbox' id='selectedSKU' value='" & reader("SKUN") & "' runat='server' />"
tNewRow.Cells.Add(cellSKU)
tNewRow.Cells.Add(cellDESCR)
tNewRow.Cells.Add(cellDept1)
tNewRow.Cells.Add(cellDeptGrp1)
tNewRow.Cells.Add(cellDeptRng1)
tNewRow.Cells.Add(cellStand)
tNewRow.Cells.Add(cellBoard)
tNewRow.Cells.Add(cellSelect)
tNewRow.Style.Add("border", "solid 1px #cccccc")
skusTable.Rows.Add(tNewRow)
Loop
reader.NextResult()
Loop
But I want to use the checkbox in another sub such as:
Protected Sub editSkus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles editSkus.Click
End Sub
Though I can't use selectedSKU.whatever as the checkbox doesn't exist on the page until the other section of code is run.
Is there a way I can get around this or another way of doing things?
Thanks in advance for any help.
It's nasty, but here goes...
Dim skusTable As New HtmlTable
Dim i As Integer
Do While reader.HasRows
Do While reader.Read
i = i + 1
Dim tNewRow As New HtmlTableRow
tNewRow.ID = "MyRow" & i
Dim cellSKU, cellDESCR, cellDept1, cellDeptGrp1, cellDeptRng1, cellStand, cellBoard, cellSelect As New HtmlTableCell
cellSKU.InnerHtml = "<a href='edit.aspx?edit=" & reader("SKUN") & "'>" & reader("SKUN") & "</a>"
cellDESCR.InnerText = reader("DESCR")
cellDept1.InnerText = reader("DPT1")
cellDeptGrp1.InnerText = reader("GRP1")
cellDeptRng1.InnerText = reader("RNG1")
cellBoard.InnerText = reader("BOARD")
cellStand.InnerText = reader("STAND")
'Create the checkbox as a webcontrol and add it to the table cell
Dim checkBox As New HtmlControls.HtmlInputCheckBox
checkBox.Value = reader("SKUN")
checkBox.ID = "selectedSKU"
cellSelect.ID = "SelectedCell"
cellSelect.Controls.Add(New WebControls.CheckBox)
tNewRow.Cells.Add(cellSKU)
tNewRow.Cells.Add(cellDESCR)
tNewRow.Cells.Add(cellDept1)
tNewRow.Cells.Add(cellDeptGrp1)
tNewRow.Cells.Add(cellDeptRng1)
tNewRow.Cells.Add(cellStand)
tNewRow.Cells.Add(cellBoard)
tNewRow.Cells.Add(cellSelect)
tNewRow.Style.Add("border", "solid 1px #cccccc")
skusTable.Rows.Add(tNewRow)
Loop
reader.NextResult()
Loop
Now all you need do is use FindControls to get to the element...
Dim myRow As HtmlControls.HtmlTableRow = skusTable.FindControl("MyRow" & i)
'Probably be good to check the object exists first....
If Not myRow Is Nothing Then
Dim myCell As HtmlControls.HtmlTableCell = myRow.FindControl("SelectedCell")
If Not myCell Is Nothing Then
Dim myCheckbox As HtmlControls.HtmlInputCheckBox = myCell.FindControl("selectedSKU")
If Not myCheckbox Is Nothing Then
'Got it! now is it selected?
Return myCheckbox.Checked
End If
End If
End If
The runat="Server" attribute is parsed by the ASP.NET process and indicates that it should create some kind of control object. At the point your code is running this parsing has already been done. ASP.NET does not parse content added to the InnerHTML property to look for additional runat attributes or any other ASP.NET specific markup, InnerHTML is expected to be strictly standard HTML that is to be sent to the server.
You could create an instance of the CheckBox ASP.NET control and add it to the cellSelect controls collection, which is the equivalent to runat="Server". However that doesn't really help because you want to bind an event to this control but on post back this control will no longer exist.
Is there a reason you are not using DataGrid to acheive this UI?