I am programming in c# and I have some radio buttons in my form, and I want to make validation assuring that the user selected all the radio buttons in the button, so my method is :
public bool check_radiobutton(RadioButton radio1, RadioButton radio2)
{
//none of them aare selected
if ((radio1.Checked) && (radio2.Checked))
{
return false;
}
else
{
MessageBox.Show("You forgot to select a radiobutton!");
}
return true;
}
but it did not work
For each pair of radio button you have (or for each set, being it pairs for yes/no questions). You must check if at least (in fact if only) one of the options is checked. That is you want to check if:
(radio1.Checked) || (radio2.Checked)
Why is it? Because this way you are asking if radio1 is checked or else if radio2 is checked. Otherwise, if you keep:
(radio1.Checked) && (radio2.Checked)
You are asking if radio1 is checked and also if radio2 is checked. Which can't be, that's like requesting to answer both "yes" and "no". Of course this will never evaluate to true, unless there is something inherentily wrong with the universe.
From your comment:
//none of them aare selected
I guess you were trying to use D' Morgan's law, which applied to this cases states that:
(radio1.Checked) || (radio2.Checked) == !((!radio1.Checked) && (!radio2.Checked))
You can read this code:
!((!radio1.Checked) && (!radio2.Checked))
As follows: If it's false that (radio1 is not checked and also radio2 is not checked). That will be false only if both are not checked, which is the case when you want to return false (that is you want to return true when that evaluates to true):
if (!((!radio1.Checked) && (!radio2.Checked)))
{
return true;
}
else
{
return false;
}
By reversing the if, you end up with:
if ((!radio1.Checked) && (!radio2.Checked))
{
return false;
}
else
{
return true;
}
Which is close to what you have, but not quite the same thing. So, a proposed implementation for your method would be [I changed your style to mine]:
public bool CheckRadioButtons(RadioButton radioButtonA, RadioButton radioButtonB)
{
//none of them are selected
if ((!radioButtonA.Checked) && (!radioButtonB.Checked))
{
return false;
}
else
{
MessageBox.Show("You forgot to select a RadioButton!");
return true;
}
}
Also, as I think you may want to take out the MessageBox from there you can compress the method to:
public bool CheckRadioButtons(RadioButton radioButtonA, RadioButton radioButtonB)
{
return !((!radioButtonA.Checked) && (!radio2.radioButtonB));
}
A generalization would be something like:
public bool CheckRadioButtons(params RadioButton[] radioButtons)
{
foreach (RadioButton radioButton in radioButtons)
{
if (radioButton.Checked)
{
return true;
}
}
return false;
}
You may still show the messegebox in the caller if you like [Which I think is a good thing separate those concerns]. Also if you are using Linq [Remeber to add "using System.Linq" at the top of yout file or namespace block, avaliable form .NET 3.5]:
public bool CheckRadioButtons(params RadioButton[] radioButtons)
{
return radioButtons.Any(radioButton => radioButton.Checked);
}
Given the simplicity of this, you may consider skip to create a method for this altogether. Here is how you may call this with only two RadioButtons without an additional method:
(new RadioButton[]{radioButtonA, radioButtonB}).Any(radioButton => radioButton.Checked);
Of course it's an overhead for simple cases as the one with only two RadioButtons, so having a method will allow you to overload it for the simple cases (such as 2 RadioButtons and 3 RadioButtons).
In your if statement you check if both the radiobutons are checked, but this will never happen because always on of the radio buttons will be check. You should use checkboxes to make this happen or change the && to || to check that at leased one of the buttons is checked.
Radio buttons are generally used to represent options which are mutually exclusive. Checkboxes better represent what you seem to need (multiple choices).
If I try to add two radio buttons on a form I see that only one of them can be checked (the other is automatically unchecked when I do this).
This means that the two radio buttons will never be checked at the same time and the MessageBox will always show...
EDIT:
Only one of the radio buttons inside a container can be checked at a time.
You can use this to implement "either A or B" and "either C or D" by having 2 panels, one with radio buttons for A and B and another panel with radio buttons for C and D.
Since it is possible for neither radio button to be checked a valid state is the one where one of the buttons is checked. You don't check this with && (which is AND ) but with || (which is OR).
bool IsValid = radio1.Checked || radio2.Checked;
Related
I am making myself a project manager and I need to refresh Project List every so often. When I am refreshing the Project Manager, I want to select the item that was previously selected. But that selection causes my text box to unselect, therefore, what happens is that that text box unselects after typing one key.
So outline what happens:
I try to edit one text box
Edition causes update in project -> program calls RefreshProjectList()
RefreshProjectList() on marked position causes selected text box to unselect
Result: You must select text box after writing one symbol
Picture if useful
These selected text boxes are struggling to be edited
Code:
private void RefreshProjectList() {
if (BlockListReload)
return;
Project selected = (Project)ProjectList.SelectedItem;
ProjectList.Items.Clear();
CurrentlyShown.Clear();
foreach(Project p in Projects){
if (p.state == State.Planned && ShowPlanned.Checked) {
CurrentlyShown.Add(p);
ProjectList.Items.Add(p);
}
if (p.state == State.Active && ShowActive.Checked) {
CurrentlyShown.Add(p);
ProjectList.Items.Add(p);
}
if (p.state == State.Finished && ShowFinished.Checked) {
CurrentlyShown.Add(p);
ProjectList.Items.Add(p);
}
if (p.state == State.Delayed && ShowDelayed.Checked) {
CurrentlyShown.Add(p);
ProjectList.Items.Add(p);
}
}
if (selected == null)
return;
if (ProjectList.Items.Contains(selected)) {
ProjectList.SelectedItem = selected; // IF I REMOVE THIS
} else {
if (ProjectList.Items.Count > 0)
ProjectList.SelectedIndex = 0; // OR THIS LINE, EVERYTHING WORKS
}
}
If you need more code, I will be happy to provide, but I don't want to spam you with loads of unuseful code.
Q: Why does changing selected item in ListBox cause deselecting of TextBox and how to prevent it?
Several controls that have selectable text or items also come with a property HideSelection.
This includes:
TextBox
RichTextBox
ListView
but not
ListBox
CheckedListBox
DataGridView
Like it or not it always defaults to true so the selection is hidden whenever the focus is off the control..
Simply set it to false in the designer and you can see all selection no matter where the focus is..
OMG. I honestly don't know why I did not see it.
ProjectList.SelectedItem = selected;
//where ProjectList is ListBox<Project> and selected is Project
I am selecting an item in the ProjectList(ListBox). I didn't realize that it was calling a ProjectList_SelectedIndexChanged() event which was doing it.
EDIT: SOLVED by adding this:
if (focused != null) {
this.ActiveControl = focused;
focused.Select(focused.TextLength,0);
}
Where focused is a TextBox I set to last selected TextBox and this is the form.
Thanks TaW.
FastColoredTextbox is an user-control that can be downloaded in this url, it looks like this:
Its an amazing control but only can select one word when doubleclicking on the text, can't hold the mouse to select more words, so it only selects the entire current word over the mouse pointer even if you try to move the mouse cursor to left or right to select more text.
I have not found any information explaining the problem, and all of the official example projects has this problem.
Nobody means how to make an AutoWordSelection equivalent of a default TextBox for a FastcoloredTextbox control, but even the most important thing is:
How to select just more than one word with the mouse?
UPDATE:
#mostruash answer is very instructive but in all this time I could not carry out the modifications by myself.
I need a huge help from a C# programmer to carry out this task, my knowledge of C# is very low and the modifications that I made to the source did not work (don't compiled), I went back to the original user-control source to not end up spoiling more. I hate to say this but this time I need the job done, this source is too much for me.
If I'm requesting for too much then maybe with the necesary extended instructions of a C# developer, explaining how to accomplish this step by step, maybe I could carry it out by myself.
UPDATE
A video that demostrates the problem:
https://www.youtube.com/watch?v=Cs2Sh2tMvII
UPDATE
Another demo, I show what the FastColoredTextBox can't do but I would like to do like every other text-editor can do:
I've checked the source code of the project. Dragging is cancelled if a double click occurs and SelectWord is called.
You could modify the source code to include the feature that you request. (https://github.com/PavelTorgashov/FastColoredTextBox). In that case:
You must trace selections that start with double clicks.
Instead of calling SelectWord function, use the Selection class and draggedRange attribute to mark the selected word in OnMouseMove.
You also must handle deselection of words in OnMouseMove.
You must also select spaces between words in OnMouseMove.
The double click is handled in the code piece below:
if (!isLineSelect)
{
var p = PointToPlace(e.Location);
if (e.Clicks == 2)
{
mouseIsDrag = false; //Here, drag is cancelled.
mouseIsDragDrop = false;
draggedRange = null; //Drag range is nullified
SelectWord(p); //SelectWord is called to mark the word
return;
}
if (Selection.IsEmpty || !Selection.Contains(p) || this[p.iLine].Count <= p.iChar || ReadOnly)
OnMouseClickText(e);
else
{
mouseIsDragDrop = true;
mouseIsDrag = false;
}
}
EDIT:
This may require a lot of work to accomplish. So maybe you should use another tool/library. I have not studied the whole source code so there will probably be additional steps to those provided above.
For example, to trace double clicks you can do the following:
Define a class variable/property in FastColoredTextbox.cs: bool isDoubleClick.
Set it to true in OnMouseDown under if(e.Clicks == 2) condition. Set it to false in all other conditions.
Set it to false in OnMouseClick or OnMouseUp or in other relevant mouse event handlers.
That way you will know if series of mouse events had started with a double click event or not. Then you would act accordingly in OnMouseMove because that is where you (un)mark characters or (un)mark words.
LAST WORDS OF CAUTION:
The author of that project did not include any inline comments or any other means of documentation so you will be studying the code line by line to understand what each function/part does.
Add the following statement between Line 5276 and line 5277 in the class FastColoredTextBox.cs:
SelectWord(p);
mouseIsDrag = true; // here
return;
Note that implementing the ultimate behavior would require a good bunch of coding. Whereas the workaround mentioned above might satisfy your needs.
As #mostruash points out in his answer, that is the place where author cancels the mouse drag. Not sure why he deliberately prevents this feature. Only he knows.
if (e.Clicks == 2)//Line 5270
{
mouseIsDrag = false;
mouseIsDragDrop = false;
draggedRange = null;
SelectWord(p);
return;
}
I didn't read whole code, and I have no reason to do it. I just checked quickly and removed them. And it works as you expect.
if (e.Clicks == 2)//Line 5270
{
//Comment or remove completely.
//mouseIsDrag = false;
//mouseIsDragDrop = false;
//draggedRange = null;
SelectWord(p);
return;
}
Note: Am not sure this breaks something else, I've not tested. At least that works. Test it yourself.
My solution is a bit tweaky, but seems to work at first glance.
You have to make some changes in the Code:
Add mouseIsWholeWordSelection flag and a Range variable which can store the initial selected range after double click (best after line 100, I guess):
private bool mouseIsWholeWordSelection;
private Range mouseIsWholeWordSelectionBaseRange;
Change the selection code for double click event as stated above and extend it a bit (line 5222):
if (e.Clicks == 2)
{
//mouseIsDrag = false;
mouseIsDragDrop = false;
mouseIsWholeWordSelection = true;
//draggedRange = null;
SelectWord(p);
mouseIsWholeWordSelectionBaseRange = Selection.Clone();
return;
}
Add evaluation of dragging event for recreating selection (line 5566):
else if (place != Selection.Start)
{
if (mouseIsWholeWordSelection)
{
Selection.BeginUpdate();
var oldSelection = Selection.Clone();
SelectWord(place);
if (Selection.End >= mouseIsWholeWordSelectionBaseRange.End)
{
Selection.Start = (mouseIsWholeWordSelectionBaseRange.Start > Selection.Start) ? mouseIsWholeWordSelectionBaseRange.Start : Selection.Start;
Selection.End = mouseIsWholeWordSelectionBaseRange.End;
}
else if (Selection.Start < mouseIsWholeWordSelectionBaseRange.End)
{
Selection.Start = new Place(Selection.End.iChar, Selection.End.iLine);
Selection.End = mouseIsWholeWordSelectionBaseRange.Start;
}
Selection.EndUpdate();
DoCaretVisible();
Invalidate();
}
else
{
Place oldEnd = Selection.End;
Selection.BeginUpdate();
if (Selection.ColumnSelectionMode)
{
Selection.Start = place;
Selection.ColumnSelectionMode = true;
}
else
Selection.Start = place;
Selection.End = oldEnd;
Selection.EndUpdate();
DoCaretVisible();
Invalidate();
}
return;
}
Add at every place where isMouseDrag is being set to false:
isMouseWholeWordSelection = false;
And there you go.
I have a wepage for a user to sign up,i have tested it and runned it,i was testing it using space not entering any words to signup,meaning a user can signup without entering any words just by using space.so i dont want this to happen to my webpage.
any one who has some code that i can use to validate this...
You can use the method: string.IsNullOrWhiteSpace to check
either the simple string.IsNullOrWhiteSpace
or if you really want to use the answer you chose, you should edit it to:
if (firstName ! = null && lastName ! = null)
{
if (firstName.Trim()=="" || lastName.Trim()=="")
{
return False;
}
else
{
return True;
}
}
else return False;
you can validate user input in many ways. One of them is to use built in Visual Studio Vaidator controls and make sure that each control is tighed to a text box in your form and its preoperty is selected to ensure the field is filled before submitting the form.
Another way is to do the validation from the code behind. Something like this:
if (firstName.Trim()=="" || lastName.Trim()=="")
{
return False;
}
else
{
return True;
}
I am having the strangest problem, and I have to be missing something.
Here is my code that is causing the error.
if (radLot.Checked == true)
{
SymbolSpecification = "LotRenderer";
}
if (radWaterMeter.Checked == true)
{
SymbolSpecification = "WaterMeterRenderer";
}
As you can see, I don't even use =+ or -=... I actually don't have it anywhere in my code... Any help would be appreciated.
Checked is the name of the event that is raised when a ToggleButton is checked. (The RadioButton class derives from ToggleButton.)
I assume you want to access the IsChecked property, which gets (or sets) whether the ToggleButton is checked.
if (radLot.IsChecked == true)
{
SymbolSpecification = "LotRenderer";
}
Hint: Most boolean properties related to the visual state start with Is— in WPF.
Alternative you can check the CheckState to perform your statement.
if (radLot.CheckState == CheckState.Checked)
{
}
Edit:
This will only work when writing a winform application. It will not work with WPF. Use Douglas' answer for WPF.
This is indeed true - just hit this problem myself converting from Winforms to WPF.
In WPF using:
if (radiobutton1.IsChecked == true)
works
BUT
if (radiobutton1.IsChecked)
Does not.
However in WinForms
if (radiobutton1.Checked)
works but does not in WPF.
I have created a messagebox which returns DialogResult. Now I added checkbox on it and want to know if it is checked or not. So what should I return? The simple way I thought is to create new enum which will have all the values from DialogResult plus a value to indicate checkbox status
public enum MyDlgResult
{
NONE = DialogResult.NONE,
OK = DialogResult.OK ........................,
CHKBOXCHECKED = 8
}
...and returning this enum MyDlgResult.
But is this correct approach? Because I have to add value in this enum every time a new functionality is added to my messagebox.
Better way to do this if any.
Thank You.
Just add Property to that message box, which will be a proxy to Checked property of CheckBox and on OK result form message box check that new Property.
Property to add
public bool Checked
{
get { return yourCheckBox.Checked; }
}
And final code like this
MessBox box = new MessBox();
if(box.Show() == DialogResult.OK)
{
bool isChecked = box.Checked;
}
You don't have to override the return of a dialog to enable the client code to get the state of a UI control. The dialog information is retained after it is closed and you can get values from it. For example, assume that there is a Form class named SomeDlg with a property called PublicDlgProperty. PublicDlgProperty can be set on OK, or any other UI change and then queried after the dialog is closed, like this:
var someDlg = new SomeDlg();
someDlg.ShowDialog();
var someLocalVariable = someDlg.PublicDlgProperty;
This is a very simple example. You'll need to test the DialogResult to see if you want to query the value or not.
I agree with both other people who answered you that you should have a property, delegating the IsChecked or something, but if you must do it using only the return enum result...
Make the enum Flagged:
[Flags]
public enum MyDlgResult
{
NONE = ...
OK = ...
CHK...
}
Then, you can return:
return MyDlgResult.NONE | MyDlgResult.CHK;
Or
return MyDlgResult.OK | MyDlgResult.CHK;
Or just
return MyDlgResult.OK;
And so on...
Then, you can check:
if (res.HasFlag(MyDlgResult.OK))
{
}
if (res.HasFlag(MyDlgResult.CHK))
{
}