This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have this code in the main wpf window:
private void ButtonChangePermissions_Click(object sender, RoutedEventArgs e)
{
if (ComboBoxSelectedProfile.SelectedIndex != -1)
{
ChangePermissionsWindow cpWindow = new ChangePermissionsWindow { parent = this };
cpWindow.Show();
}
else
{
MessageBox.Show("Please choose a profile first.");
}
}
This is the child wpf window code:
public partial class ChangePermissionsWindow : Window
{
private readonly string dbConnectionString = Properties.Settings.Default.dbConnectionString;
public postLoginWindow parent { get; set; }
public ChangePermissionsWindow()
{
InitializeComponent();
ComboBoxValuesToShow();
}
private void ComboBoxValuesToShow()
{
using (SqlConnection connection = new SqlConnection(dbConnectionString))
{
try
{
connection.Open();
if (TableFunctions.doesTableExist("ProfilePermissions", dbConnectionString))
{
string selectQuery = "SELECT Permissions from ProfilePermissions where ProfileName = #ProfileName";
using (SqlCommand command = new SqlCommand(selectQuery, connection))
{
command.Parameters.AddWithValue("#ProfileName", parent.ComboBoxSelectedProfile.Text);//This line produces the Null reference error
...Does not matter from here
}
For some reason the line:
command.Parameters.AddWithValue("#ProfileName", parent.ComboBoxSelectedProfile.Text)
causes a NullReferenceException.
This is the exception documentation:
System.NullReferenceException: Object reference not set to an instance
of an object.
at WpfApplication1.Windows.ChangePermissionsWindow.ComboBoxValuesToShow()
in c:\Users\Censored\Documents\Visual Studio
2013\Projects\WpfApplication1\WpfApplication1\Windows\WindowChangePermissions.xaml.cs:line 38}
System.Exception {System.NullReferenceException
I will appreciate your help very much!
At a very high-level using the Object initialization syntax follows these steps...
Create an instance of the desired class by calling the appropriate constructor
Call all of the listed property setters
Return the newly initialized object
ComboBoxValuesToShow is called from the constructor but based on the listed steps the parent property (which is used in the method) is not set until after the constructor returns, because the property setters are not called until after the instance is created. Therefore the parent property will always be null in this case.
There are a couple of ways that come to mind to solve this...
If you want to use the parent property in the constructor then pass the value into the constructor and initialize the property internally.
Or
Make the ComboBoxValuesToShow method accessible from the parent window and move the call to ComboBoxValuesToShow from the constructor to the event handler in the parent window.
Related
I'm trying to access a native Wpf control property within the UI test framework (MS UI Tests). My specific issue is that, when I try accessing a WpfButton control property (e.g., IsVisible) using the function call WpfButtonObject.GetProperty("IsVisible"), the exception "System.NotSupportedExceptions" occurs. I'm able to see this WpfButton property using Snoop; so, I'm wondering if the GetProperty call is correct? Please see my related code below. Thanks for any insight.
UIMap.cs: Test function for a pressing a WpfButton. Please note the call uIButton.GetPropery("IsVisible"). This is where the exception occurs:
public void PressButtonTest()
{
WpfButton uIButton = this.UIMainWindowWindow.UIButtonButton;
object state = uIButton.GetProperty("IsVisible"); // Throws SystemNotSupportedException exception
bool stateBool = (bool)state;
Assert.IsTrue(stateBool, "Button is visible");
PressButton();
}
UIMap.Designer.cs: WpfButton property:
public WpfButton UIButtonButton
{
get
{
if ((this.mUIButtonButton == null))
{
this.mUIButtonButton = new WpfButton(this);
#region Search Criteria
this.mUIButtonButton.SearchProperties[WpfButton.PropertyNames.AutomationId] = "button";
this.mUIButtonButton.WindowTitles.Add("MainWindow");
#endregion
}
return this.mUIButtonButton;
}
}
Here's what I've done:
Point point;
bool isClickable = uIButton.TryGetClickablePoint(out point);
Assert.IsTrue(isClickable, "No clickable point was found, button not visible.");
By the way, your message in your Assert (2nd parameter) is inaccurate because it's only used on fail... in your case, when the button would not be visible. So in your output it would say "Button is visible" on failure when in fact it was not.
I've found a sample showing how to connect to SQL server (a local MDF), but it uses databinding, how can I use SQL in the normal way (insert, select, update, delete..., sqldatareader, without binding), I think all SQL staff should be performed in service.cs, so how can I use SQL from my XAML.cs? here is the service code:
and here service.cs:
public class ServiceCustomer : IServiceCustomer
{
public clsCustomer getCustomer(int intCustomer)
{
SqlConnection objConnection = new SqlConnection();
DataSet ObjDataset = new DataSet();
SqlDataAdapter objAdapater = new SqlDataAdapter();
SqlCommand objCommand = new SqlCommand("Select * from Customer where CustomerId=" + intCustomer.ToString());
objConnection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
objConnection.Open();
objCommand.Connection = objConnection;
objAdapater.SelectCommand = objCommand;
objAdapater.Fill(ObjDataset);
clsCustomer objCustomer = new clsCustomer();
objCustomer.CustomerCode = ObjDataset.Tables[0].Rows[0][0].ToString();
objCustomer.Customer = ObjDataset.Tables[0].Rows[0][1].ToString();
objConnection.Close();
return objCustomer;
}
}
and my page.xaml.cs:
public Page()
{
InitializeComponent();
ServiceCustomerClient obj = new ServiceCustomerClient();
obj.getCustomerCompleted += new EventHandler<getCustomerCompletedEventArgs>(DisplayResults);
obj.getCustomerAsync(1);
}
void DisplayResults(object sender, getCustomerCompletedEventArgs e)
{
LayoutRoot.DataContext = e.Result;
}
how can I insert a value into my dayabase right from my page.xaml.cs? how can I make a connection between service and xaml objects and functions?
thanks
The Page.xaml.cs file is not autogenerated in a standard silverlight project (beyond it's initial creation via template), so any changes you make to the class will persist.
If your current project does some autogen of xaml classes then you can use the partial class feature of C# Partial Classes in C# Guide to add to the class without worrying that the autogen will remove your additions.
You would need to add another method within your service class that performs the insert, and then pass it the values from your form.
public class ServiceCustomer : IServiceCustomer
{
public clsCustomer getCustomer(int intCustomer)
{
...
}
public void addCustomer(clsCustomer newCustomer)
{
//Code to add the customer to the database
}
}
to call this from your code you could use the following code, all calls to the service in silverlight are Asynchronous calls therefore they are called in a seperate thread but since the following call has no return there is no need for a completed event handler.
public void foo
{
clsCustomer cust = new clsCustomer();
//Create your customer object here
ServiceCustomerClient obj = new ServiceCustomerClient();
obj.AddCustomerAsync(cust);
}
this function could then be called when ever you want to add a customer, E.g. when a button is clicked
public void somebutton_Click(object sender, RoutedEventArgs e)
{
foo();
}
If you need any more information let me know.
hi i have this lines of code that i cant make it work
the goal is simple setting the form1 to visible = false
public static void DoActions(string Cmd){
if(Cmd == true)
{
MainForm.Visible = false;
}
}
but i keep on having this error
An object reference is required for
the non-static field, method, or
property
usually i set the called methond to static.. so the error will go away
but on this case how do i do it?
thanks for any help guys
'System.Windows.Forms.Control.Invoke(System.Delegate)'
This is happening because DoActions is a static method rather than an instance method, however MainForm is an instance field / property. The distinction is that instance methods operate on an instance of the class on which they are defined, wheras static methods do not.
This means that wheras instance methods are able to access properties, fields and methods of their containing class through the this keyword, for example:
// Instance field
Form1 MainForm;
void InstanceMethod()
{
Form1 frm = this.MainForm;
}
You cannot do the same thing from inside a static method (think about it, what instance would it operate on?). Note that C# will implicitly assume the use of the this keyword in places where it makes sense (so the above example could have been written as Form1 frm = MainForm).
See C# Static Methods for an alternative explanation of static vs instance methods (this is an important concept in object oriented programming that you should take the time to understand properly).
In your example you probably want to change DoActions to an instance method (by removing the static declaration):
public void DoActions(string Cmd)
{
if(Cmd == true)
{
this.MainForm.Visible = false;
}
}
This will allow it to access the instance MainForm field / property, however this may cause problems elsewhere in your code in places where you attempt to call DoActions from another static method without supplying an object instance.
Set form opacity and showintaskbar property in property window:
this.Opacity = 0;
this.ShowInTaskbar = false;
Your method is static - and so cannot access MainForm.
Make your method non-static if it is not required to be so.
public void DoActions(string Cmd)
{
if(Cmd == true)
{
MainForm.Visible = false;
}
}
If it is required, then create a static field in your class and ensure it is set before this method runs.
I am trying to display a custom dialog box multiple times using the following code:
TestWindow newTestWindow = new TestWindow(test);
newTestWindow.Owner = this;
newTestWindow.ShowDialog();
And I get the following exception when running the code above for the 2nd time:
Specified element is already the logical child of another element. Disconnect it first.
Chances are you are trying to display the same element in both dialogs (maybe the test parameter)? You would need to disconnect the element from the dialog when it's closed, so that it can be used in any subsequent dialogs.
Works fine for me:
public partial class MainWindow : Window
{
private Test _newTestWindow;
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(OnLoaded);
}
private void OnLoaded( object sender, RoutedEventArgs e )
{
_newTestWindow = new Test { Owner = this };
_newTestWindow.ShowDialog();
_newTestWindow = new Test { Owner = this };
_newTestWindow.ShowDialog();
}
}
I'm attempting to implement an adorner for a PasswordBox to add watermark functionality. I'm basing it on the project at http://sladorner.codeplex.com/. I've gotten the watermark implementation working in a sandbox application, but I'm running into issues when I attempt to add this to a class library.
When the line that sets _Popup.Child is executed, I get the exception "Error HRESULT E_FAIL has been returned from a call to a COM component." Is there a solution for this (or maybe a completely different way around the issue of watermarking a PasswordBox)?
public class PasswordBoxWatermarkAdorner : Control
{
private Border _ContentBorder;
private TextBlock _WatermarkTextBlock;
private PasswordBox _AssociatedElement;
private Popup _Popup;
private string _WatermarkText;
public PasswordBoxWatermarkAdorner(PasswordBox associatedElement, string watermarkText)
{
this.DefaultStyleKey = typeof(PasswordBoxWatermarkAdorner);
_AssociatedElement = associatedElement;
_WatermarkText = watermarkText;
_Popup = new Popup
{
Child = this,
IsOpen = true
};
_Popup.LayoutUpdated += _Popup_LayoutUpdated;
}