I have created a Master page. And I have created a default page named default.aspx The defult aspx file has all of the standard content and ID's. In the ID I made a div tag to hold content for the dynamic page.
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="Default.aspx.vb" Inherits="P03_S02.Link1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="DynPage" runat="server"></div>
</asp:Content>
This is all good. So by using SQL server express that comes with Visual Studio 2012 I created a table with data in it. The entitys in the table is
ProductID
Name
Price
Quantity
Now in the default.aspx.vb page I completed the following code.
Imports System.Data
Imports System.Data.SqlClient
Public Class Catelog
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim Connection As SqlConnection
Dim Command As SqlCommand
Dim Reader As SqlDataReader
Connection = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Products.mdf;Integrated Security=True")
Dim CommandString As String
CommandString = "SELECT * FROM Product"
Command = New SqlCommand(CommandString)
Command.CommandType = CommandType.Text
Command.Connection = Connection
Command.Connection.Open()
Command.ExecuteNonQuery()
Reader = Command.ExecuteReader(CommandBehavior.CloseConnection)
Dim ProductList As String
If Reader.HasRows Then
ProductList &= "<table width=""100%"">"
ProductList &= " <tr bgcolor=""#00CCFF"">"
ProductList &= "<td><b>ID</b></td>"
ProductList &= "<td><b>Product</b></td>"
ProductList &= "<td><b>Price</b></td>"
ProductList &= "<td><b>Quantity</b></td>"
ProductList &= "</tr>"
While Reader.Read
Dim newProduct As String
ProductList &= "<tr>"
ProductList &= "<td>" & Reader("ProductID") & "</td>" & _
"<td>" & "" & Reader("Name") & "" & "</td>" & _
"<td>" & Reader("Price") & "</td>" & _
"<td>" & Reader("Quantity") & "</td>"
ProductList &= "</tr>"
End While
ProductList &= "</table>"
End If
Catelog.InnerHtml = ProductList
Command.Connection.Close()
' Command.Dispose()
Connection.Dispose()
ProductCatelog.InnerHtml = ProductList
End If
End Sub
End Class
As you can see the table will display all data form the table. In the while loop I make each name in the table hyperlinks to another apsx file named Link1.
I used the same code as above but changed a few things in Link1.aspx.vb
Added:
Dim ProductID As String
ProductID = Request.QueryString("ProdID").ToString()'problem possible here
Changed the Display of data:
Dim ProductList As String
If Reader.HasRows Then
ProductList &= "<table width=""100%"">"
ProductList &= " <tr bgcolor=""#00CCFF"">"
ProductList &= "<td><b>Product</b></td>"
ProductList &= "<td><b>Price</b></td>"
ProductList &= "<td><b>Quantity</b></td>"
ProductList &= "</tr>"
While Reader.Read
Dim newProduct As String
ProductList &= "<tr>"
ProductList &= "<td>" & Reader("Name") & "</td>" & _
"<td>" & Reader("Price") & "</td>" & _
"<td>" & Reader("Quantity") & "</td>"
ProductList &= "</tr>"
End While
ProductList &= "</table>"
End If
Used the following to display only one record:
Dim CommandString As String
CommandString = "SELECT * FROM Product where ProductID =" & ProductID
My goal is if you click on a name it will link it to Link1.aspx and display only information about that name (Info in table). That does not happen because the program crashes. I have used all my basic debugging knowledge.
In default.aspx.vb you have :
"<td>" & "" & Reader("Name") & "" & "</td>" & _
passing name as ProdID
for ProdID you are passing Name and in link1.aspx.vb you are querying like:
Dim ProductID As String
ProductID = Request.QueryString("ProdID").ToString()'problem possible here
and later:
Dim CommandString As String
CommandString = "SELECT * FROM Product where ProductID =" & ProductID
expecting ProdID, not Name.
So, in default.aspx.vb you should change the line to:
<td>" & "<a href=""Link1.aspx?ProdID=""" & Reader("ProdID").ToString() & ">" &
Firstly, look up SqlParameters, because you've just opened your code up to SQL injection by passing parameters in the QueryString.
To address your question, I think the problem lies with this line:
"<td>" & "" & Reader("Name") & "" & "</td>" & _
You are closing your double-quote too soon and the productId isn't being put inside the href.
I'd rewrite it like this:
"<td>" & "" & Reader("Name") & "" & "</td>" & _
Subtle difference, but it should make it work.
Finally, always do a null/empty string check on the QueryString before you call .ToString(). Compare your QueryString entry using String.IsNullOrWhiteSpace(), and then only continue processing when String.IsNullOrWhiteSpace() returns false.
Related
i'm gonna straight forward. i have these lines of codes. basically it's about update data based on user input. but first, the textbox will retrieve data from database, and then the user will be free to change the value/text of the textbox and when the user click a button, the system will store the new value to database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim check As String = Session("user_id")
Dim SqlSelect As String = "SELECT * FROM Worker Where user_id='" & check & "' "
Dim con As dbConn = New dbConn()
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
Dim reader As OleDbDataReader
Try
con.open()
reader = cmd.ExecuteReader()
reader.Read()
WorkerID_.Text = reader("WorkerID").ToString()
WorkerName.Text = reader("WorkerName").ToString()
DoB.Text = reader("DoB").ToString()
Address.Text = reader("Address").ToString()
Phone.Text = reader("Phone").ToString()
Email.Text = reader("Email").ToString()
Company.Text = reader("CompanyName").ToString()
PassNum.Text = reader("PassportNum").ToString()
PassExp.Text = reader("PassportExp").ToString()
VisaExp.Text = reader("VisaExp").ToString()
Finally
reader.Close()
con.close()
End Try
End Sub
Protected Sub Update_Click(sender As Object, e As EventArgs)
Dim con As dbConn = New dbConn()
Dim SqlUpdate As String
SqlUpdate = "UPDATE Worker SET "
SqlUpdate &= "WorkerID = '" & WorkerID_.Text & "', "
SqlUpdate &= "WorkerName = '" & WorkerName.Text & "', "
SqlUpdate &= "Address = '" & Address.Text & "', "
SqlUpdate &= "Email = '" & Email.Text & "', "
SqlUpdate &= "CompanyName = '" & Company.Text & "', "
SqlUpdate &= "PassportNum = '" & PassNum.Text & "' "
SqlUpdate &= "Where user_id ='" & Session("user_id") & "'"
Dim cmd As New OleDbCommand(SqlUpdate, con.oleconnection)
Dim rad As OleDbDataReader
Try
con.open()
rad = cmd.ExecuteReader()
Finally
rad.Close()
con.close()
Response.Redirect("~\Worker\Profile.aspx")
End Try
End Sub
based on this code, the data can't be updated. the textbox.text in update_click will retrieve the same value of textbox in page_load (which is data from database) instead of the text input by the user.
it all worked fine if i delete the code for retrieving the data from database inside page_load. did i miss something in my code?
put
If Not Page.IsPostBack Then
//code
End If
inside page_load
I got a toolbar with different actions the user can start. In the user interface it looks like:
If I press on the "Ok" button the value will not known at the backend. My code structure is the following:
Configuration of an action
<Action Id="MyAction" Name="Action with Form">
<Form>
<asp:TextBox xmlns:asp="System.Web.UI.WebControls" ID="txtValue" runat="server" />
</Form>
</Action>
ASPX-File
<asp:Content ContentPlaceHolderID="cphToolbar" Runat="Server">
<asp:PlaceHolder ID="plhToolbar" runat="server" />
</asp:Content>
VB-File to the ASPX-File
Partial Class Form
Inherits UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.plhToolbar.Controls.Add(Me.CreateActionToolbar(<XML configuration element for the toolbar>))
End Sub
End Class
Page base class
Namespace UI
Public MustInherit Class Page
Inherits System.Web.UI.Page
Protected Overridable Function CreateActionToolbar(source As XmlElement) As Interfaces.IActions
Dim oAction As Interfaces.IActions = Me.LoadControl("~/Controls/Toolbar/Actions.ascx")
For Each element As XmlElement In source.SelectNodes("node()").OfType(Of XmlElement)()
Dim NewItem As New Controls.ActionItem
'set settings for the toolbar element
'add fields to form
For Each Item As XmlNode In element.SelectNodes("Form/node()", oNamespaceManager)
If (TypeOf Item Is XmlElement) Then
If (NewItem.Fields Is Nothing) Then NewItem.Fields = New List(Of XmlElement)
NewItem.Fields.Add(Item)
End If
Next
oAction.Items.Add(NewItem)
Next
Return oAction
End Function
End Class
End Namespace
Action user control
Partial Class Actions
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each Item As ActionItem In Me.Items
'set settings for action
If (Not (Item.Fields Is Nothing)) Then
Dim oPanel As New Panel
oPanel.ID = "dlgActionPanel" & Me.dlgAction.Controls.Count
Me.dlgAction.Controls.Add(oPanel)
Dim oFields As New Panel
oFields.ID = oPanel.ID & "_Controls"
For Each Field As XmlElement In Item.Fields
Dim oControl As System.Web.UI.Control = Nothing
Try
oControl = Me.ParseControl(Field.OuterXml)
Catch ex As Exception
oControl = New LiteralControl("<font style=""color:red;"">" & ex.Message & "</font>")
End Try
oFields.Controls.Add(oControl)
Next
Dim pnlResult As New Panel
Dim btnOk As New Button
btnOk.ID = "btnOk_" & oPanel.ID
AddHandler btnOk.Click, AddressOf Ok_Click
btnOk.Attributes.Add("onclick", "ShowWaitDialog();")
btnOk.Attributes.Add("ItemId", NewAnchor.Attributes("ItemId"))
btnOk.UseSubmitBehavior = False
btnOk.Text = Me.AcceptDialogText
pnlResult.Controls.Add(btnOk)
Dim btnCancel As New Button
btnCancel.Attributes.Add("onclick", "ShowWaitDialog();$('#" & oPanel.ClientID & "').dialog('close');CloseWaitDialog();return false;")
btnCancel.Text = Me.CancelDialogText
pnlResult.Controls.Add(btnCancel)
oPanel.Controls.Add(oFields)
oPanel.Controls.Add(pnlResult)
Dim strMessageControlId As String = oPanel.ClientID
strClientScript &= "$(""#" & strMessageControlId & """).dialog({" & NewLine
strClientScript &= " bgiframe:true, " & NewLine
strClientScript &= " autoOpen:false, " & NewLine
strClientScript &= " modal:true, " & NewLine
strClientScript &= " closeOnEscape:false, " & NewLine
strClientScript &= " width:600, " & NewLine
strClientScript &= " height:450, " & NewLine
strClientScript &= " minWidth:450, " & NewLine
strClientScript &= " minHeight:300, " & NewLine
If (Not (Item.Description Is Nothing)) Then strClientScript &= " title:'" & Item.Description & "', " & NewLine
strClientScript &= " open: function(event, ui) { $("".ui-dialog-titlebar-close"").hide(); } " & NewLine
strClientScript &= "});" & NewLine
If (String.IsNullOrEmpty(NewAnchor.Attributes("onclick"))) Then NewAnchor.Attributes.Add("onclick", String.Empty)
NewAnchor.Attributes("onclick") &= "$('#" & oPanel.ClientID & "').dialog('open');"
End If
Next
End Sub
Private Sub Ok_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim oDialog As Panel = Nothing
If (Not (String.IsNullOrEmpty(sender.ID))) Then oDialog = Me.dlgAction.FindControl(sender.ID.Substring(sender.ID.IndexOf("_") + 1) & "_Controls")
Dim oAction As ActionItem = Items.Find(Function(item) item.ItemId = sender.Attributes("ItemId"))
If (Not (oDialog Is Nothing)) Then
For Each Field As XmlElement In oAction.Fields
Dim oControl As WebControl = Nothing
If (Not (Field.SelectSingleNode("#Id|#ID") Is Nothing)) Then oControl = oDialog.FindControl(Field.SelectSingleNode("#Id|#ID").Value)
If (Not (oControl Is Nothing)) Then
Dim oParameter As SqlClient.SqlParameter = oAction.Parameters.Find(Function(item) item.ParameterName = "#" & oControl.ID.Substring(3))
If (Not (oParameter Is Nothing)) Then
Select Case oControl.GetType.ToString
Case GetType(TextBox).ToString
'After postback the value is empty!!!
If (Not (String.IsNullOrEmpty(CType(oControl, TextBox).Text))) Then oParameter.Value = CType(oControl, TextBox).Text
'more controls
Case Else
End Select
End If
End If
Next
End If
End Sub
End Class
Where is the fault that the value of the TextBox is after PostBack empty and not set because of the View State?
Thanks for any response.
I could solve it. The problem was that the jQuery dialog was not PostBack save. The solution was
$("#dialog").dialog({
appendTo:'form:first'
});
I'm using this code to insert in database , but every time it inserts more than one row ,what is the problem ?
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
Dim com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
con.Open()
com.ExecuteNonQuery()
con.Close()
End Using
End Sub
Have you checked to see if your block of code is being called more than once? One quick way is to put a alert box inside so you can count the times it runs.
Well... there are lots of problems. The first of which is the potential for SQL Injection, you should be using named parameters. Another is that the line about Dim com As New... should also be in a Using clause.
However, nothing in that bit of code suggests that it is inserting more than 1 record. I suggest you put a break point on the ExecuteNonQuery line and see what's going on.
I have checked and hole the button click was executed twice , I have changed the code to this one and it has been solved , but I dont know why the click event is executed twice :
Dim i As Boolean = True
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
con.Open()
Using com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
If i = True Then
com.ExecuteScalar()
i = False
End If
End Using
con.Close()
End Using
End Sub
I have to use an old user control written in the ASP.NET 2.0 days. the control is running fine in a ASP.NET 2.0 environment, but when the control is used with asp.net 4.0 it stops working.
Here is the code from the user control:
<%# Control Language="VB" Inherits="ControlDb" Src="../Bin/ControlDb.vb"%>
<%# import Namespace="System.Data" %>
<%# import Namespace="System" %>
<%# import Namespace="System.Data" %>
<%# import Namespace="System.Web" %>
<%# import Namespace="System.Web.UI" %>
<%# import Namespace="System.Web.UI.WebControls" %>
<%# import Namespace="System.Web.UI.HtmlControls" %>
<%# import Namespace="System.Data.OleDb" %>
<%# import Namespace="System.Configuration" %>
<script runat="server">
' Public isEditable as Boolean
Public Class CommonDb
Inherits System.Web.UI.Page
Dim ConnectionString As String = "<ConnectionString>"
Public Property dbConnection() As String
Get
Return ConnectionString
End Get
Set(ByVal Value As String)
ConnectionString = Value
End Set
End Property
Public Function Execute_GetID(ByVal strSQL As String) As Long
Dim dbConn As New OleDbConnection(ConnectionString)
Dim dbComm1 As New OleDbCommand(strSQL, dbConn)
Dim dbComm2 As New OleDbCommand("SELECT ##IDENTITY", dbConn)
dbConn.Open()
dbComm1.ExecuteNonQuery()
Dim id As Long = CLng(dbComm2.ExecuteScalar())
Return id
End Function
Function Execute(ByVal strSQL As String) As Integer
Dim dbConn As New OleDbConnection(ConnectionString)
Dim dbComm As New OleDbCommand(strSQL, dbConn)
Dim rowsAffected As Integer = 0
dbComm.Connection = dbConn
dbConn.Open()
Try
rowsAffected = dbComm.ExecuteNonQuery
Finally
dbConn.Close()
End Try
Return rowsAffected
End Function
Public Function FillData(ByVal strSQL As String) As DataSet
Dim conn As New OleDbConnection(ConnectionString)
Dim adapter As New OleDbDataAdapter
Dim ds As New DataSet
adapter.SelectCommand = New OleDbCommand(strSQL, conn)
adapter.Fill(ds)
Return ds
End Function
End Class
Private Cdb as new ControlDb()
Private dtR as DataTable
Private resourceIds as DataRow()
Sub Page_Load(Src As Object, E As EventArgs)
End Sub
Public Sub setData()
dtR = Cdb.FillData("SELECT resourceid FROM VEJLEDNING_RESOURCE WHERE centerid = '" & CenterId & "' AND date='" & DateTime & "' ORDER BY resourceid;").tables(0)
if dtR.rows.count > 0 then
Dim dtB as DataTable = Cdb.FillData("SELECT Count(resourceid) FROM VEJLEDNING_BOOKING WHERE resourceid='" & dtR.rows(0)("resourceid") & "'").tables(0)
RBtn.text = FormatDateTime(DateTime,vbShorttime) & "(" & dtR.rows.count & "/" & dtB.rows(0)(0) & ")"
RemBtn.Visible=true
CType(Page.FindControl("IntervalList"),DropDownList).Enabled=false
If dtB.rows(0)(0) >= dtR.rows.count
RBtnClass = "BookingBusyEdit"
else
RBtnClass = "BookingFree"
end if
else
RBtn.text = FormatDateTime(DateTime,vbShorttime) & "(0/0)"
RBtnClass = "BookingNormalEdit"
RemBtn.Visible=false
end if
End Sub
Public ReadOnly Property AddBtnId As Button
Get
Return AddBtn
End Get
End Property
Public ReadOnly Property RBtnId As Button
Get
Return RBtn
End Get
End Property
Public ReadOnly Property RemBtnId As Button
Get
Return RemBtn
End Get
End Property
Public Property Text As String
Get
Return RBtn.text
End Get
Set
RBtn.text = Value
End Set
End Property
Public Property DateTime As String
Get
Return ViewState("time")
End Get
Set
ViewState("time") = Value
End Set
End Property
Public Property CenterId As String
Get
Return ViewState("centerid")
End Get
Set
ViewState("centerid") = Value
End Set
End Property
Public Property isEditable As Boolean
Get
Return ViewState("isEditable")
End Get
Set
ViewState("isEditable") = Value
End Set
End Property
Public Property addBtnClass As String
Get
Return AddBtn.CssClass
End Get
Set
AddBtn.CssClass = Value
End Set
End Property
Public Property RBtnClass As String
Get
Return RBtn.CssClass
End Get
Set
RBtn.CssClass = Value
End Set
End Property
Public Property RemBtnClass As String
Get
Return RemBtn.CssClass
End Get
Set
RemBtn.CssClass = Value
End Set
End Property
Sub AddBtn_Click(sender As Object, e As EventArgs)
NyPost(ViewState("time"))
setData()
End Sub
Sub RBtn_Click(sender As Object, e As EventArgs)
Dim interval as Integer = CType(Page.FindControl("IntervalList"),DropDownList).SelectedItem.Value
if isEditable then
response.redirect("Resource.aspx?id=" & CenterId & "&dtm=" & DateTime & "&interval=" & interval)
else
response.redirect("Booking.aspx?id=" & CenterId & "&dtm=" & DateTime)
end if
End Sub
Sub RemBtn_Click(sender As Object, e As EventArgs)
setData()
Try
Cdb.Execute("DELETE FROM VEJLEDNING_RESOURCE WHERE centerid = '" & CenterId & "' AND date='" & DateTime & "'") ' Ryd
'Cdb.Execute("DELETE FROM VEJLEDNING_RESOURCE WHERE resourceid = '" & dtR.rows (dtR.rows.count-1)("resourceid") & "'") ' Fjern sidste
Catch ex As Exception
End Try
setData()
End Sub
Sub NyPost(dato)
Dim strSQL as string
Dim wn As Integer = DatePart("ww", dato, vbMonday, FirstWeekOfYear.FirstFourDays)
Dim interval as Integer = CType(Page.FindControl("IntervalList"),DropDownList).SelectedItem.Value
If not session("initialer") = nothing then
if wn = 53 then wn = 1
Try
strSQL = "INSERT INTO VEJLEDNING_RESOURCE ("
strSQL = strSQL & "centerid, "
strSQL = strSQL & "week, "
strSQL = strSQL & "interval, "
strSQL = strSQL & "initialer, "
strSQL = strSQL & "date "
strSQL = strSQL & ") "
strSQL = strSQL & "VALUES ("
strSQL = strSQL & "'" & CenterId & "', "
strSQL = strSQL & "'" & wn & "', "
strSQL = strSQL & "'" & interval & "', "
strSQL = strSQL & "'" & session("initialer") & "', "
strSQL = strSQL & "'" & dato & "' "
strSQL = strSQL & ")"
Cdb.Execute(strSQL)
Catch ex As Exception
End Try
End If
End sub
</script>
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<asp:Button title="Tilføj ressource" id="AddBtn" onclick="AddBtn_Click" CssClass="BookingFree" Visible="true" Width="14px" runat="server" Text="+"></asp:Button>
</td>
<td width="100">
<asp:Button id="RBtn" onclick="RBtn_Click" Width="100px" runat="server"></asp:Button>
</td>
<td>
<asp:Button title="Slet ressource" id="RemBtn" onclick="RemBtn_Click" CssClass="BookingFree" Visible="true" Width="14px" runat="server" Text="-"></asp:Button>
</td>
</tr>
</table>
Here is the code from the file that uses the user control:
<%# Page Language="vb" Inherits="CommonDb" Src="../bin/CommonDb.vb" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Drawing" %>
<%# Register TagPrefix="MyControls" TagName="RB" Src="ResourceButton.ascx" %>
<script runat="server">
Dim Cdb As New CommonDb
Dim ResourceDst As DataTable
Dim BookingDst As DataTable
Dim dtmCurrent As Date = Now()
Dim intDatebuff = (Weekday(dtmCurrent, vbMonday) - 1) * -1
Dim dtmMonday As Date = FormatDateTime(DateAdd("d", intDatebuff, dtmCurrent), vbShortDate)
Dim WeekDays As String() = {"Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag"}
Dim dtmStart As String = "08:00"
Dim dtmEnd As String = "19:00"
Dim dtmInterval As Integer = 20
Dim BInterval As String() = {"10", "15", "20", "25", "30", "40", "60"}
Dim CenterId As String
Dim cssBtnBar As String
Dim isEditable As Boolean
Dim strOverskrift As String
Dim testYear As String
Sub Page_Load(ByVal Src As Object, ByVal E As EventArgs)
Response.Expires = 0
Response.AppendHeader("Refresh", Convert.ToString((Session.Timeout * 60) + 10) & ";URL=.")
CenterId = Request.QueryString("id")
If CenterId <> "" Or Not Session("initialer") Is Nothing Then
isEditable = (CenterId <> "" And Request.QueryString("admin") <> "" And Not Session("initialer") Is Nothing)
If Not isEditable Then
strOverskrift = "Book en tid : "
cssBtnBar = "display:none;"
Else
strOverskrift = "Læg vejledertider ind (" & Session("initialer") & ")"
End If
If Not IsPostBack Then
VisChatBtn(getChat())
Cdb.Execute("LP_Cleanup_Vejledning_resource") ' 52 uger
If Request.QueryString("dtm") <> "" Then dtmMonday = Request.QueryString("dtm")
ShowPage(dtmMonday)
ViewState("dtmMonday") = dtmMonday
Else
dtmMonday = ViewState("dtmMonday")
End If
Else
Response.Redirect(".")
End If
End Sub
Sub AddControl(ByVal day As String, ByVal e As RepeaterItemEventArgs)
'Dim uc = CType(e.Item.FindControl(day), Web.UI.UserControl)
Dim uc As Web.UI.UserControl = e.Item.FindControl(day)
Dim strTider As String = e.Item.DataItem(day).ToString
Dim ResourceRows As DataRow() = ResourceDst.Select("date='" & strTider & "'")
Dim rc As Integer = ResourceRows.Length
Dim BookingRows As DataRow() = BookingDst.Select("date='" & strTider & "'")
Dim br As Integer = BookingRows.Length
If isEditable Then
uc.RBtnId.text = FormatDateTime(e.Item.DataItem(day).ToString, vbShortTime) & "(" & rc & "/" & br & ")"
If rc = 0 Then
uc.RemBtnId.Visible = False
uc.RBtnClass = "BookingNormalEdit"
ElseIf br >= rc Then
uc.RBtnClass = "BookingBusyEdit"
Else
uc.RBtnClass = "BookingFree"
End If
Else
uc.RBtnId.text = FormatDateTime(e.Item.DataItem(day).ToString, vbShortTime)
uc.RemBtnId.Visible = False
uc.AddBtnId.Visible = False
If rc = 0 Then
setNormalBooking(uc, FormatDateTime(e.Item.DataItem(day).ToString, vbShortTime))
ElseIf br >= rc Then
uc.RBtnId.Attributes.add("onClick", "this.blur();return false;")
uc.RBtnClass = "BookingBusy"
Else
uc.RBtnClass = "BookingFree"
End If
End If
uc.isEditable = isEditable
uc.DateTime = strTider
uc.CenterId = CenterId
End Sub
Here is the error message:
Server Error in '/' Application.
--------------------------------------------------------------------------------
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30456: 'RBtnId' is not a member of 'System.Web.UI.UserControl'.
Source Error:
Line 209:
Line 210: If isEditable Then
Line 211: uc.RBtnId.text = FormatDateTime(e.Item.DataItem(day).ToString, vbShortTime) & "(" & rc & "/" & br & ")"
Line 212: If rc = 0 Then
Line 213: uc.RemBtnId.Visible = False
Source File: \\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx Line: 211
Show Detailed Compiler Output:
Microsoft (R) Visual Basic Compiler version 10.0.30319.233
Copyright (c) Microsoft Corporation. All rights reserved.
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(211) : error BC30456: 'RBtnId' is not a member of 'System.Web.UI.UserControl'.
uc.RBtnId.text = FormatDateTime(e.Item.DataItem(day).ToString, vbShortTime) & "(" & rc & "/" & br & ")"
~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(213) : error BC30456: 'RemBtnId' is not a member of 'System.Web.UI.UserControl'.
uc.RemBtnId.Visible = False
~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(214) : error BC30456: 'RBtnClass' is not a member of 'System.Web.UI.UserControl'.
uc.RBtnClass = "BookingNormalEdit"
~~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(216) : error BC30456: 'RBtnClass' is not a member of 'System.Web.UI.UserControl'.
uc.RBtnClass = "BookingBusyEdit"
~~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(218) : error BC30456: 'RBtnClass' is not a member of 'System.Web.UI.UserControl'.
uc.RBtnClass = "BookingFree"
~~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(221) : error BC30456: 'RBtnId' is not a member of 'System.Web.UI.UserControl'.
uc.RBtnId.text = FormatDateTime(e.Item.DataItem(day).ToString, vbShortTime)
~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(222) : error BC30456: 'RemBtnId' is not a member of 'System.Web.UI.UserControl'.
uc.RemBtnId.Visible = False
~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(223) : error BC30456: 'AddBtnId' is not a member of 'System.Web.UI.UserControl'.
uc.AddBtnId.Visible = False
~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(227) : error BC30456: 'RBtnId' is not a member of 'System.Web.UI.UserControl'.
uc.RBtnId.Attributes.add("onClick", "this.blur();return false;")
~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(228) : error BC30456: 'RBtnClass' is not a member of 'System.Web.UI.UserControl'.
uc.RBtnClass = "BookingBusy"
~~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(230) : error BC30456: 'RBtnClass' is not a member of 'System.Web.UI.UserControl'.
uc.RBtnClass = "BookingFree"
~~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(234) : error BC30456: 'isEditable' is not a member of 'System.Web.UI.UserControl'.
uc.isEditable = isEditable
~~~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(235) : error BC30456: 'DateTime' is not a member of 'System.Web.UI.UserControl'.
uc.DateTime = strTider
~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(236) : error BC30456: 'CenterId' is not a member of 'System.Web.UI.UserControl'.
uc.CenterId = CenterId
~~~~~~~~~~~
\\Webfilefs\websites\DATAPOOL006\u12jbyv\wwwroot\vejlederbooking\hfvuc.aspx(405) : warning BC40004: WithEvents variable 'header' conflicts with property 'header' in the base class 'Page' and should be declared 'Shadows'.
Protected WithEvents header As Global.System.Web.UI.WebControls.Literal
How do i use this control under 4.0?
I had some old UserControls that worked fine in Debug mode, but when I tried to publish the site, I received the same error you received, that a property I had defined for the control was "not a member of System.Web.UI.WebControl."
I thought that declaring the property as "Public" in the block at the top of my UserControl was sufficient. However, there seems to be something with way the aspnet_compiler works that caused it to fail to recognize this Property when I attempted to publish the site. I haven't done any digging into this to find out why it didn't work (deadlines, you know). If anyone could explain that behavior, I'd love to hear the reason behind it!
The fix? I ended up moving all of the code for the user control into a code behind file rather than including it in the tags at the top of the control itself. Once I did that, the site compiled and published without any errors.
I think WithEvents variable 'header' conflicts with property 'header' in the base class 'Page' and should be declared 'Shadows'. is creating problem. Try to resolve this error and see what happens.
I have a form email, asp.net 4.0 / VB / Visual Studio, and I want it to go automatically into a Microsoft Access DB without any effort from me. Is this possible? I'm not a programmer, but here's the form e-mail:
<script runat="server">
Protected Sub SubmitForm_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsValid Then Exit Sub
Dim SendResultsTo As String = "me#domain.com"
Dim smtpMailServer As String = "smtp.domain.com"
Dim smtpUsername As String = "me#domain.com"
Dim smtpPassword As String = "******"
Dim MailSubject As String = "Form Results"
Try
Dim txtQ As TextBox = Me.FormContent.FindControl("TextBoxQ")
If txtQ IsNot Nothing Then
Dim ans As String = ViewState("hf1")
If ans.ToLower <> txtQ.Text.ToLower Or ans.ToUpper <> txtQ.Text.ToUpper Then
Me.YourForm.ActiveViewIndex = 3
Exit Sub
End If
End If
Dim FromEmail As String = SendResultsTo
Dim msgBody As StringBuilder = New StringBuilder()
Dim sendCC As Boolean = False
For Each c As Control In Me.FormContent.Controls
Select Case c.GetType.ToString
Case "System.Web.UI.WebControls.TextBox"
Dim txt As TextBox = CType(c, TextBox)
If txt.ID.ToLower <> "textboxq" Then
msgBody.Append(txt.ID & ": " & txt.Text & vbCrLf & vbCrLf)
End If
If txt.ID.ToLower = "email" Then
FromEmail = txt.Text
End If
If txt.ID.ToLower = "subject" Then
MailSubject = txt.Text
End If
Case "System.Web.UI.WebControls.CheckBox"
Dim chk As CheckBox = CType(c, CheckBox)
If chk.ID.ToLower = "checkboxcc" Then
If chk.Checked Then sendCC = True
Else
msgBody.Append(chk.ID & ": " & chk.Checked & vbCrLf & vbCrLf)
End If
Case "System.Web.UI.WebControls.RadioButton"
Dim rad As RadioButton = CType(c, RadioButton)
msgBody.Append(rad.ID & ": " & rad.Checked & vbCrLf & vbCrLf)
Case "System.Web.UI.WebControls.DropDownList"
Dim ddl As DropDownList = CType(c, DropDownList)
msgBody.Append(ddl.ID & ": " & ddl.SelectedValue & vbCrLf & vbCrLf)
End Select
Next
msgBody.AppendLine()
msgBody.Append("Browser: " & Request.UserAgent & vbCrLf & vbCrLf)
msgBody.Append("IP Address: " & Request.UserHostAddress & vbCrLf & vbCrLf)
msgBody.Append("Server Date & Time: " & DateTime.Now & vbCrLf & vbCrLf)
Dim myMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
myMessage.To.Add(SendResultsTo)
myMessage.From = New System.Net.Mail.MailAddress(FromEmail)
myMessage.Subject = MailSubject
myMessage.Body = msgBody.ToString
myMessage.IsBodyHtml = False
If sendCC Then myMessage.CC.Add(FromEmail)
Dim basicAuthenticationInfo As New System.Net.NetworkCredential(smtpUsername, smtpPassword)
Dim MailObj As New System.Net.Mail.SmtpClient(smtpMailServer)
MailObj.Credentials = basicAuthenticationInfo
MailObj.Send(myMessage)
Me.YourForm.ActiveViewIndex = 1
Catch
Me.YourForm.ActiveViewIndex = 2
End Try
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsPostBack Then
Dim lbl As Label = Me.FormContent.FindControl("labelq")
If lbl IsNot Nothing Then
Dim rq(3) As String
rq(0) = "Is fire hot or cold?"
rq(1) = "Is ice hot or cold?"
rq(2) = "Is water wet or dry?"
Dim ra(3) As String
ra(0) = "hot"
ra(1) = "cold"
ra(2) = "wet"
Dim rnd As New Random
Dim rn As Integer = rnd.Next(0, 3)
lbl.Text = rq(rn)
ViewState("hf1") = ra(rn)
End If
End If
End Sub
</script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server"> <h1>CONTACT HEALTH
NUTTS AND WORK FROM THE COMFORT OF YOUR OWN HOME!
Enter your Email Address:
* Required
* Please enter a valid email address.
Subject:
* Required
Please type your message below:
* Required
First Name:
* Required
Last Name:
* Required
Phone Number:
* Required
* Please enter a valid U.S. phone number (including dashes).
City:
* Required
State/Province:
* Required
Your message has been sent. Thank you for contacting us.
Due to technical difficulty, your message may NOT have been sent.
You did not correctly answer the anti-spam question. Please go back and try again.
When someone fills out the form, I get an e-mail like this:
Email: rmajeski#yahoo.com
Subject: I need A Job
Message: Me wants job today okay? Thank you for J.O.B
First_Name: Rich
Last_Name: Majeski
Phone: xxx-xxx-xxxx
City: Hockeytown
State: Michigan
Browser: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101
Firefox/12.0
IP Address: 108.224.49.14
Server Date & Time: 5/15/2012 6:03:33 AM
How can I make this go into a Microsoft Access DB automatically, without me having to do it manually? Any guidance would be truly appreciated! Thanks!
You can have a read on tutorials on Office add-in programming.
One way to go would be having this add-in looking at every incoming email in Outlook and parse the fields into corresponding variables. After that you can create a database connection to a MS Access database file to insert the data with an SQL-Insert DML statement.
I think this would be the easiest way for you, as programming this will not take too many lines of code. But MS Outlook has to be running!
The best way would of course be to create the database connection asynchronously (using ODBC) in ASP.NET. There should be a lot tutorials on that online.