Disable NumericUpdown C# - c#

The student is back! I am trying to self-teach C#, so please pardon my simple but many questions. I appreciate you all.
I am working on a quiz app.What I want but cant seem to achieve is that when "Testing mode" (radio button) is selected, "Number of questions" need to be grayed out.Otherwise, student can select number of questions to attempt.
Here is my code
private void rdotesting_CheckedChanged(object sender, EventArgs e)
{
if (MessageBox.Show("You have selected Testing Mode.Do you want to continue?", "Confirm Choice", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
MessageBox.Show("Click 'Start' to continue..");
btnclose.Hide();
}
else
{
MessageBox.Show("You Must select an option to continue.");
}
}
//if testing mode, dissable number of questions ,and also the 'Close' button

Like this - see comments
private void rdotesting_CheckedChanged(object sender, EventArgs e)
{
//this event fires when rdotesting is checked or when it is unchecked (change)
//set the enabled state of the nud/button to th opposite of the checked state
//ie when checked = true then enabled = false
numberQsNUD.Enabled = !rdotesting.Checked;
closeButton.Enabled = !rdotesting.Checked;
//if not in test mode, exit to stop the message showing every time
if(!rdotesting.Checked)
return;
if (MessageBox.Show("You have selected Testing Mode.Do you want to continue?", "Confirm Choice", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
rdotesting.Checked = false; //user said no; turn off test mode

simply you can try this code...
private void rdotesting_CheckedChanged(object sender, EventArgs e) {
if(rdotesting.Checked) {
numberQsNUD.Enabled = false;
closeButton.Enabled = false;
} else {
numberQsNUD.Enabled = true;
closeButton.Enabled = true;
}
}
or you can customize this via using this code...
private void EnableComponent(bool check) {
numberQsNUD.Enabled = check;
closeButton.Enabled = check;
}
private void rdotesting_CheckedChanged(object sender, EventArgs e) {
if(rdotesting.Checked) {
EnableComponent(false);
} else {
EnableComponent(true);
}
}

Related

Close button is not closing the form properly

My form contains a button named as close. I just put the below code in the close button click... Then the 2nd code set is for the form closing. But if I execute this when I click the close button a MessageBox will appear. When I click the "Yes" button, the form is not closing but if I click the "Yes" button second time the form will be closed. What is the reason? Can you, please, help me?
private void btnClose_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are You Sure You Want To Close This Form?",
"Close Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// MessageBox.Show("The application has been closed successfully.",
// "Application Closed!",
// MessageBoxButtons.OK);
System.Windows.Forms.Application.Exit();
}
else
{
this.Activate();
}
}
-------------------------------------
private void frminventory_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are You Sure You Want To Close This Form?",
"Close Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
System.Windows.Forms.Application.Exit();
}
else
{
this.Activate();
}
}
Do not close/exit Application, but Form:
private void btnClose_Click(object sender, EventArgs e) {
// On btnClose button click all we should do is to Close the form
Close();
}
private void frminventory_FormClosing(object sender, FormClosingEventArgs e) {
// If it's a user who is closing the form...
if (e.CloseReason == CloseReason.UserClosing) {
// ...warn him/her and cancel form closing if necessary
e.Cancel = MessageBox.Show("Are You Sure You Want To Close This Form?",
"Close Application",
MessageBoxButtons.YesNo) != DialogResult.Yes;
}
}
Edit: Usually we ask direct questions to user (it's unclear what wrong things can arise if I just "Close This Form"), e.g.
private void frminventory_FormClosing(object sender, FormClosingEventArgs e) {
// Data has not been changed, just close without pesky questions
if (!isEdited)
return;
// If it's a user who is closing the form...
if (e.CloseReason == CloseReason.UserClosing) {
var action = MessageBox.Show(
"You've edited the data, do you want to save it?"
Text, // Let user know which form asks her/him
MessageBoxButtons.YesNoCancel);
if (DialogResult.Yes == action)
Save(); // "Yes" - save the data edited and close the form
else if (DialogResult.No == action)
; // "No" - discard the edit and close the form
else
e.Cancel = true; // "Cancel" - do not close the form (keep on editing)
}
}
So, because i can't comment, i would do something like this.
//Create this variable
private bool _saved = true;
public Form1()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
DoSomething();
_saved = true;
}
//Raised when the text is changed. I just put this for demonstration purpose.
private void textBox1_TextChanged(object sender, EventArgs e)
{
_saved = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (_saved == false)
{
var result = MessageBox.Show("Are you sure you want to close?\nYou may have unsaved information", "Information", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
_saved = true;
Application.Exit();
}
else
e.Cancel = true;
}
}
Hope this can solve yor problem

