I've written a code in which when one check box is clicked the others get disselected
image of buttons
3 of my check boxes are working fine byname,containing and bydate But when I try to do the same with the by category check box I get the following message.error image
This is my code
private void vieworder_Load(object sender, EventArgs e)
{
try
{
con.Open();
if (con.State == ConnectionState.Open)
{
lblstatus.Text = "Connected";
lblstatus.ForeColor = Color.Green;
}
else
{
lblstatus.Text = "Not-Connected";
lblstatus.ForeColor = Color.Red;
}
showdtgrid();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void hidecheckbox()
{
chkboxbyname.CheckState = CheckState.Unchecked;
chkboxbydate.CheckState = CheckState.Unchecked;
chkboxcontaining.CheckState = CheckState.Unchecked;
checkBox1.CheckState = CheckState.Unchecked;
}
private void chkboxbyname_CheckedChanged(object sender, EventArgs e)
{
hidecheckbox();
chkboxbyname.CheckState = CheckState.Checked;
}
private void chkboxcontaining_CheckedChanged(object sender, EventArgs e)
{
hidecheckbox();
chkboxcontaining.CheckState = CheckState.Checked;
}
private void chkboxbydate_CheckedChanged(object sender, EventArgs e)
{
hidecheckbox();
chkboxbydate.CheckState = CheckState.Checked;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
hidecheckbox();
checkBox1.CheckState = CheckState.Checked;
}
}
}
Please tell me what's wrong
At a glance, it looks like the stack overflow is directly related to the event handler for checkBox1_CheckedChanged.
It looks like that handler is calling hideCheckbox(), which in turn changes the CheckState of your checkbox to Unchecked. That would in turn fire off your event handler, and therefore create an infinite loop.
What's strange is that you claim everything is working for the other checkboxes. My guess is that those checkboxes aren't wired up to their corresponding event handlers, as they should also cause stack overflow.
Could you try removing your event handler entirely if it isn't needed? Otherwise, comment out the call to hideCheckbox()
Related
Here's what H have so far:
private void button1_Click(object sender, EventArgs e)
{
button3.BackgroundImage = slideshow_test.Properties.Resources.ai_yori_aoshi_5370;
}
private void button2_Click(object sender, EventArgs e)
{
button3.BackgroundImage = slideshow_test.Properties.Resources.AiYoriAoshi_feature;
}
private void button3_Click(object sender, EventArgs e)
{
audio.Stop();
if (button1.Enabled == true)
{
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start("http://www.watchcartoononline.com/anime/ai-yori-aoshi-guide");
if (button2.Enabled == true)
{
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start("http://www.watchcartoononline.com/anime/ai-yori-aoshi-enishi-guide");
}
}
}
this is only my test so far but what i want to do is change what button 3 does, i.e. if button 1 is clicked button three will open webpage 1, if button2 is clicked button 3 will open webpage 2, button 3's image will change depending, but what im finding with what i have done so far is that it opens BOTH pages AT THE SAME TIME ... how to i prevent this? i have tried if, else and else if, same result every time.
Both of your buttons are enabled, you are checking to see if the buttons are enabled or disabled (clickable or not), not which one has been clicked.
also:if (button2.Enabled == true)
is nested in the first conditional, I'm not sure if that's what you want.
You can: disable buttons 1 and 2 after their clicked so that, for instance button2.Enabled will now = false; (but then you will not be able to reclick that button)
More sophisticated, but better, is to use a delegate for the button3, and assign them in your button1_Click and button2_Click events. Something like this:
private void button1_Click(object sender, EventArgs e)
{
button3.BackgroundImage = slideshow_test.Properties.Resources.ai_yori_aoshi_5370;
button3.Click += new EventHandler(this.Button3_Click_First);
}
private void button2_Click(object sender, EventArgs e)
{
button3.BackgroundImage = slideshow_test.Properties.Resources.AiYoriAoshi_feature;
button3.Click += new EventHandler(this.Button3_Click_Second);
}
void Button3_Click_First(Object sender,
EventArgs e)
{
// When the button is clicked,
// change the button text, and disable it.
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start("http://www.watchcartoononline.com/anime/ai-yori-aoshi-guide");
}
void Button3_Click_Second(Object sender,
EventArgs e)
{
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start("http://www.watchcartoononline.com/anime/ai-yori-aoshi-enishi-guide");
}
You may also have to check and make sure an event handler was not previously assigned, in calse someone clicks button1, then button2, then button1 ect. This is described here: Removing event handlers
You can handle your problem by storing the URL of the webpage in a private field, setting it when buttons 1 or 2 are clicked and reading from it after clicking button 3.
private string _address = null;
private void button1_Click(object sender, EventArgs e)
{
// do other stuff
_address = "http://www.watchcartoononline.com/anime/ai-yori-aoshi-guide";
}
private void button2_Click(object sender, EventArgs e)
{
// do other stuff
_address = "http://www.watchcartoononline.com/anime/ai-yori-aoshi-enishi-guide";
}
private void button3_Click(object sender, EventArgs e)
{
if (_address != null)
{
audio.Stop();
if (button1.Enabled || button2.Enabled)
{
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start(_address);
}
}
}
I wasn't sure if all the code in button3_Click is necessary, so I cleared it up a little. I might be a bit off, though.
button.Enabled is always true for all buttons by default unless you set it to false. So you cannot use button1.Enabled property to check which button is pressed. try below approach.
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["Button1Clicked"] = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
ViewState["Button1Clicked"] = false;
}
protected void Button3_Click(object sender, EventArgs e)
{
if ((bool)ViewState["Button1Clicked"])
{
//open webpage2 code comes here
}
else
{
//open webpage2 code comes here
}
}
I got this code and what I am looking for is to validate the text boxes before saving. Now if I fill the textboxes then I clear any of them it saves anyway. How could I possibly check if the are all filled before saving? I was trying to add handlers for textchanged events but I didn't work. Any suggestion will be appreciated, cheers.
public partial class frmTrainer : Form
{
public frmTrainer()
{
InitializeComponent();
// We initialize new event handlers for the subjects textboxes
this.englishTextBox.KeyPress += new KeyPressEventHandler(englishTextBox_KeyPress);
this.mathsTextBox.KeyPress += new KeyPressEventHandler(mathsTextBox_KeyPress);
this.physicsTextBox.KeyPress += new KeyPressEventHandler(physicsTextBox_KeyPress);
}
// We create a public list for all the textbox controls in the form
public List textBoxes = new List();
private void frmTrainer_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'rCMDataSet.Students_Credentials' table. You can move, or remove it, as needed.
this.students_CredentialsTableAdapter.Fill(this.rCMDataSet.Students_Credentials);
// We initialize the List of textboxes
textBoxAdd();
}
// We create method stubs for the KeyPress event on the subjects textboxes
// to allow them receive only numeric inputs
private void englishTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Numeric input accepted only");
}
}
private void mathsTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Numeric input accepted only");
}
}
private void physicsTextBox_KeyPress(object sendet, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Numeric input accepted only");
}
}
// We create a method to add each textbox to the List
private void textBoxAdd()
{
textBoxes.Add(studentIDTextBox);
textBoxes.Add(first_NameTextBox);
textBoxes.Add(last_NameTextBox);
textBoxes.Add(usernameTextBox);
textBoxes.Add(passwordTextBox);
textBoxes.Add(englishTextBox);
textBoxes.Add(mathsTextBox);
textBoxes.Add(physicsTextBox);
textBoxes.Add(trainerIDTextBox);
}
// We create a private method to validate the textboxes
private void CheckTextBox()
{
foreach(TextBox txt in textBoxes)
{
if (string.IsNullOrWhiteSpace(txt.Text))
{
MessageBox.Show("Please insert data correctly");
}
}
}
private void students_CredentialsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.CheckTextBox();
try
{
//this.Validate();
this.students_CredentialsBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.rCMDataSet);
MessageBox.Show("Data saved successfully");
}
catch(System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void toolStripExit_Click(object sender, EventArgs e)
{
// We disable the automatic validation when clicking Exit button
this.AutoValidate = AutoValidate.Disable;
// We call the method to close the application
Application.Exit();
}
private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
{
// We disable the navigation buttons to prevent any skipping errors
this.bindingNavigatorMoveFirstItem.Enabled = false;
this.bindingNavigatorMoveLastItem.Enabled = false;
this.bindingNavigatorMoveNextItem.Enabled = false;
this.bindingNavigatorMovePreviousItem.Enabled = false;
}
}
}
In your students_CredentialsBindingNavigatorSaveItem_Click event, while you do call the CheckTextBox method to "validate" your controls, you're essentially not doing anything about empty controls except to show a MessageBox. What you should do is to return a boolean on the validation method whenever an empty input is found:
private bool CheckTextBox()
{
bool isValid = true;
foreach(TextBox txt in textBoxes)
{
if (string.IsNullOrWhiteSpace(txt.Text))
{
isValid = false;
MessageBox.Show("Please insert data correctly");
break; //You only need one invalid input to prevent saving
}
}
return isValid;
}
And in your Click event, check for the return value of the method and exit the event if an invalid input is detected:
private void students_CredentialsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
if(!this.CheckTextBox()) return; //Stop executing code if there's invalid input
try
{
//this.Validate();
this.students_CredentialsBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.rCMDataSet);
MessageBox.Show("Data saved successfully");
}
catch(System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Did you try using the String.Trim method on your text box text like:
foreach(TextBox txt in textBoxes)
{
//trim whitespaces from text at both ends and might be better to operate on a string
String text = txt.ToString();
text.Trim();
if (string.IsNullOrWhiteSpace(text))
{
MessageBox.Show("Please insert data correctly");
}
}
I am trying to validate windows form with try catch and so far I succeeded. My goal is when someone forgot to fill the gap or put in incorrect entry, catch returns messagebox with a warning. Now I also have Validating event on every control I want to validate so when somebody leave it empty or in incorrect format it will show the error next to the control. That seems ok so far (for me, at least) but my issue is, that if user doesn't even click to one box it only shows message box, but it won't highlight wrong controls.
Below is my code:
private void createButton_Click(object sender, EventArgs e)
{
try
{
Book newBook = new Book(titleBox.Text, authBox.Text, Convert.ToInt32(yearBox.Text), Convert.ToInt32(editBox.Text), pubComboBox.Text, descBox.Text);
bookList.Add(newBook);
booklistListBox.DataSource = bookList;
}
catch (FormatException)
{
MessageBox.Show("You probably missed a gap or put in incorrect form");
}
}
and those validating events:
private void titleBox_Validating(object sender, CancelEventArgs e)
{
if (titleBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(titleBox, "Title is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(titleBox, "");
}
}
private void authBox_Validating(object sender, CancelEventArgs e)
{
if (authBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(authBox, "Author is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(authBox, "");
}
}
private void yearBox_Validating(object sender, CancelEventArgs e)
{
if (yearBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(yearBox, "Year is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(yearBox, "");
}
}
private void editBox_Validating(object sender, CancelEventArgs e)
{
if (editBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(editBox, "Edition is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(editBox, "");
}
}
private void pubComboBox_Validating(object sender, CancelEventArgs e)
{
if (pubComboBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(pubComboBox, "Publisher is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(pubComboBox, "");
}
}
private void descBox_Validating(object sender, CancelEventArgs e)
{
if (descBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(descBox, "Description is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(descBox, "");
}
}
So is there way to, I don't know, change focus or something like that, forced with pressing the create button?
Thank You
Try using ValidateChildren():
private void createButton_Click(object sender, EventArgs e)
{
bool gotIssues = this.ValidateChildren();
if (gotIssues)
{
// someone didn't validate well...
}
}
So, the issue here is that you want to have it highlight in either of two scenarios:
1) When you leave the field and its contents are invalid (empty in this case)
2) When you click the create button and the field in question has invalid contents
And so I would create a single textBox_checkIfEmpty(object sender, EventArgs e) method:
private void textBox_checkIfEmpty(object sender, EventArgs e)
{
var asTb = sender as TextBox;
if (asTb != null && asTb.Text.Trim() == String.Empty)
{
errorProvider.SetError(asTb, "I'll leave it to you to abstract the error message appropriately");
e.Cancel = true;
}
else
{
errorProvider.SetError(asTb, "");
}
}
Then, you can set this method as the handler for your Validate event on your desired required controls, and you can also call the same method from the create button's handler, looping through the required TextBox instances and executing the method on each.
UPDATE
J. Hudler's ValidateChildren solution would be a more (developer) efficient tail to mine, as opposed to looping through the desired controls. That said, if the form has many children, and you only need to validate several, it might be helpful to loop still. Just depends on your specific scenario. My only other question is whether or not ValidateChildren is infinitely recursive, or if it only goes one level down (immediate children rather than all descendants).
the event validating for control call when the mouse click on the control and then leave it from the control. In your case when the user does not click on the control it will not trigger the validating event. U can do this by making your own function and call them on creat event.
private void button1_Click(object sender, EventArgs e)
{
textBox1_Validating(sender);
}
public void textBox1_Validating(object sender)
{
MessageBox.Show("validating");
errorProvider1.SetError(textBox1, "provide");
}
I'm currently creating a calculator type form on C#. I have four radiobuttons (Addition, subtraction, multi, and div) and a label in between two textboxes. The label changes according to the selected radiobutton, (for example if I selected the Addition radiobutton the label would read "+"). The problem I'm experiencing with this code:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
label3.Text = ("+");
}
else if (radioButton2.Checked == true)
{
label3.Text = ("-");
}
else if (radioButton3.Checked == true)
{
label3.Text = ("x");
}
else if (radioButton4.Checked == true)
{
label3.Text = ("/");
}
}
is when I select the division button the label does not change unless I go through all the buttons and THEN other radio buttons (such as subtraction), when selected, do not change the label until multiple tries. I tried changing the last line to an "else label3.text=("/");" but it doesn't really change anything other than the order of errors.
Any help would be appreciated! Thanks :)
I think you need to check if the radio button is checked in each individual radioButtonX_CheckedChanged method like so:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label3.Text = ("+");
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
if (radioButton2.Checked)
{
label3.Text = ("-");
}
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
if (radioButton3.Checked)
{
label3.Text = ("x");
}
}
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
if (radioButton4.Checked)
{
label3.Text = ("/");
}
}
Let me know if that helps, and if you are still having the issue.
You may want to change how you check for the Checked button. MrB's solution works, but if you'd like to keep your selection code in a single block (as you have), make sure all your radio buttons have their CheckedChanged event subscribed to something similar to the following:
private void RadioButtonCheckedChanged(object sender, EventArgs e)
{
var radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
switch (radioButton.Text)
{
case "Add":
label3.Text = "+";
break;
case "Subtract":
label3.Text = "-";
break;
case "Divison":
label3.Text = "/";
break;
}
}
}
You can also switch on another property, such as the RadioButton.Tag field, whatever may be meaningful to you.
As far as the actual reason your code is failing, it's hard to understand without ensuring which RadioButton's have their events set properly, and seeing the incorrect results.
protected void Page_Load(object sender, EventArgs e)
{
agm.Visible = RadioButtonList1.SelectedValue == "1" ? true : false;
}
I have a ListView with various items and a ItemCheck handler as below:
private void ListView1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == System.Windows.Forms.CheckState.Checked)
{
if (e.Index == 0)
{
ListView1.Items[1].Checked = false;
ListView1.Items[2].Checked = false;
ListView1.Items[3].Checked = false;
ListView1.Items[4].Checked = false;
ListView1.Items[5].Checked = false;
ListView1.Items[6].Checked = false;
ListView1.Items[7].Checked = false;
}
else
{
ListView1.Items[0].Checked = false;
}
}
}
Essentially the first item is "none", so when it is checked all the other items become unchecked (and vice-versa). Occasionally the program checks items in the code and I think this is causing problems. I know TreeViewEventArgs has a field called Action which is equal to TreeViewAction.Unkownif the call is coming from the program and not from the user.
Is there a way to check if a ListViewItem is being checked by a user as opposed to being checked by code?
There's no way to tell from the event arguments so you would have code for it yourself, something like
private bool raisedFromCode;
private void button2_Click(object sender, EventArgs e)
{
raisedFromCode = true;
listView1.Items[1].Checked = !listView1.Items[1].Checked;
raisedFromCode = false;
}
private void listView1_ItemCheck(object sender, ItemCheckEventArgs args)
{
if (!raisedFromCode)
MessageBox.Show("User checked");
}
Alternatively if you just don't want your logic to fire when you change the check state through code you could unsubscribe from the event handler
listView1.ItemCheck -= new ItemCheckEventHandler(this.listView1_ItemCheck);
listView1.Items[1].Checked = false;
listView1.ItemCheck += new ItemCheckEventHandler(this.listView1_ItemCheck);