Close dialog, when pressed OK button on it - c#

If the user clicks on a button, a dialog shows up, asking to input a string, and there's an 'OK' button on the same dialog, when the user presses that, the dialog should close. That's at least the plan, the problem is: after adding the eventhandler to the OK button, my application freezes, when the user would open the dialog.
addNewFamButton = FindViewById<Button>(Resource.Id.newFamilyButton);
addNewFamButton.Click += (sender, e) => {
Dialog dialog = new Dialog(this);
dialog.SetContentView(Resource.Layout.addNewFamily);
dialog.SetTitle("Add new family to the list");
dialog.Show();
// Problem starts here:
Button saveNewFamily = FindViewById<Button>(Resource.Id.dialogButtonOK);
saveNewFamily.Click += (object o, EventArgs ea) => { dialog.Dispose(); };
};
I tried it with dialog.Cancel() too, but I got the same results. If I remove the last two lines, the dialog works, but obviously won't close.
FIXED: Thanks to user370305 for the simple solution:
Button saveNewFamily = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);

Your OK button is part of Dialog view, so you have to find that view using your dialog object reference, something like, (I am not familiar with xamarin but this one gives you hint)
Change your line,
// Problem starts here:
Button saveNewFamily = FindViewById<Button>(Resource.Id.dialogButtonOK);
with
Button saveNewFamily = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);

try this
// create an EditText for the dialog
final EditText enteredText = new EditText(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title of the dialog");
builder.setView(enteredText);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
// perform any operation you want
enteredText.getText().toString());// get the text
// other operations
dialog.cancel(); // close the dialog
}
});
builder.create().show();

Related

How do I open another window (Form) when a button is pressed?

Complete C# beginner here, just wondering how to open an existing form from within the current form, and close the first one. I have literally no code yet so any help is much appreciated
I had a bit of a mess around, of course not knowing anything. Something like this is about all I tried just going off of intellisense prompts:
Application.Run(Terry2);
It obviously didn't work. Here was the error
Error CS0119 'Window2' is a type, which is not valid in the given context.
I have no idea where to start so thanks in advance for the help. I am using Visual Studio 2022.
Actually there are plenty of examples for this code on the internet, first you should create both of your forms and then just create an instance of your form2 in form1 under the event of your form1's button and call it's Show() method.
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog(); // Shows Form2 you can also use f2.Show()
}
Here is a step by step explenation of the process that you should follow. I recommend you to watch some fundamental c# programming tutorials as well.
Click Here
If you've used windows for some time, you've noticed that there are two types of Dialog Boxes (forms): Modal and Modeless Dialog Boxes
Modal dialog boxes: while this one is being shown, you cannot use the other dialog boxes of the application; you'll have to finish this one before you can continue using your application. Example: File Open dialog box.
Modeless Dialog Box. A kind of dialog box that gives some extra information next to the other dialog box of your application. While this one is being shown, you can switch back to your original dialog box and enter some input.
How to show a modal dialog box
For this, you use Form.ShowDialog
In your form:
private DialogResult AskFileName()
{
using (Form myForm = new SaveFileDialog();
{
// Before showing the dialog box, set some properties:
myForm.Title = "Save file";
myForm.FileName = this.DefaultFileName;
myForm.ValidateNames = true;
...
// show the file save dialog, and wait until operator closes the dialog box
DialogResult dlgResult = myForm.ShowDialog(this);
// if here, you know the operator closed the dialog box;
return dlgResult;
}
}
private void SaveFile()
{
DialogResult dlgResult = this.AskFileName();
switch (dglResult)
{
case DialogResult.Ok:
// File is saved:
this.HandleFileSaved();
break;
case DialogResult.Cancel();
// operator pressed cancel
this.ReportFileNotSaved();
break;
...
}
}
A form is disposable, hence you should use the using statement. After creation of the form you have time to set the properties. The form is shown using ShowDialog. While this dialog box is shown, your form can't get the focus. After the operator closes the dialog box, your form gets the focus again. The return value of ShowDialog indicates the result.
If you want to save the file as a result of the operator selecting the menu item "file save", or pressing the button "Save", do the following:
private void OnMenuItemFileSave_Clicked(object sender, ...)
{
this.SaveFile();
}
private void OnButtonSave_Clicked(object sender, ...
{
this.SaveFile();
}
How to show a modeless Dialog Box
A modeless dialog box is shown using Form.Show. After you call this, your dialog box can get the focus. Therefore you'll have to remember that the form is being shown.
class MyModelessDialogBox : Form {...}
class MyForm : Form
{
private MyModelessDialogBox {get; set;} = null;
private void ShowMyModelessDialogBox()
{
if (MyModelessDialogBox != null)
{
// Dialog box already shown, TODO: report to operator?
...
return;
}
else
{
// Dialog box not shown yet; create it and show it
this.MyModelessDialogBox = new MyModelessDialogBox();
// if needed, before showing set some properties
// make sure you get notified if the dialog box is closed
this.MyModelessDialogBox.FormClosed += new FormClosedEventHandler(this.MyModelessDialogBoxClosed);
// show the dialog box:
this.MyModelessDialogBox.Show(this); // I am the owner / parent window
}
// when the modeless dialog box is closed, you get notified:
void MyModelessDialogBoxClosed(object sender, FormClosedEventArgs e)
{
// if needed, inspect e.CloseReason
// if needed, handle the DialogResult
// finally: not my form anymore. The form should disposes itself:
this.MyModelessDialogBox = null;
}
}
}
}
Before closing your form you should check if the dialog box is being shown, and close:
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
if (this.MyModelessDialogBox != null)
{
// the modeless dialog box is being shown. Order it to close itself:
this.MyModelessDialogBox.Close();
// this will lead to MyModelessDialogBoxClosed
}
}
Sometimes you have a dialog box that refuses to close, for instance because the dialog box warns the operator and he clicks cancel. In that case, you should not Close the dialog box directly, but add a method to ask the dialog box nicely.
In the dialog box:
bool RequestToClose()
{
bool allowedToClose = this.AskOperatorIfCloseAllowed();
if (allowedToClose)
{
// close this dialog box.
this.Close();
// the owner of the dialog box will be notified via MyModelessDialogBoxClosed
}
return allowedToClose;
}

