How to make back button return to the system Windows Phone - windows-phone-7

I have a small app there is 3 seconds intro page, then the content page. When I push back button I go back to the intro screen, but I think I should go back to the system. How to do it?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ServiceModel.Syndication;
using System.Xml;
using Microsoft.Phone.Tasks;
namespace RSS {
public partial class FeedPage : PhoneApplicationPage {
public FeedPage() {
InitializeComponent();
this.Loaded += new RoutedEventHandler(PhonePage1_Loaded);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
clearBackStack();
base.OnNavigatedTo(e);
}
void clearBackStack() {
while (this.NavigationService.BackStack.Any()) {
this.NavigationService.RemoveBackEntry();
}
}
void PhonePage1_Loaded(object sender, RoutedEventArgs e) {
// clearBackStack();
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("http://www.carmagazine.co.uk/Shared/Handlers/RssHandler.ashx?&N=190&Ns=P_Publication_Date|1&?"));
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
SyndicationFeed feed;
try {
using (XmlReader reader = XmlReader.Create(e.Result)) {
feed = SyndicationFeed.Load(reader);
lista.ItemsSource = feed.Items;
}
} catch (WebException we) { MessageBox.Show("Internet connection is down.");}
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e) {
WebBrowserTask webBrowserTask = new WebBrowserTask();
String url = (String)((Button)sender).Tag;
webBrowserTask.Uri = new Uri(url);
webBrowserTask.Show();
}
}
}

You should clear the BackStack in the OnNavigateTo method of your content page
while (this.NavigationService.BackStack.Any())
{
this.NavigationService.RemoveBackEntry();
}

The following code is the best practice for the back button key press.
protected override void OnBackKeyPress(CancelEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
base.OnBackKeyPress(e);
}
This ensures that your application will exit and return to the main screen on pressing the BackKey.

Related

While navigating to Register Player details screen, throws object reference error in Xamarin.Forms

