I was doing a test to upload pictures and i found out that when i upload pictures more than 2000px the webpage turn to be slow. I want users to upload pics with size not more than 600px and height 700px.
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Partial Class PhotoAdmin_Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
cannotUploadImageMessage.Visible = False
End Sub
Protected Sub dvPictureInsert_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvPictureInsert.ItemInserted
'If the record was successfully inserted, save the picture
If e.AffectedRows > 0 Then
'Determine the maximum pictureID for this user
Dim results As DataView =
CType(maxPictureIDDataSource.Select(DataSourceSelectArguments.Empty),
DataView)
Dim pictureIDJustAdded As Integer = CType(results(0)(0), Integer)
'Reference the FileUpload control
Dim imageUpload As FileUpload =
CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If imageUpload.HasFile Then
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
imageUpload.SaveAs(baseDirectory & pictureIDJustAdded & ".jpg")
End If
End If
If e.Exception Is Nothing Then
' Use the AffectedRows property to determine whether the
' record was inserted. Sometimes an error might occur that
' does not raise an exception, but prevents the insert
' operation from completing.
If e.AffectedRows = 1 Then
MessageLabel.Text = "Record inserted successfully."
Else
MessageLabel.Text = "An error occurred during the insert operation."
' Use the KeepInInsertMode property to remain in insert mode
' when an error occurs during the insert operation.
e.KeepInInsertMode = True
End If
Else
' Insert the code to handle the exception.
MessageLabel.Text = e.Exception.Message
' Use the ExceptionHandled property to indicate that the
' exception has already been handled.
e.ExceptionHandled = True
e.KeepInInsertMode = True
End If
End Sub
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting
Dim cancelInsert As Boolean = False
Dim imageUpload As FileUpload =
CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If Not imageUpload.HasFile Then
cancelInsert = True
Else
If Not imageUpload.FileName.ToUpper().EndsWith(".JPG") Then
cancelInsert = True 'Invalid image file!
End If
End If
If cancelInsert Then
e.Cancel = True
cannotUploadImageMessage.Visible = True
End If
'Set the UserId value to the currently logged on user's ID
e.Values("UserId") = Membership.GetUser().ProviderUserKey
'Set the UploadedOn value to the current date/time
e.Values("UploadedOn") = DateTime.Now
End Sub
Protected Sub gvPictures_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gvPictures.RowDeleted
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
Dim fileName As String = baseDirectory &
e.Keys("PictureID") & ".jpg"
File.Delete(fileName)
End Sub
Protected Sub gvPictures_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvPictures.RowUpdating
e.NewValues("UserId") = Membership.GetUser().ProviderUserKey
End Sub
End Class
Setting a max width and height on an uploaded image isn't necessarily going to fix your problem as you could upload an image with a much higher DPI and it still be a "large" image with small dimensions. Also, you would have to check the image dimensions once the image had been uploaded to your server.
You could set a maxiumum file size in the web.config using the maxRequestLength property which could be used to prevent a large file being uploaded...
Sorry if my vb is wrong as im a c# guy!! but I hope this should give you a guidance. I do something similar in c#. Good luck
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting
Dim cancelInsert As Boolean = False
Dim imageUpload As FileUpload =
CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If Not imageUpload.HasFile Then
cancelInsert = True
Else
If Not imageUpload.FileName.ToUpper().EndsWith(".JPG") Then
cancelInsert = True 'Invalid image file!
Else
Dim image As System.Drawing.Image =
System.Drawing.Image.FromStream(imageUpload.PostedFile.InputStream)
If image.Width > 600 Or image.Height > 700 Then
cancelInsert = True
End If
End If
End If
//etc
Related
I have a button which is not created dynamically. When I click on that button the number of lines in a textbox are counted. I store that in the variable called count. Depending on value of count I create buttons in panel.
Up to now it is working properly.
Now the click event of those buttons is not firing.
I have tried to google my question. But everywhere I got the same answer. Create the controls in Page_Init event. But how is it possible? I am getting the value of count from a textfile's lines, and that value of count decides how many button will be created in the panel.
Dim btnAllow As New Button
btnAllow.Text = "Allow"
btnAllow.ID = "btA" & x
AddHandler btnAllow.Click, AddressOf btnAllow_Click
btnAllowList.Add(btnAllow)
tdAllow.Controls.Add(btnAllow)
The code for btnAllow_Click
Protected Sub btnAllow_Click(ByVal sender As Object, ByVal e As System.EventArgs)
For x As Integer = 0 To btnAllowList.Count - 1
If sender.ID.SubString(3) = btnAllowList(x).ID.Substring(3) Then
Dim lineCount = IO.File.ReadAllLines(PendingRequestsPath).Length
Dim reader As New System.IO.StreamReader(DocumentViewersPath)
Dim allLines As New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
Dim DocumentViewerAlreadyExists As Boolean = False
For i As Integer = 0 To lineCount - 1
If ReadLine(i, allLines) = lblRequestorsList(x).Text Then
DocumentViewerAlreadyExists = True
Exit For
End If
Next
If DocumentViewerAlreadyExists = False Then
Dim Writer As System.IO.StreamWriter = IO.File.AppendText(DocumentViewersPath)
Writer.WriteLine(lblRequestorsList(x).Text)
End If
Dim line As String = ""
Dim r As IO.StreamReader = IO.File.OpenText(PendingRequestsPath)
Dim strFile As New ArrayList
While r.Peek <> -1 ' Loop through the file
line = r.ReadLine 'Read the next available line
' Check to see if the line contains what you're looking for.
' If not, add it to an ArrayList
If Not line.Contains(lblRequestorsList(x).Text) Then
strFile.Add(line)
End If
r.Close()
' Because we want to replace the content of the file, we first
' need to delete it.
If IO.File.Exists(PendingRequestsPath) Then
IO.File.Delete(PendingRequestsPath)
End If
' Create a StreamWriter object with the same filename
Dim objWriter As New IO.StreamWriter(PendingRequestsPath, True)
' Iterate through the ArrayList
For Each item As ArrayList In strFile
objWriter.WriteLine(item) ' Write the current item in the ArrayList to the file.
Next
objWriter.Flush()
objWriter.Close()
End While
End If
Next
End Sub
This worked for me:
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim NumberOfControls As Integer = 10
Session("CreateControls") = NumberOfControls
End Sub
Protected Sub btnAllow_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'This will be executed when clicking on the newly created buttons.
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Session("CreateControls") IsNot Nothing Then
For x As Integer = 0 To Convert.ToInt32(Session("CreateControls"))
Dim btnAllow As New Button
btnAllow.Text = "Allow"
btnAllow.ID = "btA" & x
AddHandler btnAllow.Click, AddressOf btnAllow_Click
Panel1.Controls.Add(btnAllow)
Next
End If
End Sub
I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:
Imports System.Data.OleDb
Partial Public Class addBook
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
Dim noFile As String = Nothing
Dim myGUID = Guid.NewGuid()
Dim newFileName As String = myGUID.ToString() & ".jpg"
Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
If fu_picture.HasFile Then
fu_picture.SaveAs(fileLocationOnServerHardDisk)
Else
myGUID = noFile
End If
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7,#f8)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_booktitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_bookauthor.Text)
cmd.Parameters.AddWithValue("#f3", tb_bookpubyear.Text)
cmd.Parameters.AddWithValue("#f4", tb_bookpages.Text)
cmd.Parameters.AddWithValue("#f5", tb_publisher.Text)
cmd.Parameters.AddWithValue("#f6", tb_blurb.Text)
cmd.Parameters.AddWithValue("#f7", "img/thumb/" & newFileName)
cmd.Parameters.AddWithValue("#f8", rbl_Stars.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/addedrecord.aspx")
End Sub
Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged
End Sub
End Class
Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist
You should pass DBNull.Value to your db if you fail the requirement
cmd.Parameters.AddWithValue("#f7", _
if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)
The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.
In my VB.net ASP application, i have some ASPTREEVIEW where, on page load there is a Label, to which i set some value. After clicking on any row, i catch that value & assign it to the label.
But suddenly that label value is not updating by the chosen value. As if i check it via debugging the value, the value changes, but when i use Lable.text = chosen_value... It sets the value, but it is not actually changing on the html page. HTML shows the old value.
What will be the problem, i am not getting it.
Imports DevExpress
Imports DevExpress.Xpo
Imports DevExpress.Data
Imports DevExpress.Data.Filtering
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Public testvar As Integer = 35
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xpcol As New XPCollection(Of WCSOEE.WcsGCObject)
Dim GCObj1 As WCSOEE.WcsGCObject
Dim Filter1 As New DevExpress.XtraCharts.DataFilter
Dim SelectedGCObject As WCSOEE.WcsGCObject
Filter1.ColumnName = "Oid"
Filter1.Condition = XtraCharts.DataFilterCondition.Equal
Filter1.Value = Label2.Text
If Label2.Text = "" Then
Label2.Text = 10
End If
For Each Siris As DevExpress.XtraCharts.Series In WebChartControl1.Series
' WebChartControl1.Series(Siris.Name).DataFilters.Item(0).Value = CInt(Label2.Text)
Next
Dim masterKeyvalue As DevExpress.Web.ASPxTreeList.TreeListNode = ASPxTreeList1.FocusedNode
If masterKeyvalue IsNot Nothing Then
SelectedGCObject = masterKeyvalue.DataItem
Else
SelectedGCObject = xpcol.Object(31)
End If
' MsgBox(SelectedGCObject.GCName)
MsgBox(Label2.Text)
If IsPostBack = False Then
Label2.Text = calculatehours(SelectedGCObject.Oid)
End If
End Sub
Protected Function calculatehours(Oid As Integer)
xpocolLogAvailability.Session = DevExpress.Xpo.XpoDefault.Session
Dim logavail As New XPCollection(Of WCSOEE.LogAvailability)
Dim gcobjlist As New XPCollection(Of WCSOEE.WcsGCObject)
gcobjlist.Filter = CriteriaOperator.Parse("[Oid]=?", Oid)
Dim filter As CriteriaOperator
Dim ds As New DataTable
Dim Series As New DevExpress.XtraCharts.Series
Dim Filter1 As New DevExpress.XtraCharts.DataFilter
' Label2.Text = Oid
logavail.Filter = CriteriaOperator.Parse("GCObject.Oid=?", Oid)
Filter1.ColumnName = "Oid"
Filter1.Condition = XtraCharts.DataFilterCondition.Equal
Filter1.Value = Oid
Dim arr1(32) As Long
'For i As Int16 = 1 To 32
' arr1(i) = 0
'Next
'For Each gcobj As WCSOEE.LogAvailability In logavail
' arr1(gcobj.Status) = arr1(gcobj.Status) + gcobj.Duration
'Next= ""
'ds.Columns.Add(New DataColumn("Name", System.Type.GetType("System.Int32")))
For Each Siris As DevExpress.XtraCharts.Series In WebChartControl1.Series
WebChartControl1.Series(Siris.Name).DataFilters.Item(0).Value = Oid
Next
WebChartControl1.RefreshData()
'For i As Int16 = 1 To 32
' ds.Rows.Add(i, arr1(i))
'Next
'ASPxListBox1.DataSource = ds
'ASPxListBox1.DataBind()
Return Oid
End Function
Protected Sub ASPxTreeList1_CustomCallback(sender As Object, e As DevExpress.Web.ASPxTreeList.TreeListCustomCallbackEventArgs) Handles ASPxTreeList1.CustomCallback
End Sub
Protected Sub ASPxTreeList1_FocusedNodeChanged(sender As Object, e As System.EventArgs) Handles ASPxTreeList1.FocusedNodeChanged
Dim masterKeyvalue As DevExpress.Web.ASPxTreeList.TreeListNode = ASPxTreeList1.FocusedNode
Dim SelectedGCObject As WCSOEE.WcsGCObject = masterKeyvalue.DataItem
' MsgBox(SelectedGCObject.GCName)
If IsPostBack Then
Label2.Text = calculatehours(SelectedGCObject.Oid)
End If
MsgBox(IsPostBack)
MsgBox(Label2.Text)
End Sub
End Class
Post some code so we can see exactly what your doing, without seeing anything so far ensure you have an If statement in your page load to only apply the label text if the current request is not a postback other wise the the label will be set to this on every request.
If Not IsPostBack() Then
lblSomeLabel.Text = "Page load text"
End If
I'm using ASP.net 4.0 VB :)
I am using a session variable to add a user entered code into the url of each page. I can get the code to show up at the end of the page's URL that my textbox is on, but what do I add to every page to make sure that the session stays at the end of every URL that person visits during their session? This is the code from the page that the user enters their user code.
Protected Sub IBTextBoxButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles IBTextBoxButton.Click
Session("IB") = IBTextBox.Text
Dim IB As String = Session("IB")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ProductID.Value = Request.QueryString("id")
If Session("IB") Is Nothing Then
tab4.Visible = "False"
Else
tab4.Visible = "True"
End If
End Sub
This is what I have in the page load of one of the other pages. What else do I add to make sure that variable is added to the URL of that page?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim IB As String
IB = Session("IB")
End Sub
string url = Request.Url.ToString();
string newUrl = url + url.Contains("?") ? "&" : "?" + "ib=" + Server.UrlEncode(IBTextBox.Text);
Response.Redirect(newUrl);
return;
The approach I might use would be to create a base page class that all of your pages can inherit. The base page would then inherit the System.Web.UI.Page.
Within your base page class, create a property for IB and also handle the page load event.
In that event, check if the QueryString has the IB parameter in it. If it does, set the property to the value in the parameter.
Private _IB As String
Public Property IB() As String
Get
Return _IB
End Get
Set(ByVal value As String)
_IB = value
End Set
End Property
Public Function GetIB(ByVal url As String) As String
If Not(_IB = String.Empty) Then
If (url.Contains("?")) Then
Return "&IB=" & _IB
Else
Return url & "?IB=" & _IB
End If
Else
Return url
End If
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (String.IsNullOrEmpty(Request.QueryString("IB"))) Then
_IB = Request.QueryString("IB")
End If
End Sub
Finally in your markup you would need to place something like the following at the end of all of your links:
next page
I threw this code into the Master Page to make sure that every page knows whether or not the Session is there. Thanks for all the help everyone!
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Session("IB") Is Nothing Then
IBText.Visible = True
IBTextBox.Visible = True
IBTextBoxButton.Visible = True
Else
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name")
End If
End Sub
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
Hello everyone I've been struggling with this error message for days:
Here is the error message:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 7:
Line 8: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Line 9: UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
Line 10: cannotUploadImageMessage.Visible = False
Line 11: End Sub
Source File: C:\Users\Collins\Documents\Visual Studio 2005\WebSites\living to please god world\PhotoAdmin\Default.aspx.vb Line: 9
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
PhotoAdmin_Default.Page_Load(Object sender, EventArgs e) in C:\Users\Collins\Documents\Visual Studio 2005\WebSites\living to please god world\PhotoAdmin\Default.aspx.vb:9
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
This is my complete code to upload photos. Can someone help me please?
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Partial Class PhotoAdmin_Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
cannotUploadImageMessage.Visible = False
End Sub
Protected Sub dvPictureInsert_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvPictureInsert.ItemInserted
'If the record was successfully inserted, save the picture
If e.AffectedRows > 0 Then
'Determine the maximum pictureID for this user
Dim results As DataView = CType(maxPictureIDDataSource.Select(DataSourceSelectArguments.Empty), DataView)
Dim pictureIDJustAdded As Integer = CType(results(0)(0), Integer)
'Reference the FileUpload control
Dim imageUpload As FileUpload = CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If imageUpload.HasFile Then
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
imageUpload.SaveAs(baseDirectory & pictureIDJustAdded & ".jpg")
End If
End If
If e.Exception Is Nothing Then
' Use the AffectedRows property to determine whether the
' record was inserted. Sometimes an error might occur that
' does not raise an exception, but prevents the insert
' operation from completing.
If e.AffectedRows = 1 Then
MessageLabel.Text = "Record inserted successfully."
Else
MessageLabel.Text = "An error occurred during the insert operation."
' Use the KeepInInsertMode property to remain in insert mode
' when an error occurs during the insert operation.
e.KeepInInsertMode = True
End If
Else
' Insert the code to handle the exception.
MessageLabel.Text = e.Exception.Message
' Use the ExceptionHandled property to indicate that the
' exception has already been handled.
e.ExceptionHandled = True
e.KeepInInsertMode = True
End If
End Sub
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting
Dim cancelInsert As Boolean = False
Dim imageUpload As FileUpload =CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If Not imageUpload.HasFile Then
cancelInsert = True
Dim acceptedExtensions = New String() {".jpg", ".png", ".gif"}
If Not acceptedExtensions.Contains(imageUpload.FileName, StringComparer.OrdinalIgnoreCase) Then
cancelInsert = True 'Invalid image file!
End If
Else
Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(imageUpload.PostedFile.InputStream)
If image.Width > 1300 Or image.Height > 950 Then
cancelInsert = True
End If
End If
If cancelInsert Then
e.Cancel = True
cannotUploadImageMessage.Visible = True
End If
'Set the UserId value to the currently logged on user's ID
e.Values("UserId") = Membership.GetUser().ProviderUserKey
'Set the UploadedOn value to the current date/time
e.Values("UploadedOn") = DateTime.Now
End Sub
Protected Sub gvPictures_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gvPictures.RowDeleted
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
Dim fileName As String = baseDirectory & e.Keys("PictureID") & ".jpg"
File.Delete(fileName)
End Sub
Protected Sub gvPictures_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvPictures.RowUpdating
e.NewValues("UserId") = Membership.GetUser().ProviderUserKey
End Sub
End Class
Are you sure Membership.GetUser() is actually returning a user?
You are authenticated and not an anonymous user, correct? You should add a null check or a check to make sure they are authenticated first. I believe you can use User.Identity.IsAuthenticated
Just while editing for formatting I see line 9 has to do with membership and a control. Gut instinct is saying you're not logged in or that control doesn't exist.
Place a breakpoint at your line 9, run the site in debug, and see if the Membership.GetUser() or UserIdValue are null.