If-Else statement for a checkbox

I've got the following problem:
When my program checks for a determined condition and if the checkbox was checked, it throws the MessageBox twice; according to the debugger, it goes inside the if, throws the messagebox and then issue the Checkbox1.Checked == false . After that it executes the entire if condition again.
I've tried MSDN documentation about Checkbox1.Threestate but I couldn't get to implement it. What can I do to solve this checkbox issue ?
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
string currPath = textBox1.Text;
if (!textBox1.Text.Contains("\\"))
{
MessageBox.Show("Please define the input folder before starting");
checkBox1.Checked = false;
}
else if (!textBox2.Text.Contains("\\"))
{
MessageBox.Show("Please define the XML Output folder before starting");
checkBox1.Checked = false;
}
else if (!textBox3.Text.Contains("\\"))
{
MessageBox.Show("Please define the Converted PPF Output Folder before starting");
checkBox1.Checked = false;
}
else if (!textBox4.Text.Contains("\\"))
{
MessageBox.Show("Please define the Invalid PPF Output Folder before starting");
checkBox1.Checked = false;
}
else
{
// calls the watcher
prg.ProgramProcessing(textBox1.Text);
}
}
Since you change the check inside the checkchange event, it trigger it a second time, you should unsubscribe the event, then resubscribe
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
checkBox1.CheckedChanged -= checkBox1_CheckedChanged;
try
{
// Your conditions
}
finally
{
checkBox1.CheckedChanged += checkBox1_CheckedChanged;
}
}
You could skip it if checkbox is not checked.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (!checkBox1.Checked) return; //<- this.
string currPath = textBox1.Text;
if (!textBox1.Text.Contains("\\"))
{
MessageBox.Show("Please define the input folder before starting");
checkBox1.Checked = false;
}
else if (!textBox2.Text.Contains("\\"))
{
MessageBox.Show("Please define the XML Output folder before starting");
checkBox1.Checked = false;
}
else if (!textBox3.Text.Contains("\\"))
{
MessageBox.Show("Please define the Converted PPF Output Folder before starting");
checkBox1.Checked = false;
}
else if (!textBox4.Text.Contains("\\"))
{
MessageBox.Show("Please define the Invalid PPF Output Folder before starting");
checkBox1.Checked = false;
}
else
{
// calls the watcher
prg.ProgramProcessing(textBox1.Text);
}
}
You have multiple solution:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
checkBox1.CheckedChanged -= checkBox1_CheckedChanged;
// Yours conditions
checkBox1.CheckedChanged += checkBox1_CheckedChanged;
}
OR
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if(checkBox1.Checked == false)
{
return;
}
// your conditions..
}
As soon as you set Checked = false, you change its value, and the Changed event is fired again.
One way to solve this, is using a guard variable that makes sure you don't go through the code again while you are handling the event:
private bool handlingCheckboxChanged;
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if(handlingCheckboxChanged) { return; }
handlingCheckboxChanged = true;
try {
// Your original code
} finally {
handlingCheckboxChanged = false;
}
}
Even better would be to make sure that the user cannot check the checkbox in the first place, for example by handling the change events of the text boxes and only enabling your checkbox once all the conditions have been met.

How to Require Confirmation on Form Close When there is Changed Data in a DataGridView