On click on the Register_OnClicked button in the Xamarin.Forms app, system throws System.NullReferenceException: Object reference not set to an instance of an object This button will allow app to navigate to Player Register details screen from where the system save data. Could someone please advise about the cause of the error? I couldn't figure out the reason for that error yet, have restarted the app, perform the clean buildoperation, but still the same.
Database library using : sqlite-net-pcl
//MainPage.xaml.cs details
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
public async void NavigateButton_OnClicked(object sender, EventArgs e)
{
var tabbedPage = new TabbedPage();
tabbedPage.Children.Add(new Home("Welcome"+' '+emailEntry.Text+' '+",have a nice day!"));
tabbedPage.Children.Add(new Map());
tabbedPage.Children.Add(new Settings());
await Navigation.PushAsync(tabbedPage);
}
public async void Register_OnClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new Register());
}
}
Register.xaml.cs details where the saving of Player details:
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Linq;
namespace soccerapp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Register : ContentPage
{
public SQLiteConnection conn;
public Register()
{
InitializeComponent();
conn = DependencyService.Get<Isqlite>().GetConnection();
conn.CreateTable<PlayerDetails>();
}
public void RegisterSave_OnClicked(object sender, EventArgs e)
{
PlayerDetails playerDetails = new PlayerDetails();
playerDetails.FullName = fullNameEntry.Text;
playerDetails.Mobile = mobileEntry.Text;
playerDetails.SoccerPosition = soccerpostionEntry.Text;
playerDetails.Email = emailRegister.Text;
playerDetails.Password = passwordEntry.Text;
int x = 0;
try
{
x = conn.Insert(playerDetails);
}
catch (Exception ex)
{
throw ex;
}
if (x == 1)
{
DisplayAlert("Registration", "Player Registered Successfully", "Cancel");
}
else
{
DisplayAlert("Registration Failled!!!", "Please try again", "ERROR");
}
}
}
}
SQlite Connection class created and return connection:
public class SQliteDroid : Isqlite
{
public SQLiteConnection GetConnection()
{
var dbase = "soccerpep";
var dbpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
var path = Path.Combine(dbpath, dbase);
var connection = new SQLiteConnection(path);
return connection;
}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/nZ8GZ.png
Error details from Debug > Windows > Call Stack add below;
0xFFFFFFFFFFFFFFFF in System.Diagnostics.Debugger.Mono_UnhandledException_internal C#
0x1 in System.Diagnostics.Debugger.Mono_UnhandledException C#
0x20 in Android.Runtime.DynamicMethodNameCounter.43 C#
0x12 in System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw C#
0x6 in System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_0 C#
0xC in Android.App.SyncContext. C#
0xE in Java.Lang.Thread.RunnableImplementor.Run C#
0xA in Java.Lang.IRunnableInvoker.n_Run C#
0x11 in Android.Runtime.DynamicMethodNameCounter.43 C#
Debug through the Constructor for your Register page, and the GetConnection method of your SqliteDroid class.
I've seen hard-to-find errors like this when the Dependency Injection fails. This could be either because of an error in GetConnection, or because SqliteDroid has not been registered in your DependencyService.

Customizing the progress bar color in UWP using Xamarin Forms

I made a progress bar customization (custom renderer) to change the progress bar color in iOS and Droid as seen in the following
Custom progress bar class in the PCL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace App2
{
public class ColorProgressBar : ProgressBar
{
public static BindableProperty BarColorProperty
= BindableProperty.Create<ColorProgressBar, Color>(p =>
p.BarColor, default(Color));
public Color BarColor
{
get { return (Color)GetValue(BarColorProperty); }
set { SetValue(BarColorProperty, value); }
}
}
}
Custom renderer for iOS:
using App2;
using App2.iOS;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Xamarin.Forms;
//using MonoTouch.Foundation;
//using MonoTouch.UIKit;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(ColorProgressBar),
typeof(ColorProgressBarRenderer))]
namespace App2.iOS
{
public class ColorProgressBarRenderer : ProgressBarRenderer
{
public ColorProgressBarRenderer()
{ }
protected override void
OnElementChanged(ElementChangedEventArgs<ProgressBar> e)
{
base.OnElementChanged(e);
if (e.NewElement == null)
return;
if (Control != null)
{
UpdateBarColor();
}
}
protected override void OnElementPropertyChanged(object sender,
PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName ==
ColorProgressBar.BarColorProperty.PropertyName)
{
UpdateBarColor();
}
}
private void UpdateBarColor()
{
var element = Element as ColorProgressBar;
Control.TintColor = element.BarColor.ToUIColor();
}
}
}
Custom renderer for Android:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Renderscripts;
using static Java.Util.ResourceBundle;
using Xamarin.Forms.Platform.Android;
using Android.Graphics;
using System.ComponentModel;
using Xamarin.Forms;
using App2;
using App2.Droid;
[assembly: ExportRenderer(typeof(ColorProgressBar),
typeof(ColorProgressBarRenderer))]
namespace App2.Droid
{
public class ColorProgressBarRenderer : ProgressBarRenderer
{
public ColorProgressBarRenderer()
{ }
protected override void
OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ProgressBar>
e)
{
base.OnElementChanged(e);
if (e.NewElement == null)
return;
if (Control != null)
{
UpdateBarColor();
}
}
protected override void OnElementPropertyChanged(object sender,
PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName ==
ColorProgressBar.BarColorProperty.PropertyName)
{
UpdateBarColor();
}
}
private void UpdateBarColor()
{
var element = Element as ColorProgressBar;
// http://stackoverflow.com/a/29199280
Control.IndeterminateDrawable.SetColorFilter(
element.BarColor.ToAndroid(), PorterDuff.Mode.SrcIn);
Control.ProgressDrawable.SetColorFilter(
element.BarColor.ToAndroid(), PorterDuff.Mode.SrcIn);
}
}
}
I'm setting the custom progress bar's color this way:
var progressBar = new ColorProgressBar();
progressBar.BarColor = Color.Red;
I don't understand how to make a custom renderer class for UWP that changes the color of the progress bar. Could someone please help me understand how to do this class?
You're going to want to update the Foreground property of the native Windows.UI.Xaml.Controls.ProgressBar control to change the color.
It should look something like this:
private void UpdateBarColor()
{
var element = Element as ColorProgressBar;
Control.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(
GetWindowsColor(element.BarColor));
}
Windows.UI.Color GetWindowsColor(Color color)
{
return Windows.UI.Color.FromArgb((byte)(255 * color.A), (byte)(255 * color.R), (byte)(255 * color.G), (byte)(255 * color.B));
}
This will take your BarColor, use it to make a SolidColorBrush of the right color, and then assign that to your native ProgressBar control.

Insert, Update, Delete query using LINQ in datagridview in C# Windows Programming?

