I want to cancel the loading and not show the window if my else statement executes in the loaded event. See the code below.
private void OpenTradesLoaded(object sender, RoutedEventArgs e)
{
if (OpenTradesQuery.Count() > 0)
{
numOfrecords = OpenTradesQuery.Count();
DataContext = this;
foreach (var rowObj in OpenTradesQuery)
{
row = SourceTable.NewRow();
SourceTable.Rows.Add(rowObj.TraderID, rowObj.ClientTradedDate, rowObj.ClientTradedTime, rowObj.ClientName, rowObj.CurrencyPair, rowObj.TradedAmount, rowObj.Action, rowObj.ExecutedRate);
}
}
else
{
Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
MeBox.Show("You have no open trades.", "", MessageBoxButton.OK, MessageBoxImage.Error);
**//Cancel Loading here and do not show window**
}
}
You can use this property:
public bool ShouldLoad
{
get { return OpenTradesQuery.Count() > 0; }
}
And when you want to open, ask if should open:
MyPage mypage = new MyPage();
if (mypage.ShouldLoad)
{
mmypage.Show();
}
else
{
MeBox.Show("You have no open trades.", "", MessageBoxButton.OK,
MessageBoxImage.Error);
}
With this code, you can check before loading if it really should load.
I just used
this.Close();
works fine.
Related
I created a project in C# windows form application in visual studio 2010 and .net framework version 4.0.
In my project Main form contains another form which name is Communication.
Communication form has five combo box for COM Port settings and Connect button.
When I select Items from Combo box drop down list and click on connect button then text on button shows disconnect. Then I will close Communication form.Comport gets connected.
My main problem is that, when I reopen form for disconnect communication. I want same Items in combo box and text on button shows Disconnect as before.
I don't know how to do this. Please help me to solve this issue. Thanks in advance.
Code for Communication form
public partial class Connect : Form
{
public bool Connect_Status = false;
public Connect()
{
InitializeComponent();
COM_List();
}
private void COM_List()
{
for (int i = 0; i < CommPortManager.Instance.GetCommList().Count; i++)
{
cb_CommPort.Items.Add(CommPortManager.Instance.GetCommList()[i]);
}
}
private void btn_Connect_Click(object sender, EventArgs e)
{
CommPortManager.Instance.PortName = cb_CommPort.Text;
CommPortManager.Instance.BaudRate = cb_BaudRate.Text;
CommPortManager.Instance.Parity = cb_Parity.Text;
CommPortManager.Instance.StopBits = cb_StopBits.Text;
CommPortManager.Instance.DataBits = cb_DataBits.Text;
if ((cb_CommPort.Text == "") || (cb_BaudRate.Text == "") || (cb_Parity.Text == "") || (cb_DataBits.Text == "") || (cb_StopBits.Text == ""))
{
MessageBox.Show("Please select all communication settings and then Save", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
Connect_Status = false;
}
else
{
if (CommPortManager.Instance.COM_Open() == false)
{
MessageBox.Show("Could not open the COM port. Most likely it is already in use, has been removed, or is unavailable.", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
Connect_Status = false;
}
else
{
CommPortManager.Instance.COM_Close();
Connect_Status = true;
btn_Connect.Text = "Disconnect";
}
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
And Code for main form where this communication form open
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
Connect connect = new Connect();
connect.ShowDialog();
if (connect.Connect_Status == true)
{
lb_Comm.Text = String.Format("Connected to '{0}'", connect.cb_CommPort.SelectedItem);
}
else
{
CommPortManager.Instance.COM_Close();
lb_Comm.Text = "Not Connected";
}
}
You have to create a Serializable class in which you will be saving the indexes of combo boxes.
[Serializable]
class SaveComboSettings
{
[OptionalField]
public int cmb1SelectedIndex = 0;
[OptionalField]
public int cmb2SelectedIndex = 0;
}
At the time of closing the form, You need to serialize the combo boxes's index in this class's object. Like -
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//Assigning the current selected index of combobox to serialize class.
SaveComboSettings f1 = new SaveComboSettings();
f1.cmb1SelectedIndex = this.comboBox1.SelectedIndex;
f1.cmb2SelectedIndex = this.comboBox2.SelectedIndex;
//Serialize
BinaryFormatter bf = new BinaryFormatter();
FileStream fsout = new FileStream("ComboBoxSettings.binary", FileMode.Create, FileAccess.Write, FileShare.None);
try
{
using (fsout)
{
bf.Serialize(fsout, f1);
}
}
catch (Exception Ex)
{
//Some Exception occured
}
}
When form is loaded back/restart, You need to deserialize the settings and assign the combo box values back -
public Form1()
{
InitializeComponent();
DeserializeFormSettings();
}
public void DeserializeFormSettings()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fsin;
if(File.Exists("ComboBoxSettings.binary"))
fsin = new FileStream("ComboBoxSettings.binary", FileMode.Open, FileAccess.Read, FileShare.None);
else
return;
try
{
using (fsin)
{
SaveComboSettings f1 = (SaveComboSettings)bf.Deserialize(fsin);
this.comboBox1.SelectedIndex = f1.cmb1SelectedIndex;
this.comboBox2.SelectedIndex = f1.cmb2SelectedIndex;
}
}
catch(Exception Ex)
{
// "An error has occured";
}
}
This example is created with combo box only. You can use the same way for string on button also.
Our application requires that a witness must authenticate before a logged in user can perform enrollment operations (Enroll and Delete).
This is not an issue for Enrolling as I can add a check (IsWitnessApproved) to an enrollment_OnStartEnroll method I.E. before the Capture method is called and fired.
However, this is not possible for Deletion as I don't have access to a point where the enrollment_OnDelete method hasn't fired.
I haven't been able to get a response to this issue from Digital Persona so I'm now looking at work-arounds.
I'm exploring if its possible to open up a new form (WitnessApproval) inside the enrollment_OnDelete method, approve the witness in the form (btnConfirmWitness_Click) and then come back into the method and continue on with the deletion?
enrollment_OnDelete method:
private void enrollment_OnDelete(DPCtlUruNet.EnrollmentControl enrollmentControl, Constants.ResultCode result, int fingerPosition)
{
if (!witnessApproved)
{
WitnessApproval witnessApproval = new WitnessApproval();
witnessApproval.Show();
}
else
{
int fingerMask = GetFingerMask(fingerPosition);
if (enrollmentControl.Reader != null)
{
try
{
// Delete from database
new EnrollmentDAL().DeleteEnrolledFingerprint(Settings.Default.Username, fingerMask, txt_WitnessName.Text);
MessageBox.Show("Fingerprint deleted.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
pbFingerprint.Image = null;
pbFingerprint.Visible = false;
btnCancel.Visible = false;
witnessApproved = false;
txt_WitnessName.Text = String.Empty;
txt_WitnessPassword.Text = String.Empty;
}
catch (Exception ex)
{
MessageBox.Show("There was a problem deleting the fingerprint.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
new Util().LogError(ex);
}
}
else
{
MessageBox.Show("No Reader Connected.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
_sender.Fmds.Remove(fingerPosition);
}
}
Selected WitnessApproval methods:
private void btnConfirmWitness_Click(object sender, EventArgs e)
{
lbl_Validation.Visible = false;
if (txt_WitnessName.Text == String.Empty)
{
SetMessage("Please enter a Witness.");
return;
}
if (txt_WitnessPassword.Text == String.Empty)
{
SetMessage("Please enter a Password.");
return;
}
if (txt_WitnessName.Text == Settings.Default.Username)
{
SetMessage("User and witness cannot be the same.");
return;
}
bool IsValidate = Membership.ValidateUser(txt_WitnessName.Text, txt_WitnessPassword.Text);
Settings.Default.WitnessName = txt_WitnessName.Text;
Settings.Default.WitnessPassword = txt_WitnessPassword.Text;
if (IsValidate)
{
this.Close();
// Allow enrollment operations
}
else
{
SetMessage("Witness credentials invalid.");
}
}
private void btnCancelWitness_Click(object sender, EventArgs e)
{
this.Close();
// DO NOT Allow enrollment operations
witnessCancelled = true;
}
private void SetMessage(string message)
{
lbl_Validation.Visible = true;
lbl_Validation.Text = message;
}
How to open form inside method, submit button and then come back to original method and continue?
There is ShowDialog method for this purposes.
Here is usage example from MSDN:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
In your case, Form2 is WitnessApproval.
In WitnessApproval Form button handlers you will also need to set DialogResult to true when the witness is approved or to false when user cancelled operation.
I want to open the StdinfoPage page after clicking the Go to Admin button on the message box
how can i do that?
here is my button coding
private void button_login_Click(object sender, RoutedEventArgs e)
{
if (MyReader.HasRows && this.Frame != null)
{
while (MyReader.Read())
{
if (privilege == 1)
{
DisplayMsgBox("click to open the admin page ", "Go to Admin");
this.Frame.Navigate(typeof(StdinfoPage));
}
else
{
DisplayMsgBox("privilege 0", "ok");
}
}
}
else
{
DisplayMsgBox("sucess else", "ok");
}
conn.Close();
}
}
here is message box code
private async void DisplayMsgBox(string displayMsg, string displayBtn)
{
try
{
// Create the message dialog and set its content
var messageDialog = new MessageDialog(displayMsg);
// Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
messageDialog.Commands.Add(new UICommand(displayBtn, new UICommandInvokedHandler(this.CommandInvokedHandler)));
messageDialog.Commands.Add(new UICommand("Close", new UICommandInvokedHandler(this.CommandInvokedHandler)));
// Set the command that will be invoked by default
messageDialog.DefaultCommandIndex = 0;
// Set the command to be invoked when escape is pressed
messageDialog.CancelCommandIndex = 1;
// Show the message dialog
await messageDialog.ShowAsync();
}
catch (Exception)
{
}
}
Based on the example from here: http://msdn.microsoft.com/library/windows/apps/windows.ui.popups.messagedialog.aspx, you need to create this method that will be executed when Go to Admin or Close button is clicked
private void CommandInvokedHandler(IUICommand command)
{
// Check which button is clicked
if (command.Label == "Go to Admin")
{
// open StdinfoPage
this.Frame.Navigate(typeof(StdinfoPage));
}
}
and delete this.Frame.Navigate(typeof(StdinfoPage)); inside if (privilege == 1) block
if (privilege == 1)
{
DisplayMsgBox("click to open the admin page ", "Go to Admin");
}
I have another WPF Window i've created.. say window2.xaml. I have a button.. and on click i want it to load that window.. i've tried Googling but nothing seems to be working. It just loads a blank page. I know this is really simple, but I really can't find how to do it through my searches.
This is what i have tried:
GameClock temp = new GameClock();
temp.ShowDialog(); //just shows blank window
temp.Show(); //just shows a blank window too
EDIT: I figured out the problem. I took out the initialize component because there an an error. I thought it was something only the main window needed. When I put it back, it works. Thanks, everyone.
try this... u can use like a generic methode
private void button_ItemClick(object sender, ItemClickEventArgs e)
{
try
{
OpenWin("window2", new Uri(#"window2.xaml", UriKind.Relative), "Window2Label");
}
catch (Exception ex)
{
Message.Show(ex);
}
}
public static DocumentPanel OpenWin(string namePainelItem, Uri xamlPath, string caption = "", RoutedEventHandler unloadEvent = null, bool closeOpenWin = false)
{
try
{
if (closeOpenWin)
{
CloseWin(namePainelItem, false);
}
DocumentPanel panel1 = GetWin(namePainelItem);
if (panel1 == null)
{
panel1 = new DocumentPanel();
panel1.Caption = caption;
panel1.Name = namePainelItem;
panel1.Content = xamlPath;
if (unloadEvent != null)
{
panel1.Unloaded += unloadEvent;
}
hdl.dockLayoutManager.DockController.Insert(hdl.documentGroup1, panel1, 1);
hdl.dockLayoutManager.DockController.ActiveItem = panel1;
}
else
{
if (panel1.Visibility != Visibility.Visible)
panel1.Visibility = Visibility.Visible;
if(panel1.IsClosed)
panel1.Closed = false;
hdl.dockLayoutManager.DockController.ActiveItem = panel1;
}
return panel1;
}
catch (Exception ex)
{
Message.Show(ex);
}
return new DocumentPanel();
}
public static void CloseWin(string namePainelItem)
{
try
{
BaseLayoutItem item = hdl.dockLayoutManager.GetItem(namePainelItem);
if (item != null)
{
hdl.documentGroup1.Items.Remove(item);
hdl.dockLayoutManager.DockController.RemovePanel((DocumentPanel)item);
item = null;
}
}
catch (Exception ex)
{
Message.Show(ex);
}
}
You may need to read the XAML file before creating the instance of GameClock. Something like this:
GameClock clock;
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
clock = (GameClock)XamlReader.Load(fs);
JAB
I have one MDIPrent Form that is my main form. Now I am logging out form Main_Form by clicking LogOut MenuStrip. In my code I have prevented duplicate instance. But I get this error. I have googled so much, tried so many things but error doesn't go away.
Below is code for Program.cs file:
using System.Diagnostics;
static class Program
{
[STAThread]
static void Main()
{
LoggedInUser = string.Empty;
loginSuccess = false;
String thisprocessname = Process.GetCurrentProcess().ProcessName;
if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
return;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MyApplicationContext context = new MyApplicationContext();
Application.Run(context);
}
public class MyApplicationContext : ApplicationContext
{
private Login_Form lgFrm = new Login_Form();
public MyApplicationContext()
{
try
{
lgFrm.ShowDialog();
if (lgFrm.LogonSuccessful)
{
////lgFrm.Close();
lgFrm.Dispose();
FormCollection frm = Application.OpenForms;
try
{
foreach (Form fc in frm)
fc.Close();
}
catch (Exception ex){}
Application.Run(new Main_Form());
}
}
catch (Exception ex){}
}
}
}
Below is the code for Login_Form
public bool LogonSuccessful
{
get
{
return Program.loginSuccess;
}
set
{
Program.loginSuccess = value;
}
}
private void BtnEnter_Click(object sender, EventArgs e)
{
Login_Form lgn = new Login_Form();
Program.loginSuccess = true;
this.Hide();
Program.LoggedInUser = TxtBxUserName.Text;
}
Below is for Main_Form
private void LogOutMenuItem_Click(object sender, EventArgs e)
{
Login_Form lgFrm = new Login_Form();
lgFrm.LogonSuccessful = false;
Program.loggedOut = true;
Program.LoggedInUser = string.Empty;
this.Close();
////FormCollection frm = Application.OpenForms;
////foreach (Form fc in frm)
////{
//// MessageBox.Show(fc.ToString());
////}
Program.MyApplicationContext context = new Program.MyApplicationContext();
Application.Run(context);
}
I have used context, because I want to make Main_Form, the only OpenForm of application. Somewhere I got the idea of using the context.
Your exception is because you call Application.Run(...) inside another Application.Run(...), modify as follow:
//MyApplicationContext constructor
public MyApplicationContext()
{
try
{
lgFrm.ShowDialog();
if (lgFrm.LogonSuccessful)
{
////lgFrm.Close();
lgFrm.Dispose();
FormCollection frm = Application.OpenForms;
try
{
foreach (Form fc in frm)
fc.Close();
}
catch (Exception ex){}
//Application.Run(new Main_Form()); <<<---- Remove this
MainForm = new Main_Form();
}
}
catch (Exception ex){}
//Add the ThreadExit event handler here
ThreadExit += (s,e) => {
if(Program.loggedOut) {
Program.MyApplicationContext ctxt = new Program.MyApplicationContext();
Application.Run(ctxt);
}
};
}
}
//
private void LogOutMenuItem_Click(object sender, EventArgs e)
{
Login_Form lgFrm = new Login_Form();
lgFrm.LogonSuccessful = false;
Program.loggedOut = true;
Program.LoggedInUser = string.Empty;
this.Close(); //I think you want to call Application.Restart() here?
//if so, you don't need the ThreadExit event handler added in the MyApplicationContext() constructor.
}
try this: instead of firing a new application when logging off, just dispose your window and replace MyApplicationContext() in this:
public MyApplicationContext()
{
bool isSuccessful = false;
do
{
try
{
lgFrm = new Login_Form();
lgFrm.ShowDialog();
if (lgFrm.LogonSuccessful)
{
isSuccessful = lgFrm.LogonSuccessful;
////lgFrm.Close();
lgFrm.Dispose();
FormCollection frm = Application.OpenForms;
try
{
foreach (Form fc in frm)
fc.Close();
}
catch (Exception ex){}
Application.Run(new Main_Form());
}
}
catch (Exception ex){}
}while(isSuccessful);
}
i had the same problem
the best way to solve this is Using
Application.Restart();
you should Use it when ever a User Log out , so the main UI close
and the log in dialog appear !!
but with Log in Form U gotta use this
ControlBox = False;
so the User can't bypass it by closing it!!
Simply U can add an Exit Button with code
Application.Exit();
this is how i solved this problem with out any additional Usings or Errors ...