Checking if parameter has been passed in windows universal c# code - c#

Am passing a parameter as a way to allow a user to go back and make changes
private void go_back_btn_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(TruckRegistrationPage), this.truckdetails);
}
Now on the trruck registration page
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
this.changeddetails= (TruckRegistrationDetails)e.Parameter;
//set the form fields based on the details
if (e.Parameter) //this throws an error of boolean not casted
{
truck_reg_no.Text = changeddetails.reg_no;
transporter_name.Text = truckdetails.owner_id;
.......assign other xaml controls
}
}
The parameters am passing are of type TruckRegistrationDetails whic is a class containing properties as below
class TruckRegistrationDetails
{
public int id { get; set; }
public string reg_no { get; set; }
public int truck_category { get; set; }
.......others
}
How do i check to see if any parameters have been passed and hence assign the xaml controls value

Change your code to this
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
changeddetails = (TruckRegistrationDetails)e.Parameter;
if (changeddetails != null)
{
truck_reg_no.Text = changeddetails.reg_no;
//do what ever you want ^^
}
}
Your check was for a boolean, but e.Parameter is an object. Here is the link to MSDN https://msdn.microsoft.com/de-de/library/windows/apps/windows.ui.xaml.navigation.navigationeventargs.parameter.aspx

I was getting an error using this approach as at some point OnNavigatedTo is called with a NavigationEventArgs.Parameter of an empty string. This was causing a Cast exception when the object is cast to the object type I passed.
I used:
if (args.Parameter is DeviceInformation)
{
DeviceInformation deviceInfo = (DeviceInformation)args.Parameter;
//Do something with object
}
This checks the type of object first to see if it matches the expected first, then the cast will not throw an exception.

Related

Does not contain a definition for NavigationContext in Windows Phone 8.1

When I work this code in NavigationContext I am getting an error.
protected void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
base.OnNavigatedTo(e);
string parameterValue = NavigationContext.QueryString["parameter"];
}
In Windows Phone 8.1 RT model app there is no need to pass parameters in URI format. Now you can send them as an object. You can create your own class for this, for example:
public class MyParametersClass
{
public string Parameter1 { get; set; }
public int Parameter2 { get; set; }
public double Parameter3 { get; set; }
}
When you want to navigate from one page to another you use Frame.Navigate() method:
MyParametersClass myParameters = new MyParametersClass(); // Initialize parameters
myParameters.Parameters1 = "Trololo"; // Let set some values
Frame.Navigate(typeof(SomePage), myParameters); // Navigate to some page with parameters
When navigation is completed, you can just get object with your parameters from property named Parameter. You do this in a page you wanted to navigate.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
MyParametersClass myParameters = e.Parameter as MyParametersClass;
}

Update a public string from protected

I want to make this string public. i.e., available from other functions. How can I do that?
protected override void OnNavigatedTo(NavigationEventArgs e)
{
String parameter = NavigationContext.QueryString["parameter"];
}
Declare it outside of the function (global scope).
Something like:
String parameter="";
protected override void OnNavigatedTo(NavigationEventArgs e)
{
parameter = NavigationContext.QueryString["parameter"];
}
Now you can use the string parameter any where in that file.
public String parameter = new String();
protected override void OnNavigatedTo(NavigationEventArgs e){
String parameter = NavigationContext.QueryString["parameter"];
}
You just need to change the scope of your variable to global :)
My suggestion would be that you move it outside the function, but make it private, then expose it via a public property; for example:
private string _parameter;
public string Parameter
{
get { return _parameter;}
set
{
_parameter = value;
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
_parameter = NavigationContext.QueryString["parameter"];
}
If you only need to access it from within the current class, but outside of the function then you can leave out the property, or even make it read-only. Alternatively, you could use the implicit property definition:
public string Parameter { get; set; }
And with C# 6 you will be able to use initializers with this.

Property losing value even though declared Public

I've a file SiteMinder.CS in App_code where I set the UserID who has accessed the webpage
public class SiteMinder : IHttpModule
{
public string UserID { get; set; }
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(Application_PreRequestHandler);
}
private void Application_PreRequestHandler(Object source, EventArgs e)
{
if (HttpContext.Current.Request.Headers != null)
{
NameValueCollection coll = HttpContext.Current.Request.Headers;
UserID = coll["uid"]; // Doesn't have NULL value
}
}
}
In another webpage UserDetails.aspx.cs file I'm trying to access this UserID but it is having NULL value.
public partial class UserDetails : System.Web.UI.Page
{
protected string SessionUser { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
SiteMinder objSite = new SiteMinder();
SessionUser = objSite.UserID;//Returns NULL
}
}
All these are under same namespace. Please let me know where I'm wrong here.
You're creating a new SiteMinder object. That's not the same object that had the property set on it, so the property will have the default value (null).
You need to obtain a reference to the original SiteMinder object which set the property - or store the value somewhere else (such as the HttpContext).

