Access to Message box buttons - c#

I am having a message box a simple one inside an if condition and the thing is i want the message box to automatically close when the user points to the OK button in the message box, what i am not able to figure out is how to access the message box OK button
private void button3_Click(object sender, RoutedEventArgs e)
{
Clipboard.Clear();
//string queryvalue;
//queryvalue = SelectedQuery.Value;
//SelectedQuery.Value = queryvalue;
if (QueryChooser.SelectedItem == null)
{
button3.Background = Brushes.PaleVioletRed;
MessageBox.Show("Select a value");
}
else
{
Clipboard.SetText(SelectedQuery.Value);
}
}

In cases like this I've found that it is easier to just create a simple Window resembling a MessageBox and pop it using ShowDialog(), this way you'll have a more flexible "MessageBox".

if (MessageBox.Show("Select a value") == DialogResult.Ok) {
// do something
}
UPDATE
As Saeb already mentioned you should create your own simple MessageBox dialog.

Related

How to do something after clicking on MessageBox button, but before this MessageBox closes?

I have a list of "projects" with some informations in textBoxs for each project. The user can select a project then modify the informations and click on save button after that.
If I changes selected project without save the modifications, a Yes/No MessageBox appear:
DialogResult dialogResult = MessageBox.Show(
"Do you want to save changes ?",
"Title",
MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
//Click Yes
}
else
{
//Click No
}
I would to refresh all the project list (with my own Refresh() methode) after clicking on Yes/No button, but staying on the MessageBox until the refresh is done.
Is it possible?
The built in MessageBox class does not allow such complicated behaviour.
One way to do this is to create your own message box. Create a subclass of Form, add some labels and buttons. Expose some events like YesClicked and NoClicked.
In your main form, create an instance of your custom message box, subscribe to the events, and call ShowDialog on it.
After the refresh is done, you can call Close or Dispose on your custom message box to close it.
Try creating a custom message box. I commented the code, let me know if you need clarification
public static class MessageBoxResult
{
public static int dialogResult; // <== i use this value to determine what button was pressed
}
// your custom message box form code
public partial class CustomMsgBox : Form
{
public CustomMsgBox()
{
InitializeComponent();
}
public void show(string pos0, string pos1, string pos2, string message) //<=== initializing the message box with the values from your main code
{
button1.Text = pos0;
button2.Text = pos1;
button3.Text = pos2;
label1.Text = message;
}
// message box events to set the static field incase a button on the custom form was changed
private void button1_Click(object sender, EventArgs e)
{
MessageBoxResult.dialogResult = 0;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
MessageBoxResult.dialogResult = 1;
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
MessageBoxResult.dialogResult = 2;
this.Close();
}
}
//usage
{
MessageBoxResult.dialogResult = -1; // <== setting the static field to -1 to mean nothing was pressed
CustomMsgBox cMsgBox = new CustomMsgBox();
cMsgBox.show("your message");
cMsgBox.ShowDialog();
}
You can change what happends, based on what button is clicked, with the DialogResult
DialogResult dialogResult = MessageBox.Show(#"Some body", #"Title", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
// do stuff
}
No, a message box cannot do this. It's not meant to do this. It's meant to just display a message... in a box :)
What you can always do is create your own window that looks like a message box and behaves like a message box, but actually does things when you click the buttons.

How to connect pop up to a button?

How to connect a pup up to a button ?
I want when i click a button pup up window to appear.
I have already made the pop up with some elements child-ed in the grid in the pop up.
I've tried this but it doesn't work
private void Task_click(object sender, RoutedEventArgs e)
{
if (PopUp.Visibility == Visibility.Collapsed)
PopUp.Visibility = Visibility.Visible;
}
I think maybe other parameter has to be changed for the pup up to appear.
Thanks for the help :D
From what I understood, you are doing Windows Form programing and the popup you are talking about must be a Custom dialog box (Simpler Version's Tutorial). Assuming you have set the properties of your PopUp suitable for a dialog box, you can use following :
using (PopUp pp = new PopUp())
{
DialogResult result = pp.ShowDialog();
if (result == DialogResult.OK)
{
// do your stuff
}
}

User input validation with a foreach loop in form constructor

I'm trying to use this custom method for user input validation in text boxes. But I feel something missing in this approach. Now use cant move to next text box if the validation failed. Is this a good thing or bad thing to do?
private void textBox_Validating(object sender, CancelEventArgs e)
{
TextBox currenttb = (TextBox)sender;
if (currenttb.Text == "")
{
MessageBox.Show(string.Format("Empty field {0 }", currenttb.Name.Substring(3)));
e.Cancel = true ;
}
else
{
e.Cancel = false;
}
}
Adding the handler to the textboxes with a foreach loop in the form constructor:
foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
tb.Validating += textBox_Validating;
}
How about using Error Provider, it will display exclamation if validation fail
I thought it would be a bad user experience if you popup too much message box. May be you should consider use labels to display error message beside each text box. In your programm, I can't even close the window by clicking the close button if I left the text box empty.

