I'm trying to create a dialog where the user gets to choose between some buttons, but the problem I'm experiencing now is that when the user closes the window (not choosing a button but using the x on the top right corner), the application shows the message but after that it crashes. Does anybody know what I am doing wrong here?
MainWindow.xaml.cs
public partial class MainWindow : Window
{
string[,] suppliers = new string[3,2] {{"xxx", "xxx"}, {"yyy", "yyy"}, {"zzz" , "zzz"}};
public MainWindow()
{
InitializeComponent();
ButtonPrompt buttonPrompt = new ButtonPrompt(suppliers, "Select supplier.");
while (buttonPrompt.ShowDialog() != true)
{
MessageBox.Show("Please choose one of the suppliers!");
}
}
}
ButtonPrompt.xaml.cs:
public partial class ButtonPrompt : Window
{
public ButtonPrompt(string[,] buttons, string question)
{
InitializeComponent();
buttonStack.Children.Clear();
TextBlock questionBlock = new TextBlock();
questionBlock.Text = question;
buttonStack.Children.Add(questionBlock);
for (int i = 0; i < buttons.GetLength(0); i++)
{
Button inputButton = new Button();
inputButton.Name = buttons[i, 0];
inputButton.Content = buttons[i, 1];
inputButton.Width = 200;
inputButton.Height = 60;
inputButton.Click += inputButton_Click;
buttonStack.Children.Add(inputButton);
if (i == 0)
{
inputButton.Focus();
}
}
}
private void inputButton_Click(object sender, RoutedEventArgs e)
{
Button inputButton = (Button)sender;
this.DialogResult = true;
}
private void Window_Closed(object sender, EventArgs e)
{
this.DialogResult = false;
}
}
Thanks in advance!
The buttonPrompt.ShowDialog() returns true when the Window is closed.
Documentation says about the Window_Closed
Once this event is raised, a window cannot be prevented from closing.
This means that you cannot set the DialogResult because it's already true and your while doesn't work.
You have three possibilities:
Override the OnClosing method like in How to override default window close operation? to prevent the window is closed from the GUI Button.
(My favourite) Override the OnClosing event like in http://msdn.microsoft.com/it-it/library/system.windows.window.closing.aspx checking for your own conditions and adding this.DialogResult = false
Hide the close button of you Dialog Window from the XAML setting WindowStyle=None
Update: On the other side, put your while check out of your Main Window initialization, try with the Loaded handler so you're sure your Main component doesn't have troubles while coming up.
Related
I implement a form for handle excel file when click button "Start".
Event click Start button:
private void btnImport_Click(object sender, EventArgs e)
{
showFormSelectLanguage();
if (CheckSheetFile() == true) {
using (WaitingForm frm = new WaitingForm(handleExcel))
{
frm.ShowDialog(this);
}
var dialogMessage = new DialogMessage();
dialogMessage.ShowDialog(this);
} else
{
ShowDialogNotFoundSheet();
}
}
showFormSelectLanguage method display dialog for select language:
private void showFormSelectLanguage()
{
var formSelectLanguage = new FormSelectLanguage();
formSelectLanguage.ShowDialog(this);
}
ShowDialogNotFoundSheet function for check sheet excel exist:
private void ShowDialogNotFoundSheet()
{
var dialogNotFoundSheet = new DialogNotFoundSheet();
dialogNotFoundSheet.setTextContent("Not found sheet");
dialogNotFoundSheet.ShowDialog(this);
}
Event click confirm select language button at Select language form:
private void btnConfirmLanguage_Click(object sender, EventArgs e)
{
//close dialog
this.Close();
}
Event click Close button for close DialogNotFoundSheet form:
private void btnCloseDialogNotFoundSheet_Click(object sender, EventArgs e)
{
this.Close();
}
CheckSheetFile method:
private bool CheckSheetFile()
{
var isCorrectFile = false;
try
{
xlWorkBook = xlApp.Workbooks.Open(txtFilePath.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read);
var xlWorkBook1 = xlWorkBook.Sheets["SheetName"];
isCorrectFile = true;
}
catch (Exception e)
{
return false;
}
return isCorrectFile;
}
Issue:
When I click Close button at DialogNotFoundSheet form. Then FormSelectLanguage from still display. It repeats. How can resolve it?
Expected 2 forms can close
Thanks!
Update:
All References btnImport_Click:
UI:
I don't exactly know what you did with btnImport_Click, but if your purpose is to disable the function of a button at a time and to enable it at another time, actually you don't have to register or unregister the click event, you can simply set button's Enabled propety.
//btnImport.Click += btnImport_Click;
btnImport.Enabled = true;
//btnImport.Click -= btnImport_Click;
btnImport.Enabled = false;
My guess of the reason of this loop is that you have called += btnImport_Click many times, but -= btnImport_Click is never (or less) run.
For instance if you do:
btnImport.Click += btnImport_Click;
btnImport.Click += btnImport_Click;
Each time btnImport is clicked, btnImport_Click will get invoked twice.
I have a WinForm popping up within a WinForm. If I close the inner Winform and reopen it, the text in the textbox doesn't highlight. However if I close both WinForms and reopen the first and then the inner WinForm, the text in the textbox will highlight.
How can I get the inner WinForm text to highlight every time?
I have tried the 2 ways I know of / most common ways of highlighting the text but they seem to only work the first time around.
Any and all help/direction is appreciated.
The inner winforms is being called from a .ShowDialog(); in the outer Winforms.
portalTitleEntryForm.ShowDialog();
Here is my code of the inner Winform and what I have tried:
public partial class PortalTitleEntryForm : Form
{
public string portalEntryTitle;
public string dialogResult;
public PortalTitleEntryForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
titleTextBox.TabIndex = 0;
continueButton.TabIndex = 1;
cancelButton.TabIndex = 2;
this.CancelButton = cancelButton;
this.AcceptButton = continueButton;
titleTextBox.Focus();
if (portalEntryTitle != null || !portalEntryTitle.Equals(""))
{
titleTextBox.Focus();
titleTextBox.Text = portalEntryTitle;
/*titleTextBox.SelectionStart = 0; // doesn't work the second time
titleTextBox.SelectionLength = titleTextBox.Text.Length;*/ // doesn't work the second time
titleTextBox.SelectAll(); // doesn't work the second time
bool focusStatus = titleTextBox.Focused; // bool equals false the second
//titleTextBox.Focus(); // doesn't work the second time around
}
private void continueButton_Click(object sender, EventArgs e)
{
if (!titleTextBox.Text.Equals(""))
{
portalEntryTitle = titleTextBox.Text;
dialogResult = DialogResult.OK.ToString();
continueButton.DialogResult = DialogResult.OK;
Close();
return;
}
else if (titleTextBox.Text.Equals(""))
{
MessageBox.Show("Please give your entry a title.", "M3dida", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void cancelButton_Click(object sender, EventArgs e)
{
dialogResult = DialogResult.Cancel.ToString();
Debug.WriteLine("Cancel button was clicked");
Close();
return;
}
}
}
Form loads only once, unless it is destroyed.
You might want to handle Form.Activated event and invoke titleTextBox.Focus() in the handler.
I have a Popup that I want to always be open and its content active when a TextBox has keyboard focus. I have attempted this with this code
public partial class MyPopup : Popup
{
public MyPopup
{
InitializeComponent();
EventManager.RegisterClassHandler(
typeof(UIElement),
Keyboard.PreviewGotKeyboardFocusEvent,
(KeyboardFocusChangedEventHandler)OnPreviewGotKeyboardFocus);
}
private void OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (sender is TextBox)
this.IsOpen = true;
else
this.IsOpen = false;
}
}
were I create the Popup in the constructor of App.
The problem with this code is that if the Popup is already open when ShowDialog is used the Popup is no longer active, even though it is still visually on top.
How do I get around this or get the required behavior in another way.
Found one solution where I check if the Window is opening by checking if it has loaded. If so I close the popup and reopen it again after the new Window has had its content rendered.
Not sure it's something I trust enough to use to use so a better solution would be welcome.
private void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
e.Handled = true;
if (sender is TextBox)
{
var _parentWindow = Window.GetWindow((UIElement)sender);
if (!_parentWindow.IsLoaded)
{
this.IsOpen = false;
_parentWindow.ContentRendered += (o, i) => this.IsOpen = true;
}
else
{
this.IsOpen = true;
}
}
else
{
this.IsOpen = false;
}
}
I have a Form which holds a DataGridView, this Form also loads with an invisible Form which only holds another DataGridView. The second DGV is used to display more information on the items in the first DGV.
The second DGV should only be shown when the user clicks inside the 7th Cell of any row in the first DGV. I have already managed to get it to hide when I click other cells, but I can't seem to get it to hide when I click outside the DataGridView. I have already tried the Leave, RowLeave and LostFocus events without success. I think it is because as soon as the second DataGridView is displayed, it gets the focus and this somehow messes with the event.
Here is my code:
public class Form1
{
Form schedules = new Form();
DataGridView backups = new DataGridView();
public Form1()
{
this.schedules.Visible = false;
backups.DataBind();
}
private void backups_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1 && e.ColumnIndex == 7)
{
if (this.schedules.getData(Convert.ToInt32(backups.Rows[e.RowIndex].Cells[0].Value)))
{
this.schedules.Owner = this;
this.schedules.Visible = true;
this.schedules.changePosition(Cursor.Position);
}
else
{
this.schedules.Visible = false;
}
}
else
{
this.schedules.Visible = false;
}
}
}
public class Schedules : Form
{
DataGridView grdSchedules = new DataGridView();
public Schedules()
{
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Visible = false;
this.AutoSize = true;
this.grdSchedules.RowHeadersVisible = false;
this.grdSchedules.AllowUserToAddRows = false;
this.grdSchedules.ScrollBars = ScrollBars.None;
this.grdSchedules.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.grdSchedules.AllowUserToResizeColumns = false;
this.grdSchedules.AllowUserToResizeRows = false;
this.grdSchedules.AllowUserToDeleteRows = false;
}
}
private void Form1_Click(object sender, EventArgs e)
{
this.schedules.Visible = false;
}
Users tend to click on the biggest window they see to close popups. You can also do the same with the secondary form; or even add a close button to it.
I think you would want to combine Form Click and Grid Leave event to make it work.
private void Form1_Click(object sender, EventArgs e)
{
detailForm.Visible = false;
}
private void dataGridView1_Leave(object sender, EventArgs e)
{
detailForm.Visible = false;
}
Now if a user clicks outside Grid on form or directly into a different control, then your detail form should be hidden.
Hope it helps.
I use MDI in MainForm.cs
public Le_MainForm()
{
InitializeComponent();
this.IsMdiContainer = true;
this.Name = "MainUSER";
}
private void barButtonItem_ListeOrdres_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Close_AllForm();
Liste_Ordres f_Liste = new Liste_Ordres();
f_Liste.MdiParent = this;
f_Liste.Show();
}
private void barButtonItem_CreatOrdreAller_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Close_AllForm();
Program.AllerRetour = "Ordre Aller";
Fiche_Ordre f_Fiche = new Fiche_Ordre();
f_Fiche.MdiParent = this;
f_Fiche.Show();
}
the question now, when I am in other form Ex.:Liste_Ordres.cs or Fiche_Ordre.cs how can i redirect from Fiche_Ordre.cs into Liste_Ordres.cs and vice versa without loosing MDI ?
When I'm in Fiche_Ordres.cs to go to Liste_Ordres.cs I use:
private void simpleButton_Annluer_Click_1(object sender, EventArgs e)
{
Liste_Ordres f_Liste = new Liste_Ordres();
f_Liste.Show();
this.Close();
}
But as you can see I lose the MDI, that mean when I click the menu on MainForm, the Liste_Ordres form will disappear.
as you can see in this Video that when i redirect From Liste to fiche, and then maximize the window i lose the menu that mean i lose Mdi.
You just need to set the MdiParent again:
f_Liste.MdiParent = this.MdiParent;