Access label control from masterpage throws nullreferenceexception - vb.net

enter code hereI am trying to assign a value to label in a Master Page using vb.net (not my first language-lol). I have followed info from these two references on how to access content from masterpage:
1.[https://msdn.microsoft.com/en-us/library/c8y19k6h(v=vs.90).aspx][1]
2.[nullreferenceexception was unhandled by user code in Master Page
I am getting Null Reference Exception on BUT ONLY when I try to call the method I created for it from another class. It works fine when I call it from the same class the method is in. I wrote a method from the starting page/class, WebForm1:
Public Sub PageIdentity(ByVal pageId As String)
' Gets a reference to a Label control inside a ContentPlaceHolder
Dim mpContentPlaceHolder As ContentPlaceHolder
'Dim mpTextBox As TextBox
Dim mpLabel As Label
mpContentPlaceHolder = CType(Master.FindControl("MainContent"), ContentPlaceHolder)*'Null Reference Exception here*
If Not mpContentPlaceHolder Is Nothing Then
mpLabel = CType(mpContentPlaceHolder.FindControl("lblPageIdentifier"), Label)
If Not mpLabel Is Nothing Then
mpLabel.Text = pageId
End If
End If
End Sub
when I call this function from another class in page load like this it throws null ref ex:
Dim oWebForm1 As WebForm1 = New WebForm1()
oWebForm1.PageIdentity("SomeText")
I must be doing something wrong in creating the instance? I tryed writing it as a Public Shared Function first but that created other problems. Can anyone help?
UPDATE: #Joey I replaced the commented line of code below as you suggested and put the sub in the master page code behind, Site1.Master.vb:
'mpContentPlaceHolder = CType(Master.FindControl("MainContent"), ContentPlaceHolder)
mpContentPlaceHolder = CType(Me.FindControl("MainContent"), ContentPlaceHolder)
I also ensured that the page directive on other pages included:
<%# MasterType VirtualPath = "~/Site1.Master" %>
On a test page, I called the sub like so:
Dim _SiteMaster As MasterPage = TryCast(Me.Master, MasterPage)
_SiteMaster.PageIdentity("SomeText")
I am getting blue squiggly line error, message: "PageIdentity is not a member of System.Web.UI.MasterPage"
The Master page inherits like this:
Public Partial Class Site1
Inherits System.Web.UI.MasterPage
The page calling the sub inherits like this
Public Class WebForm1
Inherits System.Web.UI.Page

Since you require the PageIdentity subroutine to be somewhat global you can move it into your master page. The master page can then be called by any page that references it. Use the following code on any page to call the PageIdentity routine:
Dim _SiteMaster As Site1 = TryCast(Me.Master, Site1)
_SiteMaster.PageIdentity("SomeText")

Related

Duplicated Control Name Causing 'Not A Member' Compile Errors

I have created a custom control called MultiTextbox. When I place my control onto a form and try to run my project, I get the following errors:
'MultiTextBox' is not a member of 'MultiTextbox.MultiTextbox'.
Type 'MultiTextbox.MultiTextbox' is not defined.
In my Form1.Designer code, I can see the following issues:
Me.MultiTextbox1 = New MultiTextbox.MultiTextbox()
Me.MultiTextbox1.ObjectAlignment = MultiTextbox.MultiTextbox.ObjectPlacement.Left
Me.MultiTextbox1.Style = MultiTextbox.MultiTextbox.TextboxStyle.Normal
Friend WithEvents MultiTextbox1 As MultiTextbox.MultiTextbox
I don't understand why it is duplicating the Control name for a selected few items.
The properties it is referring to are custom properties based from Enums.
For example:
Public Enum ObjectPlacement
Left
Right
End Enum
Private m_ObjectAlignment As ObjectPlacement = ObjectPlacement.Left
'ObjectAlignment
<Browsable(True), Category("Appearance"), _
Description("The text to display as an input group header.")> _
Public Property ObjectAlignment As ObjectPlacement
Get
Return m_ObjectAlignment
End Get
Set(value As ObjectPlacement)
If m_ObjectAlignment = value Then Return
m_ObjectAlignment = value
Me.Invalidate()
End Set
End Property
UPDATE
If I place my custom control on a form and run, everything will work fine without error, but as soon as I modify my control in any way (e.g. Size, Style, etc.) it gives me errors, and I can't even run the application as the compiler just sits in an infinite loop saying 'Building...'. I have to force quit VS.
Okay, after some useful posts on this thread and some googling, I found that by removing the Root Namespace from my project it removed all of my compiler errors that I was getting regarding a duplicated namespace (MultiTextbox.MultiTextbox):
Me.MultiTextbox1 = New MultiTextbox.MultiTextbox()
Me.MultiTextbox1.ObjectAlignment = MultiTextbox.MultiTextbox.ObjectPlacement.Left
Me.MultiTextbox1.Style = MultiTextbox.MultiTextbox.TextboxStyle.Normal
Friend WithEvents MultiTextbox1 As MultiTextbox.MultiTextbox
Secondly, the lockups that I was experiencing when trying to build my project was due to me setting a button's visible state within my paint event causing an infinite refresh loop of my control.

NullReferenceException on dll

Here is my code I get the error on:
Imports ADFactory
Public Class Salary
Inherits Salary_Datalayer
Protected _AD As New ADFactory.ADFactory
Protected Sub Page_Load(...)Handles Me.Load
_user = "username"
sDealer = _AD.GetUserCompany(_user)
It states that Protected _AD As New ADFactory.ADFactory is the line throwing the exception. I've looked online and read and changed it several times, declared 'New', am I missing something simple?
PatFromCanada was correct, my ADFactory was the problem. I didn't properly initialize a connection string within the reference, thus always throwing a nullexception, which apparently, I run into quite often in my questions. Thanks PatFromCanada!

Instantiating a function

This question is about a different instance that im trying to instantiate...
I have to get the "Read" function from my Cardreader class and return a string to it on the form1.vb .... Now i did what i can remeber but for some reason i'm having a problem with the brackets.... What can i do to fix this?
Form1.vb
ThisATM.getCardReader.Readr("TEST TEXT IS FUN")
CardReader.vb
Public Function Readr(ByVal card As KeyCard) As String
Return Read
End Function
Link for the image of the card reader function. I thought this link of the image of the code would be easier to understand.
The Readr function takes an KeyCard as parameter, not an string. So it seems like you have to create an instance to an KeyCard and use that as a parameter instead. In the code in the image you provided you are creating a keycard object, it seems like you should use that object in the Readr function like this:
Dim ThisKeyCard as new KeyCard("1234","5678","Mikki Monster")
Dim returnString as string=ThisATM.getCardReader.Readr(ThisKeyCard)

Switching between forms (VB.NET)

I always get an exception when I try to switch between different forms in my program. Maybe you will help me to solve this issue. Here is the exception message:
Control.Invoke must be used to interact with controls created on a separate thread
I have attached the forms to very nice variables and this problem occurs when I try to use command like MyForm.Show().
It does not happen when the forms are not attached to variables, but then I have collosal problems with refreshing the textboxes and stuff.
Hope to hear you soon!
edit;
I have 4 different forms. When I load the main module and main form, in the Sub (...) Handles MyBase.Load I execute the following code:
In module:
Public StartupForm As frmStartup
Public RegularForm As frmRegularUse
Public LoginForm As frmLogin
Public PasswordForm As frmPassword
Public SettingsForm As frmSettings
In main form:
RegularForm = Me
StartupForm = frmStartup
LoginForm = frmLogin
PasswordForm = frmPassword
SettingsForm = frmSettings
This is the aproach I worked out to get the full control over refreshing the forms. It is a program for Motorola Scanner with Windows CE. Now, for example, when I enter the correct password in LoginForm, I want to switch to the RegularForm. When I try to use RegularForm.Show() or RegularForm.ShowDialog or RegularForm.BringToFront(), I get an exception. When I try to call the form with the frmRegularUse.Show() I can call the form, but it is being created in a different thread, I believe, so I loose control over it (when I try to put something from the keyboard, there is no response).
I doubt the forms are getting created in a different thread, but if they are then STOP, go back, and fix that. All of your forms should be created and accessed from the main GUI thread. Secondly, I don't think you "newed" the forms. You need something like this:
StartupForm = New frmStartup
RegularForm = New frmRegularUse
LoginForm = New frmLogin
PasswordForm = New frmPassword
SettingsForm = New frmSettings
Actually, what I did is:
Still I have the same code in the main module, which is:
Public StartupForm As frmStartup
Public RegularForm As frmRegularUse
Public LoginForm As frmLogin
Public PasswordForm As frmPassword
Public SettingsForm As frmSettings
I managed it to work in the simpliest possible way. For example - I run the Login form, and execute the following code (long story short):
LoginForm = Me
frmRegularUse.ShowDialog()
I jump to the frmRegularUse form, where, once again, I execute:
RegularForm = Me
frmPasswordForm.ShowDialog()
And so on...
I made some tests and it works quite okay. Tomorrow I will try to make it a little bit more sophisticated. ;-)

How can I write to my own app.config using a strongly typed object?

The following code has two flaws, I can't figure out if they are bugs or by design. From what I have seen it should be possible to write back to the app.config file using the Configuration.Save and according to http://www.codeproject.com/KB/cs/SystemConfiguration.aspx the code should work.
The bugs are shown in the source below and appear when you try to set the property or save the config back out.
Imports System.Configuration
Public Class ConfigTest
Inherits ConfigurationSection
<ConfigurationProperty("JunkProperty", IsRequired:=True)> _
Public Property JunkProperty() As String
Get
Return CStr(Me("JunkProperty"))
End Get
Set(ByVal value As String)
' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
Me("JunkProperty") = value
End Set
End Property
Public Sub Save()
Dim ConfigManager As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
' The add / remove is according to http://www.codeproject.com/KB/cs/SystemConfiguration.aspx
ConfigManager.Sections.Remove("ConfigTest")
' *** Bug 2, exception InvalidOperationException thrown with message "Cannot add a ConfigurationSection that already belongs to the Configuration."
ConfigManager.Sections.Add("ConfigTest", Me)
ConfigManager.Save(ConfigurationSaveMode.Full, True)
End Sub
Public Shared Sub Main()
Dim AppConfig As ConfigTest = TryCast(ConfigurationManager.GetSection("ConfigTest"), ConfigTest)
AppConfig.JunkProperty = "Some test data"
AppConfig.Save()
End Sub
' App.Config should be:
' <?xml version="1.0" encoding="utf-8" ?>
'<configuration>
' <configSections>
' <section name="ConfigTest" type="ConsoleApp.ConfigTest, ConsoleApp" />
' </configSections>
' <ConfigTest JunkProperty="" />
'</configuration>
End Class
I'd like to do it this way so that on the first run of the app I check for the properties and then tell the user to run as admin if they need to be set, where the UI would help them with the settings. I've already 'run as admin' to no effect.
Your code doesn't really make any sense. I took your example code and turned it into a simple example that works. Please note this is not best practise code, merely an example to aid you on your journey of learning the configuration API.
Public Class ConfigTest
Inherits ConfigurationSection
<ConfigurationProperty("JunkProperty", IsRequired:=True)> _
Public Property JunkProperty() As String
Get
Return CStr(Me("JunkProperty"))
End Get
Set(ByVal value As String)
' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
Me("JunkProperty") = value
End Set
End Property
Public Overrides Function IsReadOnly() As Boolean
Return False
End Function
Public Shared Sub Main()
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim AppConfig As ConfigTest = config.GetSection("ConfigTest")
AppConfig.JunkProperty = "Some test data"
config.Save()
End Sub
End Class
This code will open the config file, modify the attribute JunkProperty and persist it back it the executable's configuration file. Hopefully this will get you started- it looks like you need to read about the configuration API a bit more.
I've used the API to create configuration sections for large scale enterprise apps, with several 1000 of lines of custom hierarchical config (my config was readonly though). The configuration API is very powerful once you've learnt it. One way I found out more about its capabilities was to use Reflector to see how the .NET framework uses the API internally.
Maybe you don't know Portuguese or c# but this is you want http://www.linhadecodigo.com.br/Artigo.aspx?id=1613
using BuildProvider from asp.net
After loading a configuration it is readonly by default, principally because you have not overriden the IsReadOnly property. Try to override it.
¿Is there something that prevents you from using a setting?
Looks like it is not possible by design. App.config is normally protected as it resides along with the app in the Program Files directory so must be amended at installation time by the installer.
Pity really, I'd like the app to have settings that an admin can set.
Sorry if I didn't understand your case, but yes, you can change App.config at runtime.
Actually, you will need to change YourApp.exe.config, because once your app is compiled, App.config contents are copied into YourApp.exe.config and your application never looks back at App.config.
So here's what I do (C# code - sorry, I still haven't learnt VB.Net)
public void UpdateAppSettings(string key, string value)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement item in xmlDoc.DocumentElement)
{
foreach (XmlNode node in item.ChildNodes)
{
if (node.Name == key)
{
node.Attributes[0].Value = value;
break;
}
}
}
using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile))
{
xmlDoc.Save(sw);
}