I'm aware that the NullReferenceException is pretty much the equivalent to the check engine light on a car but with this particular case I can't seem to pinpoint why its not working properly, I've never really messed with controls so I'm a bit unfamiliar in with the technicalities of it. What I have works, but I keep getting the exception when I run a trycatch around it. Here is what I have.
Dim TypeControl As Control
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
DBTable = MaterialStuff.GetMaterial(ID)
Using DBTable
If DBTable.Rows.Count > 0 Then
Try
CType(TypeControl, DropDownList).SelectedItem.Text = (DBTable.Rows(0).Item("MaterialTypeDescription").ToString)
Catch ex As NullReferenceException
trace.runAllErrorLogging(ex.ToString)
End Try
End If
A NullReferenceException doesn't have anything to do with "controls" specifically. It's just an indication that your code assumes an object exists when at runtime it doesn't exist. For example, if you do this:
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
CType(TypeControl, DropDownList).SelectedItem.Text = ...
Then your code assumes that TypeControl has a value on the second line. If it doesn't, trying to use .SelectedItem will fail because TypeControl is null. So you're assuming that .FindControl() actually found something. It doesn't make that guarantee implicitly.
Instead of making this assumption, you should verify:
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
If TypeControl Is Not Nothing Then
CType(TypeControl, DropDownList).SelectedItem.Text = ...
End If
That way the code only executes if there's a value that it can use. You can add an Else to handle the condition where no value is found. (Display an error? Log the error? Silently continue? It's up to you how the condition should be handled.)
There are two possible problems here:
1 - Does FindControl actually find the control you seek? Add a check in to make sure you are actually finding it:
Dim TypeControl As Control
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
If TypeControl Is Nothing Then Debug.Writeline("Could not find control")
2 - The SelectedItem of the control could also be Nothing so you may need to add a check here:
Dim ddl = CType(TypeControl, DropDownList)
If ddl.SelectedItem Is Nothing Then Debug.Writeline("Could not find selectedItem")
Related
I'm having trouble recovering a reference to a user control that is created dynamically so I can get the values of its properties or child controls.
I have a custom control called BookingObject.ascx which resides in App_Code.
I can create the controls programmatically without a problem but, later on, when I try to get a reference to the control, in order to access its child controls values, I just keep getting null.
Heres some code:
Dim MainItem As BookingItem = TryCast(LoadControl(GetType(BookingItem), Nothing), BookingItem)
MainItem.ID = "Item_" & NumberOfControls.ToString() 'Item_0
Dim lblid As Label = MainItem.FindControl("lblID")
lblid.Text = (NumberOfControls + 1).ToString()
NewItemPH.Controls.Add(MainItem)
Me.NumberOfControls += 1
This works fine and I can set the labels value successfully.
However:
Dim MainItem As BookingItem = TryCast(Me.Page.FindControl("Item_0"), BookingItem)
Dim product_id As DropDownList = MainItem.FindControl("product_id")
I get a null reference exception when trying to FindControl("product_id") as MainItem is nothing.
I've been struggling with this issue for hours now and it's something I assumed would be simple. I'm sure i'm just missing something small.
Can anyone tell me what I'm doing wrong?
All help is appreciated.
UPDATE
Never mind, I was being stupid and searching Me.Page for the control when I should have been searching NewItemPH.
Thanks to the mystery person who gave me the clue and then deleted their comment minutes later.
In VB.NET, I have a LinkButton that, when clicked, creates a report. We want to disable this functionality based on whom is logged into the system. I have a session variable to indicate whether this should be visible or not but when I set idLinkButton.visible = False, it has no effect. Any ideas on what I need to do to be able to turn this on and off?
'code-behind
' in page_load
If Not Convert.ToBoolean(HttpContext.Current.Session("HideReports")) Then
PDFbutton.Visible = True
Else If Convert.ToBoolean(HttpContext.Current.Session("HideReports")) And HttpContext.Current.Session("LoadFromConsole") Then
PDFbutton.Visible = True
end if
First, have you tried setting .Visible = false outside the if/then logic?
If that works, then you want to troubleshoot the logic. Add my first line to what you show above, then change your first line to my second line.
Dim hideRpt as Boolean = Convert.ToBoolean(HttpContext.Current.Session("HideReports"))
If Not hideRpt Then
Now put a breakpoint on the "If Not..." line.
If you aren't getting what you expect, add another line to get a string for the session value, to make sure it really should convert to a bool.
Basic troubleshooting, man, break it down into smaller parts. Sometimes I'll start a fresh windows app just to have a blank slate on which to work out details.
I'm struggling with deleting multiple rows. I'm learning and have managed new rows and edits but cant seem to nail delete. Can someone help please?
this is what I have:
If ViewState("QuoteGroupID") IsNot Nothing Then
Dim GQID As Integer = CInt(ViewState("QuoteGroupID"))
Using db As New quotingSystemDevEntities
Dim QuoteToDelete = (From q In db.QuotesGeneratedV2 Where q.QuoteGroupID = GQID Select q)
db.DeleteObject(QuoteToDelete)
db.SaveChanges()
End Using
End If
I'm getting the error "The object cannot be deleted because it was not found in the ObjectStateManager."
Thanks you for your time.
UPDATE
After much messing around I have figured it out. The info on the web was very difficult to make sense of so I went for the try everything until it works method... Might not be the perfect solution but it works better than the one that wasn't! Hopefully this info will help someone out:
If ViewState("QuoteGroupID") IsNot Nothing Then
Dim GQID As Integer = CInt(ViewState("QuoteGroupID"))
Using db As New quotingSystemDevEntities
Dim QuoteToDelete = (From q In db.QuotesGeneratedV2 Where q.QuoteGroupID = GQID Select q)
For Each item In QuoteToDelete
db.Detach(item)
db.Attach(item)
db.DeleteObject(item)
Next
db.SaveChanges()
End Using
End If
I think you missing ObjectContext.Attach Method. Try using that.
Also similar question can be found Entity Framework Delete Object Problem
I am using Code First EF. I have following code in my project
If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then
CurrentUser.ProductionLocation = Nothing
Else
CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLocation.SelectedValue))
End If
ddlProductionLocation is simply dropdown, CurrentUser is plain EF object, ProductionLocationRepository is boring class which provides me with access to database indirectly (returns plain EF object too).
User and ProductionLocation have 1-to-n relationship.
This did not work correctly for removing relationship as after setting ProductionLocation to nothing, it still contained original value. It worked randomly in few cases (during debugging etc).
Base on that I have realized, that problem is second part of relationship. I have changed code to this:
If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then
If CurrentUser.ProductionLocation IsNot Nothing Then
CurrentUser.ProductionLocation.Users.Remove(CurrentUser)
End If
CurrentUser.ProductionLocation = Nothing
Else
CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLocation.SelectedValue))
End If
MY QUESTION:
This works, but I believe this is not correct solution. Or is it? Or do i really have to remove both sides of relationship at all cases?
Thaks
EDIT:
Final solution is:
If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then
Dim pl = CurrentUser.ProductionLocation 'HACK for loading Product Location before setting it
CurrentUser.ProductionLocation = Nothing
Else
CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLocation.SelectedValue))
End If
Not nice, but works.
I keep getting the error ExecuteReader: CommandText property has not been initialized and i'm not sure why it points to this line in my code
dd1.DataSource = LogData.StermQ2(datelistquery).Tables(0).DefaultView
dd1.DataBind()
dd1.Items.Insert(0, new listitem("Any location", "%"))
The top line is the one with the error
Any help would be much appreciated
Thanks
Jamie
I suspect it has something to do with your data source:
LogData.StermQ2(datelistquery)
Typically, when I'm working with some a SQLDataSource, I have to initialize is like so:
mydatasource.SelectCommand = "select * from mytable"
dd1.DataBind()
SelectCommand is the CommandText is the query that you're passing in. If the property has not been initialized, perhaps you havn't created the command yet? Or perhaps the datasource itself has not been initialized yet.
The weird thing with it is that it only happened occasionally and if i emptied my cache it would work fine.
So I just disable caching on that page and it seems to be working (at the moment)
Also added in some Try Catch statements and seems to be ok
Thanks for the help though
Jamie