FindViewById not displaying id

I have a button that I want to clear certain fields after it is pressed. I have a button event that is supposed to display a question before the clear functionality is implemented. After the user confirms they want to clear the button then the button will clear the text in the fields. However, as of now the dialog isn't displaying. Below is a sample of my Clear Button function. Please let me know if you see anything I am not seeing.
void btnPalletClear_Click(object sender, EventArgs e)
{
dialog = new Dialog(this, Android.Resource.Style.ThemeHoloLightDialogNoActionBarMinWidth);
View myView = View.Inflate(this, Resource.Layout.confirmation_dialog, null);
myView.FindViewById<TextView>(Resource.Id.txtConfirmTitle).Text = "Clear Pallet";
myView.FindViewById<TextView>(Resource.Id.txtConfirmMessage).Text = "Are you sure?";
myView.FindViewById<LinearLayout>(Resource.Id.llQuantity).Visibility = ViewStates.Gone;
myView.FindViewById<Button>(Resource.Id.cmdConfirmCancel).Click += delegate { dialog.Dismiss(); };
myView.FindViewById<Button>(Resource.Id.cmdConfirmOK).Click += delegate
{
dialog.SetContentView(myView);
dialog.Show();
txtPalletUNQ.Text = "";
adapter.lstPallet.Clear();
adapter.NotifyDataSetChanged();
txtPalletVTPID.Text = "";
};
}
I cut the dialog.SetContentView(myview), and dialog.Show() out and pasted it in outside of the cmdConfirmOk and it fixed it.

non-responsive close button in winform

