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.
Related
I know this isn't a good approach or the Angular way of doing things. However, I have a legacy VB.NET application and I've implemented AngularJS in it for doing AJAX requests and working with data and the simplicity (I'm well versed with Angular).
My issue is ng-model overrides the value I retrieve from the server and set to the textbox. I don't really need much databinding but several directives I use 'require ng-model' which messes with the old web forms.
Here's the VB code behind setting the inputs .Text value :
'Invoiced Date - Load Initial Value Code
Try
'Dim valNumber As String = JAG.General.modFunctions.FormatFieldValue(oLoadLoadCore.LDC_Number.ToString, "int", "TextBox")
Dim valInvoicedDate As String = NASTek.Common.Lib.DB.modADO.GetDataValue("Select convert(varchar,LDC_InvoicedDate,101) from LoadCore where LDC_Key = " & Me.PrimaryKey, Me.conn).ToString
Me.txtInvoiced.Text = valInvoicedDate
Me.txtInvoiced.Attributes.Add("ng-model", valInvoicedDate.ToString())
Catch ex As System.Exception
Me.txtInvoiced.Text = ""
'Me.Context.Trace.Write("LoadLoadCore.txtInvoiced", "Unable to load initial value: " + ex.ToString() + "")
End Try
Here's the control being added the the placeholder :
Me.plhInvoiced.Controls.Add(Me.txtInvoiced)
Me.txtInvoiced.Attributes.Add("ng-model", "dateInvoiced")
Me.txtInvoiced.Attributes.Add("datepicker-popup", "MM/dd/yyyy")
Me.txtInvoiced.Attributes.Add("show-weeks", "false")
Me.txtInvoiced.Attributes.Add("show-button-bar", "true")
Me.txtInvoiced.CssClass = "FormTextBox"
Me.txtInvoiced.TextMode = TextBoxMode.SingleLine
Me.txtInvoiced.ID = "txtInvoiced"
I'm using the AngularUI datepicker directive which requires ng-model, I'm not an expert with directives at this time. I tried removing the ng-model from the 'require' line in the angularui bootstrap.js file and the popup would render without the calendar.
Does anyone know of a work around to this scenario?
Again, I know it's not elegant and the code/app are really awful and old. I hate working on it but I'm trying to make it easier to do simple CRUD operations and displaying data. If there's no work around then I'll just have to query the info and set it in the js Controller, but I didn't want to have to do that as I don't need the ng-model at this point on these particular fields. I'm mainly trying to run third party calls that render simple data on the webform and that's why I'm not needing the databinding in particular.
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")
I want to use Report Viewer in my project.
i have
1. CustomerDetails - Stored Procedure
2. CustomerDataset.xsd - in which i dragged n dropped the stored procedure.
3. CustomerReport.rdlc - in which i have crated a table which and data set is
CustomerDetails
4. CustomerReportViewer.aspx - in which the CustomerReoprt.rdlc is being binded.
now, i want to pass 2 values "chkeckInDate" and "checkOutDate" from 2 text box which are to be filled by use from "main.aspx" also i 'm calling my stored procedure from this file .
the report viewer is getting displayed but, the contents are not getting displayed (i have executed my stored procedure and it is running perfectly.)
How can i fix it? please help.
I didn't clearly understand where is the mistake, but I think you have the code under page_load event. Copy the code into button_click.
This is what I've used..
You must inport this:
Imports Microsoft.Reporting.WinForms
You should pass the textbox value as parameter.
Dim yr As New ReportParameter("param1", TextBox1.Text)
Try
Me.your_TableAdapter.Fill(Me.DataSet_name.table_name)
ReportViewer1.LocalReport.SetParameters(New ReportParameter() {yr})
Me.ReportViewer1.RefreshReport()
Catch ex As Exception
MsgBox("try again")
End Try
copy these two lines from page_load event into button_click.
Me.your_TableAdapter.Fill(Me.DataSet_name.table_name)
Me.ReportViewer1.RefreshReport()
Further, watch this
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.