I have simple Form1 with datagridview and I've enabled editing and adding.
Now, when I click on closing form button, and if some of existing cell values are changed or new row has been added I want dialogue box to open (for example, asking me if I want to save changes or don't), and if there is no changes , just to perform simple form closing.
How can I accomplish this ?
Ok, here is what I've got so far.
I'm trying to this one using CSLA framework, I've created root editable collection public class PDVCollection : BusinessBindingListBase<PDVCollection, PDV> and editable child public class PDV : BusinessBase<PDV>
On Form1 I've got this code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public PDVCollection s;
private void Form1_Load(object sender, EventArgs e)
{
bindingSource1.DataSource = PDVCollection.GetAll();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
s = (PDVCollection)bindingSource1.DataSource;
s = s.Save();
bindingSource1.DataSource = s;
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell.RowIndex > -1)
{
PDV sel = (PDV)dataGridView1.CurrentRow.DataBoundItem;
s = (PDVCollection)bindingSource1.DataSource;
s.Remove(sel);
s = s.Save();
}
}
i want to cut s = s.Save(); from both toolStripButton1_Click and toolStripButton3_Click and If something is changed/added/deleted and I perform closing event
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (//some code to implement)
{
DialogResult dialogResult = MessageBox.Show("Do you want to save changes", "Message", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
s = (PDVCollection)bindingSource1.DataSource;
s = s.Save();
}
else if (dialogResult == DialogResult.No)
{
this.DialogResult = DialogResult.OK;
}
}
}
If you're doing databinding to a DataSource, then you can use the datasource to determine whether it has been changed in the FormClosing or FormClosed event. The actual implementation would be up to the type of datasource you are using.
If you're not specifying a datasource, then the data by default can be accessed in the Rows collection of the DataGrid. That collection class doesn't have a "changed" flag by default, but it DOES have a CollectionChanged event that you could hook up.
So, in your form's construtor, you could do a
DataGrid1.CollectionChanged += Rows_CollectionChanged;
And then in your Rows_CollectionChanged you could set a flag that data has changed and needs to be saved. Obviously giving much more detail would require knowing more about the details of your datagrid and datasource.
Per the comments below, you may want more than a flag depending on how you define "changed". If you need to know that a field was changed, then changed back to the original value then as a commenter below says a simple flag wouldn't do it, and you might need to store a shadow copy of the original data.
That said, if you need to handle really complicated undo scenarios you're going to want datasource designed for that, which is a whole different topic.
EDIT: If you're using CSLA objects as your data source, then there should be an IsDirty flag on the objects. So just iterate over the items in the datasource on the FormClosed event and check the IsDirty flag for each object.
You need to create flag variable and initially set it to false
bool isAnythingChange = false;
And make this variable to true on new row add, or value change event. For sample I have shown below
void txt_Change(object sender, EventArgs e)
{
isAnythingChange = true;
}
And while you are handling form closing event make point to check isAnythingChange. If it's value is true then ask for confirmation or else close form without confirmation.
EDIT:
As you maintain in your question, updated code may be like this.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (isAnythingChange)
{
DialogResult dialogResult = MessageBox.Show("Do you want to save changes", "Message", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
s = (PDVCollection)bindingSource1.DataSource;
s = s.Save();
}
else if (dialogResult == DialogResult.No)
{
this.DialogResult = DialogResult.OK;
}
}
}
Ok, here is final working solution, if anyone is looking for it.
public Form1()
{
InitializeComponent();
}
public PDVCollection s;
private void Form1_Load(object sender, EventArgs e)
{
bindingSource1.DataSource = PDVCollection.GetAll();
s = (StopaPDVCollection)bindingSource1.DataSource;
}
private void toolStripButton1_Click(object sender, EventArgs e)
s = s.Save();
bindingSource1.DataSource = s;
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell.RowIndex > -1)
{
PDV sel = (PDV)dataGridView1.CurrentRow.DataBoundItem;
s.Remove(sel);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (s.IsDirty)
{
DialogResult dialogResult = MessageBox.Show("Do you want to save changes", "Message", "Poruka", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
s = (PDVCollection)bindingSource1.DataSource;
s = s.Save();
bindingSource1.DataSource = s;
}
else if (dialogResult == DialogResult.No)
{
this.DialogResult = DialogResult.OK;
}
}
}
}

How do i use the checkBox2 to check if its checked or not?