I'm trying to make an Option dialog in Visual Studio. I hid the default ControlBox and made a close button. The dialog work, but the close button isn't. Here's the code:
public static class dialog
{
static Form gotoBox = new Form();
public static void showDialog()
{
Button closeButton = new Button() { Text = "Close" };
gotoBox.Controls.Add(closeButton);
gotoBox.ControlBox = false;
gotoBox.ShowDialog();
closeButton.Click += new System.EventHandler(gotoBox_close);
}
static void gotoBox_close(object sender, EventArgs e)
{
gotoBox.Close();
}
}
When I click the button, nothing happen. So what did I do wrong?
gotoBox.ShowDialog(); //This line shows the dialog
//The rest doesn't execute until ShowDialog returns
closeButton.Click += new System.EventHandler(gotoBox_close);
You need to move the event registration before the show dialog or else it will not have any effect until dialog is closed

Xamarin dismiss popup window

I have an issue , when SavedAyasListView_ItemLongClick event fires, a popupwindow appears with some buttons, and my intention is whenever i click btnDeleteAya button , perform some actions and dismiss the popup.
When the event fires, the popup appears and when i click the btnDeleteAya the action gets performed and the popup disappears, but when i do the same thing again the popup window doesnt get closed.
I want it to get closed each time i click the btnDeleteAya button not by just clicking outside because that part works as expected.
Here's the code:
public string itemclicked;
PopupWindow mpopup;
private void SavedAyasListView_ItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e)
{
View popUpView = LayoutInflater.Inflate(Resource.Layout.SavedAyasPopupMenu,
null); // inflating popup layout
mpopup = new PopupWindow(popUpView, 800, 500); // Creation of popup
mpopup.SetBackgroundDrawable(new BitmapDrawable());
mpopup.OutsideTouchable = true;
mpopup.Focusable = true;
mpopup.ShowAtLocation(popUpView, GravityFlags.Center, 10, 50);
itemclicked = savedAyasListView.GetItemAtPosition(e.Position).ToString();
Button btnDeleteAya = popUpView.FindViewById<Button>(Resource.Id.btnDeleteAya);
btnDeleteAya.Click += BtnDeleteAya_Click;
btnDeleteAya.Click += delegate
{
mpopup.Dismiss();
};
Button fbShareSavedAya = popUpView.FindViewById<Button>(Resource.Id.fbShareSavedAya);
fbShareSavedAya.Click += FbShareSavedAya_Click;
}

Windows phone7 custom messagebox with a popup

In my application I have created a custom messagebox(with a different backgroud color) using a Popup. There it has a button and I have implemented the button click event.
With in the button click, it has a message box and according to "Ok" or "Cancel" it performs the operation from there onwards.
The problem is after I click the button in the popup(custom messagebox), the message box loads, but still the popup(custom messegebox) appear in the background. I need the custom popup to close entirely and to perform operations. Therefore I have used popup.IsOpen = false; as the first statement within button click, but still it appears in the background untill it finish the entire button click event. I searched for other properties, but didn't find any working.
following is the code
Popup popup = new Popup();
popup.Height = 300;
popup.Width = 480;
popup.VerticalOffset = 100;
CustomMessageBox control = new CustomMessageBox();
popup.Child = control;
popup.IsOpen = true;
this.IsEnabled = false;
control.OK_BTN.Click += (s, args) =>
{
popup.IsOpen = false;
this.IsEnabled = true;
MessageBoxResult result = MessageBox.Show("Do you want to reset the settings ?", "Settings", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
changeSettings();
}
};
Any suggestion to achieve this is highly appreciated. Thanks...!!!
The reason this happens is because all of this is happening on the UI thread which is getting blocked until you return. Until your button handler returns, no updates to the UI will happen.
If you really want the popup to disappear first, you would need to do something like
control.OK_BTN.Click += (s, args) =>
{
popup.IsOpen = false;
this.IsEnabled = true;
Dispatcher.BeginInvoke(() =>
{
MessageBoxResult result = MessageBox.Show("Do you want to reset the settings ?", "Settings", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
changeSettings();
}
});
};
That would force the MessageBox to be opened after your button handler returns. But are you sure you want the popup to disappear first? What if the user clicks cancel on the message box? Typically the message box appears directly on top of whatever invoked it and doesn't replace it.
I was just typing what Negative Eddy wrote.
Using Dispatcher.BeginInvoke will work! I tested it, works perfectly. I don't have enough rep to comment on his apparently.

Categories