How can I know which object is clicked in C#?

To make sure that the user name input is valid, I added such callback method to do the verification:
Regex UserNameRE = new Regex(#"^[a-zA-Z]\w*$");
//being called when input box is not focused any more
private void UserNameInput_Leave(object sender, EventArgs e)
{
//pop up a warning when user name input is invalid
if (!UserNameRE.IsMatch(UserNameInput.Text))
{
MessageBox.Show("Invalid User Name!");
this.UserNameInput.Text = "";
this.UserNameInput.Focus();
}
}
The method will be called when user finished their inputting(the method is bounded with the event-"leaving the input box"). It works when user left a invalid User_Name and begin to enter a password.
But it also works when user click another tab, e.g. the Register tab. I don't want this happen. Because the user obviously don't wanna login anymore if he clicks "Register" tab, and my C# app shouldnot pop up a warning box and force them inputting a valid user name again.
How can the C# tell the difference of such 2 situations? It should be easy if I know which object is being clicked.
You will have source of event in object sender in UserNameInput_Leave event.
private void UserNameInput_Leave(object sender, EventArgs e)
{
//sender is source of event here
}
Here's an option:
private void UserNameInput_Leave(object sender, EventArgs e)
{
if (sender.GetType() != typeof(TextBox))
{
return;
}
TextBox tBox = (TextBox)sender;
//pop up a warning when user name input is invalid
if (!UserNameRE.IsMatch(UserNameInput.Text) && tBox.Name == UserNameInput.Name)
{
MessageBox.Show("Invalid User Name!");
this.UserNameInput.Text = "";
this.UserNameInput.Focus();
}
}
I am not sure if there's a right solution for this particular scenario here.
When you add a handler to validate your control on mouse leave, definitely it will be executed first regardless you clicked on another control within the tab or another tab itself.
This normal flow can't be ignored easily. It must be possible by hanlding the message loop yourself but the event based flow, first leave focus, and selected index change (selecting) event will be fired. I would suggest you not to disturb the flow as the validation is client side and pretty fast. Instead of messagebox, I would recommend you to use ErrorProvider and attach to the control whenever required. Also messagebox is quite disturbing and as per your code, you're forcefully making it focus to the textbox again.
How about the following code?
public partial class Form1 : Form
{
ErrorProvider errorProvider = new ErrorProvider();
public Form1()
{
InitializeComponent();
textBox1.Validating += new CancelEventHandler(textBox1_Validating);
}
private void textBox1_Leave(object sender, EventArgs e)
{
textBox1.CausesValidation = true;
}
void textBox1_Validating(object sender, CancelEventArgs e)
{
Regex UserNameRE = new Regex(#"^[a-zA-Z]\w*$");
if (!UserNameRE.IsMatch(textBox1.Text))
{
errorProvider.SetError(this.textBox1, "Invalid username");
}
}
}

user input and acceptance inside a function

My function accepts user input and then do somework when user clicks ok.
private void cannyToolStripMenuItem_Click(object sender, EventArgs e)
{
canny();
}
private void canny()
{
// get user input
// if user clicks ok
if (ok button is clicked)
{
messagebox.show(" you clicked ok")
//
//do dome work
//
}
}
But I can't see any messagebox. What I am missing.
private void ok_Click(object sender, EventArgs e)
{
// should I add here some thing
}
what i am missing.
regards,
I think what you are trying to achieve is to get the result from a dialog box. If that is the case you want to do the following:
private void ShowDialogAndDoSomethingBasedOnTheResult()
{
DialogResult result = MessageBox.Show(
"Dialog text",
"Caption to go in title bar",
MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
//Do work
}
}
See http://msdn.microsoft.com/en-gb/library/0x49kd7z.aspx for more examples.
Well, yes, you do:
private void ok_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Ok;
}
Which closes the dialog, it will only stay running as long as its DialogResult property is None. It isn't strictly necessary, you can also use the designer. Change the button's DialogResult property, now you don't need to write the code. That is however not often appropriate, you usually want to check if the user provided all the information you require. Ymmv.

Categories