I have a message box that pops up when a user click a button. when user click yes it's run an insert function.
what i want is to add or start a count down when a messagebox pop up, the default yes button was disabled. and after 5 second the yes button, become enable and ready to click by user.
if (MessageBox.Show("log", "test", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
insert();
}
As suggested in the comment, you need to have your own implementation for this functionality. Below is partial code that you will need to modify normal form to make it appear like dialogue box:
Add new Form to your project. Open the porperties tab. Set properties as give below in point 2.
Modify form in designer to change following properties to given values:
this.AcceptButton = this.btnYes;//To simulate clicking *ENTER* (Yes)
this.CancelButton = this.button2; //to close form on *ESCAPE* button
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
//FROM CODEPROJECT ARTICLE LINK
this.ShowInTaskBar = false;
this.StartPosition = CenterScreen;
Add a timer to form. Set its interval to 5000 (5 seconds). Write code to start timer on Shown event of form:
private void DialogBox_Shown(object sender, EventArgs e)
{
timer1.Start();
}
Handle ticking of Timer:
public DialogBox()
{
InitializeComponent();
//bind Handler to tick event. You can double click in
//properrties>events tab in designer
timer1.Tick += Timer1_Tick;
}
private void Timer1_Tick(object sender, EventArgs e)
{
btnYes.Enabled = true;
timer1.Stop();
}
Set Yes button handler:
private void btnYes_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Yes;
}
From where you are showing this custom message box, you can check if Yes or No is clicked as follows:
var d=new DialogBox();
var result=d.ShowDialog();
if(result==DialogResult.Yes)
//here you go....
Related
Using: C# Forms VS2015
What I'm trying to do:
On form1, I have a textbox (tbJobTitle) and a button (bChooseJobTitle -> form2) for a "Job Title" of an employee.
The textbox(enabled=false) displays the chosen Job Title of an employee.
The button bChooseJobTitle opens another form (form2) that has a datagrid and 2 buttons (Choose & Cancel)
using System.Threading;
...
Thread the1;
...
private void bChooseJobTitle_Click(object sender, EventArgs e)
{
the1 = new Thread(OpenNew_tblJobTitle);
the1.SetApartmentState(ApartmentState.STA);
the1.Start();
}
private void OpenNew_tblJobTitle(object obj)
{
Application.Run(new form2());
}
...
I initially set a global string MyVar.Employee_Choose_idJobTitle (default "" ) to store the choosen index primary key if the user selected content and click the Choose button. If the Cancel button is click the MyVar.Employee_Choose_idJobTitle will remain = "".
//... at form2 "Choose" button
private void bChoose_Click(object sender, EventArgs e)
{
MyVar.idJobTitle = dataGridView1.CurrentRow.Cells[0].Value.ToString();
this.Close();
}
private void bCancel_Click(object sender, EventArgs e)
{
this.Close();
}
When form2 is closed either by "Choose" button or "Cancel" button, the focus goes back to form1's bChooseJobTitle button.
How do I trigger this event?
...so that can test if the content of MyVar.idJobTitle is not null and add the proper value to my textbox.
I was looking for the button events like onFocus or activate but could not find any. Do I use form events instead to do this?
Quite simply, use event Form Activate if you like.
private void form1_Activated(object sender, EventArgs e)
{
if (MyVar.idJobTitle != "")
{
tbJobTitle.Text = Choose_idJobTitle;
MyVar.idJobTitle = "";
}
}
The application I'm working on keeps track of bowling scores during tournaments. In it, there's a data entry sheet and a scoreboard. The data entry sheet has a button on which to click to launch the scoreboard form in a different thread.
private void pict_projector_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new
System.Threading.ThreadStart(this.openScoreboard));
t.Start();
}
private void openScoreboard()
{
frm_scoreboard frm = new frm_scoreboard();
frm.TourID = this.TourID;
frm.NightID = night_id;
Application.Run(frm);
}
On the scoreboard form I have a timer (threaded system.Timer) that ticks every second and checks if it's been 15 seconds before switching the scoreboards TableLayoutPanel to reflect the next playing divisions scores.
private void ttmr_switch_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
cnt_ticks++;
if (cnt_ticks == 15)
{
cnt_ticks = 0;
ttmr_switch.Enabled = false;
switchBoard();
}
}
On the same form (scoreboard) there's a "maximize" button which renders the form fullscreen. To exit fullscreen, I want the user to press Esc. Here is where the problem comes in.
private void frm_scoreboard_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Escape)
{
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.WindowState = FormWindowState.Normal;
pict_fullscreen.Visible = true;
}
}
The KeyDown event never gets triggered... and I lose control of the form.
After banging my head against a wall for a while, I decided to bring this to you all. Any idea how to resolve this?
Did you set the KeyPreview option of the form to true?
more information on msdn
I am creating a program in C# Windows Form Application.
Let me give you a scenario of what I am doing:
Log into the program (login system)
The program will determine the user's permission value (let's say I'm 3)
Depending on the permission value, the main menu will show buttons
3a. If the user has permission value greater than 2, user will view all buttons
3b. If the user has permission value less than 2, user will see only 1 button
When I logout, I am using .hide to hide the main menu and showing the login form again.
I log in another user (with permission value = 1)
All the buttons will show, not just only 1 like it should be.
Does anyone know how to "redo" the main menu after logging in, depending on permission value?
Maybe this?
const int firstButtonY = 20;
const int padding = 20;
int currentY = firstButtonY;
foreach (var control in this.Controls)
{
if (control.GetType() != typeof(System.Windows.Forms.Button))
continue;
var curButton = (Button) control;
if (!curButton.Visible)
continue;
curButton.Top = currentY;
currentY += padding + curButton.Height;
}
Instead of open new instance (in my case, Form3) in Form1 in Form1_Load
frm3 = new Form3(this);
and show after specified event trigger
frm3.Show();
and cancel the Form3_Closing
private void Form3_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
}
We do like this for every event triggered
frm3 = new Form3(this);
frm3.Show();
and comment the create new instance in Form1_Load
//frm3 = new Form3(this);
and comment the Hide form3 part
private void Form3_FormClosing(object sender, FormClosingEventArgs e)
{
//e.Cancel = true;
//this.Hide();
}
because frm3.Show() after the form3 this.Hide() WON'T triggered
private void Form3_Load(object sender, EventArgs e)
After a button is clicked in a Windows form application written in C#, how to wait for another button to be clicked? Meanwhile I am updating a datagridview dynamically by current information.
EDIT
After button1 is clicked, I want to repeatedly update a dataGridView with current information and when button2 is clicked I want to stop updating the dataGridView.
Use Timer Class.
public partial class Form1 : Form
{
System.Windows.Forms.Timer timer;
public Form1()
{
InitializeComponent();
//create it
timer = new Timer();
// set the interval, so it'll fire every 1 sec. (1000 ms)
timer.Interval = 1000;
// bind an event handler
timer.Tick += new EventHandler(timer_Tick);
//...
}
void timer_Tick(object sender, EventArgs e)
{
//do what you need
}
private void button1_Click(object sender, EventArgs e)
{
timer.Start(); //start the timer
// switch buttons
button1.Enabled = false;
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer.Stop(); //stop the timer
// switch buttons back
button1.Enabled = true;
button2.Enabled = false;
}
From MSDN:
A Timer is used to raise an event at user-defined intervals. This
Windows timer is designed for a single-threaded environment where UI
threads are used to perform processing. It requires that the user code
have a UI message pump available and always operate from the same
thread, or marshal the call onto another thread.
When you use this timer, use the Tick event to perform a polling
operation or to display a splash screen for a specified period of
time. Whenever the Enabled property is set to true and the Interval
property is greater than zero, the Tick event is raised at intervals
based on the Interval property setting.
So you have button A and button B. When button A is pressed you want to wait for button B to be pressed, then do something special? Without more information the simplest way is something like this:
private void OnButtonAClicked(object sender, EventArgs e)
{
ButtonA.Enabled = false;
ButtonA.Click -= OnButtonAClicked;
ButtonB.Click += OnButtonBClicked;
ButtonB.Enabled = true;
}
private void OnButtonBClicked(object sender, EventArgs e)
{
ButtonB.Enabled = false;
ButtonB.Click -= OnButtonBClicked;
// Do something truly special here
ButtonA.Click += OnButtonAClicked;
ButtonA.Enabled = true;
}
This code will toggle(initial state; button A is enabled, button B is disabled), when button A is pressed, button B becomes enabled and processes events, etc.
Use the BackgroundWorker http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
It doesn't freeze the UI, support ProgressBar, also it can be async. At the link you will see a good example with same functional that you want (start some task by click on one button and cancel it by click on another button).
I have a dialog that I show with <class>.ShowDialog(). It has an OK button and a Cancel button; the OK button also has an event handler.
I want to do some input validation in the event handler and, if it fails, notify the user with a message box and prevent the dialog from closing. I don't know how to do the last part (preventing the close).
You can cancel closing by setting the Form's DialogResult to DialogResult.None.
An example where button1 is the AcceptButton:
private void button1_Click(object sender, EventArgs e) {
if (!validate())
this.DialogResult = DialogResult.None;
}
When the user clicks button1 and the validate method returns false, the form will not be closed.
Given that you've specified you want a pop error dialog, one way of doing this is to move your validation into a OnClosing event handler. In this example the form close is a aborted if the user answers yes to the question in the dialog.
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}
By setting e.Cancel = true you will prevent the form from closing.
However, it would be a better design/user experience to display the validation errors inline (via highlighting the offending fields in some way, displaying tooltips, etc.) and prevent the user from selecting the OK button in the first place.
Don't use the FormClosing event for this, you'll want to allow the user to dismiss the dialog with either Cancel or clicking the X. Simply implement the OK button's Click event handler and don't close until you are happy:
private void btnOk_Click(object sender, EventArgs e) {
if (ValidateControls())
this.DialogResult = DialogResult.OK;
}
Where "ValidateControls" is your validation logic. Return false if there's something wrong.
You can catch FormClosing an there force the form to remain opened.
use the Cancel property of the event argument object for that.
e.Cancel = true;
and it should stop your form from closing.
This doesn't directly answer your question (other already have), but from a usability point of view, I would prefer the offending button be disabled while the input is not valid.
Use this code:
private void btnOk_Click(object sender, EventArgs e) {
if (ValidateControls())
this.DialogResult = DialogResult.OK;
}
The problem of it is that the user has to clic two times the buttons for closing the forms;
Just add one line in the event function
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
this->DialogResult = System::Windows::Forms::DialogResult::None;
}
I wish I had time to find a better example, but you would be much better off using the existing windows forms validation techniques to do this.
http://msdn.microsoft.com/en-us/library/ms229603.aspx
void SaveInfo()
{
blnCanCloseForm = false;
Vosol[] vs = getAdd2DBVosol();
if (DGError.RowCount > 0)
return;
Thread myThread = new Thread(() =>
{
this.Invoke((MethodInvoker)delegate {
picLoad.Visible = true;
lblProcces.Text = "Saving ...";
});
int intError = setAdd2DBVsosol(vs);
Action action = (() =>
{
if (intError > 0)
{
objVosolError = objVosolError.Where(c => c != null).ToArray();
DGError.DataSource = objVosolError;// dtErrorDup.DefaultView;
DGError.Refresh();
DGError.Show();
lblMSG.Text = "Check Errors...";
}
else
{
MessageBox.Show("Saved All Records...");
blnCanCloseForm = true;
this.DialogResult = DialogResult.OK;
this.Close();
}
});
this.Invoke((MethodInvoker)delegate {
picLoad.Visible = false;
lblProcces.Text = "";
});
this.BeginInvoke(action);
});
myThread.Start();
}
void frmExcellImportInfo_FormClosing(object s, FormClosingEventArgs e)
{
if (!blnCanCloseForm)
e.Cancel = true;
}
You can probably check the form before the users hits the OK button. If that's not an option, then open a message box saying something is wrong and re-open the form with the previous state.