What will be displayed by the MessageBox?

I Have Code for EventHandler like this below.
I do not know what is meant by e.Value, can someone explain and show approximately what will be displayed by the MessageBox?
void ConnectionManager_Error(object sender, EventArgs<string> e)
{
BeginInvoke((MethodInvoker)delegate()
{
State = ConnectState.NotFound;
MessageBox.Show(e.Value);
});
}
Note:
I have this code that I thought would trigger ConnectionManager Error EventHandler.
private void LogError(string error)
{
if (Error != null)
Error(this, new EventArgs<string>(error));
}
I also have this code that gives an error message containing the string to LogError method.
int lasterror = Marshal.GetLastWin32Error();
if (lasterror != 0)
LogError("Bluetooth API returned: " + lasterror.ToString());
or
if (BluetoothSetServiceState(IntPtr.Zero, ref device, ref HumanInterfaceDeviceServiceClass_UUID, BLUETOOTH_SERVICE_ENABLE) != 0)
LogError("Failed to connect to wiimote controller");
Another Hint
To be more specific, I also already have the code below:
public event EventHandler<EventArgs<string>> Error;
and
ConnectionManager.Error += new EventHandler<EventArgs<string>>(ConnectionManager_Error);
And also this class:
public class EventArgs<T> : EventArgs
{
public T Value
{
get;
set;
}
public EventArgs(T value)
: base()
{
Value = value;
}
}
But MessageBox never appears even when the device is not connected to the computer.
I think that comes MassageBox supposed that show error messages.
Can someone show me what is wrong?
Your ConnectionManager has Error event, which passes instance of EventArgs<string> to event handlers. I believe generic event argument looks like:
public class EventArgs<T> : EventArgs
{
public EventArgs(T value)
{
Value = value;
}
public T Value { get; private set; }
}
So, ConnectionManager sets some string value to this argument of event and passes it to ConnectionManager_Error event handler. You should see value which was passed. From event name I can assume it should be error message.
NOTE: ConnectState enum, State property of ConnectionManager and its StateChanged event is not related to code you work with.
A Message Box is shown with the value provided by the EventArgs. I can only assume that your EventArgs class is a generic EventArgs implementation where the type parameters defines the type of the value.
So whatever the value is, that is what you will see in the MessageBox.

Unable to access the fields of selecteditem on listview

I have a listview on mouse double click i am trying to get the name and path of the item selected, I have written following code but i am getting "System.NullReferenceException" error
public class Listview_data
{
public string name
{
get;
set;
}
public ImageSource Image
{
get;
set;
}
public string path
{
get;
set;
}
};
private void ListView_MouseDClick(object sender, MouseButtonEventArgs e)
{
Listview_data lvd = null;
lvd = DocsListView.SelectedItem as Listview_data;
MessageBox.Show(lvd.name);
}
I have attached screenshot of debugging
According to screenshot DocsListView.SelectedItem is of type SimpleCube.Documents
so after this line of code lvd is null
lvd = DocsListView.SelectedItem as Listview_data;
And following line of code throws NullReferenceException when accessing lvd.name
MessageBox.Show(lvd.name)
So fix your bindings first
According to the debug image posted your code should be
private void ListView_MouseDClick(object sender, MouseButtonEventArgs e)
{
SimpleCube.Documents lvd = null;
lvd = DocsListView.SelectedItem as SimpleCube.Documents;
if(lvd != null)
MessageBox.Show(lvd.Name);
}
Or, perhaps, the setting of the Datasource for the ListView should be changed to a Listview_Data list of objects.
You should be checking that the SelectedItem is not null prior to use for example;
private void ListView_MouseDClick(object sender, MouseButtonEventArgs e)
{
Listview_data lvd = null;
lvd = DocsListView.SelectedItem as Listview_data;
if (lvd == null)
{
MessageBox.Show("You should only double click on an item");
return;
}
MessageBox.Show(lvd.name);
}
There is the possibility that the SelectedItem property will return null if there is no items selected. Also by casting using 'as' you can also get a null reference exception later on if the object isn't the correct type, although this probably isn't a likely scenario in this case.
John Skeet has written a good article on using 'as' for type casting and checking for null, definitely worth a read (Casting vs "as" - embracing exceptions).

Categories