The code:
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
crawlLocaly1 = new CrawlLocaly();
crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
OptionsDB.Set_localOnly(checkBox2.Checked);
if (checkBox2.Checked)
{
DialogResult dr = crawlLocaly1.ShowDialog(this);
if (dr == DialogResult.Cancel)
{
crawlLocaly1.Close();
}
else if (dr == DialogResult.OK)
{
LocalyKeyWords.Add(crawlLocaly1.getText());
crawlLocaly1.Close();
}
removeExt = true;
}
else
{
removeExt = false;
}
}
This line:
OptionsDB.Set_localOnly(checkBox2.Checked);
Save the state of the checkBox2 if its checked or not. If its checked next time i will run my program i will see the V in the checkBox2 checked box. If i will uncheck the checkBox next time i run my program the box of the checkBox2 will be unchecked.
The problem is when i check the checkBox2 once close my program and run it again since the checkBox is checked now then for some reason it will make this:
DialogResult dr = crawlLocaly1.ShowDialog(this);
Wich will open and show the user a new Form.
But i dont want it to be like that.
I want that if the user checked the checkBox when the program is running the new Form will show up. But if the user is running the program from the beginning and the checkBox is checked dont show the new Form just show that the checkBox is checked !
How should i fix it ?
You need an other boolean flag checkedInThisSession which initially set to false, and just set it to true in a checkbox OnChecked handler, then you can check this state easily. Hope all is clear
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
crawlLocaly1 = new CrawlLocaly();
crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
OptionsDB.Set_localOnly(checkBox2.Checked);
// UPDATED
if (checkedInThisSession && checkBox2.Checked)
{
DialogResult dr = crawlLocaly1.ShowDialog(this);
// ...
}
else
{
removeExt = false;
}
// UPDATED
checkedInThisSession = checkBox2.Checked;
}
// In constructor
checkedInThisSession = false;
checkBox2.Checked = OptionsDB.Get_localOnly();
The CheckedChanged event is fired every time the checkbox is set, also programmatically. So to solve this issue you need to ignore the first time the event is fired. So a boolean could be your solution:
private bool ignore = true;
private void checkBox2_CheckedChanged(object sender, EventArgs e){
if(ignore == false){
//your code here
}
else
ignore = false;
}

Setting IsEnabled on a ribbon textbox to true doing nothing

I am working on a program to manage a minecraft server with a local UI as well as a remote interface. I have a button on a ribbon bar that will enable or disable the remote interface and a textbox for inputting the port. Currently, I disable the textbox when the networking is enabled, but, disabling does not re-enable the textbox after I set it to true again (and setting a breakpoint reveals it to still be false).
private void NetToggleChecked(object sender, RoutedEventArgs e) {
portTextBox.IsEnabled = false;
if (ButtonPressedByUser) {
var result = MessageBox.Show("Are you sure you want to enable networking with the current settings?" +
" If not properly configured, it may be possible for an attacker to enter your server.",
"Simple Bukkit Wrapper", MessageBoxButton.YesNo, MessageBoxImage.Warning,
MessageBoxResult.No);
if (result == MessageBoxResult.No) {
ButtonPressedByUser = false;
NetworkToggle.IsChecked = false;
ButtonPressedByUser = true;
return;
}
}
Config.NetConf["enabled"] = "true";
int port;
if (!int.TryParse(Config.NetConf["port"], out port)) {
MessageBox.Show("Port could not be parsed (is it a number?)");
ButtonPressedByUser = false;
NetworkToggle.IsChecked = false;
ButtonPressedByUser = true;
return;
}
Net.Listener.StartListening(port);
}
private void NetworkToggleUnchecked(object sender, RoutedEventArgs e) {
portTextBox.IsEnabled = true;
if (ButtonPressedByUser) {
var result =
MessageBox.Show("Are you sure you wish to disable all networking to your server? It will " +
"be impossible to connect to it remotely and any existing connections will be closed.",
"", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
if (result == MessageBoxResult.No) {
ButtonPressedByUser = false;
NetworkToggle.IsChecked = true;
ButtonPressedByUser = true;
return;
}
}
Config.NetConf["enabled"] = "false";
Net.Listener.StopListening();
}
Thank you for any help resolving why the textbox will not enable again.
Old Question but i kept coming across it while searching for an answer so figured i'd post an answer anyways. There is a bug in the ribbonTextbox control that results in isenabled always being false if there is no command associated. There are 2 ways round this from what i have found:
1: Create a new control based on the ribbontextbox and override the isenabledcore property to always return true. As shown here Cannot set RibbonTextBox isEnable to False
2: Create a dummy command and associate it with the control
public static readonly ICommand DummyCommand = new RoutedCommand("Dummy", typeof(Control));
public static void Dummy(Object sender, ExecutedRoutedEventArgs e)
{
// Do nothing its a dummy command
}
public static void CanDummy(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
as described in a comment in this link http://blogs.msdn.com/b/wpf/archive/2010/10/21/wpf-ribbon-october-2010-update-details.aspx .
AS i said probably no help to the original poster but i kept coming across it while looking for an answer so it may save someone else a few minutes of googling time.

Categories