Scenario: There is following controls in the form:
datagridview, textbox1, textbox2, button(save,edit,update,delete)
1.By clicking on save button, data should be updated into datagridview at run-time.
2.By selecting complete row and clicking on edit button, data should be retrieved into textboxes.
3.By clicking on Update button, that data should be updated.
4.By selecting a complete row, the row should be deleted.
This is my code.
I hope it will help you
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace LINQ_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
LINQtestDataContext dc = new LINQtestDataContext();
public void show_data()
{
dataGridView1.DataSource = (from t in dc.LinqTests
select t);
}
public void insert_data()
{
try
{
LinqTest tbl = new LinqTest
{
ID=Convert.ToInt32(textBox_id.Text),
Name=textBox_name.Text
};
dc.LinqTests.InsertOnSubmit(tbl);
dc.SubmitChanges();
MessageBox.Show("Data Inserted!!!");
show_data();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void update_data()
{
try
{
LinqTest tbl = dc.LinqTests.Single(x=>x.ID==Convert.ToInt32(textBox_id.Text));
tbl.Name = textBox_new_name.Text;
dc.SubmitChanges();
MessageBox.Show("Data Updated!!!");
show_data();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void delete_data()
{
try
{
LinqTest tbl = dc.LinqTests.Single(x => x.ID == Convert.ToInt32(textBox_id.Text));
dc.LinqTests.DeleteOnSubmit(tbl);
dc.SubmitChanges();
MessageBox.Show("Data Deleted!!!");
show_data();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
show_data();
}
private void button_insert_Click(object sender, EventArgs e)
{
insert_data();
}
private void button_update_Click(object sender, EventArgs e)
{
update_data();
}
private void button_delete_Click(object sender, EventArgs e)
{
delete_data();
}
}
}

problem with lock in thread &managment lock

i have problem in this code in the comment area "hang the form"
my program will hang there!!!! what is problem??
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication28
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
BackgroundWorker backgw = new BackgroundWorker();
private void button1_Click(object sender, EventArgs e)
{
backgw.DoWork += new DoWorkEventHandler(k_DoWork);
ParameterizedThreadStart start = new ParameterizedThreadStart(startthread);
System.Threading.Thread u;
int i = 0;
while (i < 100)
{
//u = new System.Threading.Thread(start);
//u.Start(i); //1.with thread way
backgw.RunWorkerAsync(i); //2.with backgw way
Thread.Sleep(1000);
lock (y)
{
Thread.Sleep(1000);
}
lock(h)
i++;
}
}
delegate void j(int h);
j b;
object h = new object();
object y = new object();
void startthread(object m)
{
Monitor.Enter(h);
Monitor.Enter(y);
p1((int)m);
Monitor.Exit(h);
}
void p1(int h)
{
b = delegate(int q)
{
label1.Text = string.Format("Step is :{0}", h.ToString());
};
Monitor.Exit(y);
label1.Invoke(b); //hang the form????
}
void k_DoWork(object sender, DoWorkEventArgs e)
{
Monitor.Enter(h);
Monitor.Enter(y);
p1((int)e.Argument);
Monitor.Exit(h);
}
}
}
Invoke waits for the function to return. The UI thread will be running the loop for a few minutes, the worker thread will be waiting for the UI thread to invoke and return.
Use BeginInvoke to put the task on the UI thread without blocking.

Detect Autoscrollposition value change in panel

How to detect if the Autoscrollposition value changes in the panel1?
For example,
textbox1 and textbox2.
which added in panel1. The autoscroll property is set to true.
I am only interested in detecting when the value of panel autoscrollposition changes.
The above for dynamic textboxes which are incremented.
Software in use: C#, Visual Studio 2005.
The Component required for it. is:
ListBox1
ListBox2
Panel
Button.
The Namespace for Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
Here is the Complete Solution Code:
namespace detectpanelvalue
{
public partial class Form1 : Form
{
private Point tbpoint = new Point(10, 14);
private Point tbbpoint = new Point(300, 14);
private ArrayList arylst;
private ArrayList arylst1;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.Paint += new PaintEventHandler(panel1_Paint);
}
void panel1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Point pnlpt;
pnlpt = panel1.AutoScrollPosition;
if (tbpoint !=null || pnlpt != null )
{
pnlpt = tbpoint;
}
arylst1 = new ArrayList();
arylst1.Add(pnlpt);
}
private void runtime()
{
foreach (Point pt in arylst)
{
listBox1.Items.Add(pt);
}
foreach (Point ptt in arylst1)
{
listBox2.Items.Add(ptt);
}
}
private void button1_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Location = tbpoint;
this.panel1.Controls.Add(tb);
tbpoint.Y += 30;
TextBox bb = new TextBox();
bb.Location = tbbpoint;
this.panel1.Controls.Add(bb);
tbbpoint.Y += 30;
arylst = new ArrayList();
arylst.Add(tbpoint);
runtime();
}
}
}
It is helpful for adjust the panel autoscrollposition.

Resources