Hello i want to disable / enable button with check box.
myproject:
If I understood correctly you question, there is a property called Enabled on the Control.
Here is a link to that property documentation
Update: (Just to make more clear the answer based on comments)
It belogns to the Winforms API as this property is part of the Namespace of System.Windows.Forms
As most (if not every) control inherits from Control Class and this Class has the Enabled property which states that "Enabled
Gets or sets a value indicating whether the control can respond to user interaction."
So, every Control that inherits from this Class can use that property.
Hello if you want do get your button enabled or disabled try something like this.
first set the button.enable to false:
button.enabled = false;
then:
if(checkbox.checked == true)
{
button.enabled = true;
}
else
{
//let the user know with messagebox that he needs to accept the terms
}
Related
I want a button on my winform to be enabled or disabled based on the return value of a particular function. Basically, I'm trying the following code in various places where the function will possible return a different value:
btnNewNotices.Enabled = isSelectedPrinterValid();
this.btnNewNotices.Refresh()
However, this is not working. Why is it when I call the refresh method after the enabled property is changed, that the button does not become enabled? I have to close the form and reopen it before the button properly disables. What is the best way to accomplish what I need here without having to bounce the form?
you can add a Databinding for the Enabled property.
if your method is implemented in your Form then you can define a Property
public bool IsSelectedPrinterValid
{
get{ return this.isSelectedPrinterValid(); }
}
And add a Databinding as following:
btnNewNotices.DataBindings.Add("Enabled", this, "IsSelectedPrinterValid");
You can refresh your value:
btnNewNotices.DataBindings[0].ReadValue();
The common way is to implement a ViewModel containing all Properties and Methods you need and bind your controls to these.
Short answer, but it's pretty straight forward.
Using .Refresh(); causes the button to repaint itself, and resets the Enabled property. There's no reason to use it in your context. Just remove it.
btnNewNotices.Enabled = isSelectedPrinterValid();
I'm thinking about the best way to validate user input.
Let's imagine some TextBoxes, CheckBoxes or whatever .NET control you please, where the user input has to be validated as OK or NOK. As soon as the user's filled up all required fields he submits via a button.
Now I have to know which fields were previously confirmed as OK and which as NOK. By now I've always handled such cases by declaring a global bool variable for every control to tell me so. But I don't like that...
I'm pretty sure there must be another way! What I would like to do is expanding these .NET controls with a OK or NOK property called status or similar. Can you do that? And if so how do you do it? Is something like that already existing?
Thank you for your response!
You have some useful features in windows forms to perform validation and show error messages including:
IDataErrorInfo Interface
Validating Event of Controls
ErrorProvider Component
ValidateChildren Method and AutoValidate Property of Form
Using above options:
You can perform validation when you are using data-binding to model classes.
You van perform validation when you don't use data-binding.
You can show error messages and an error icon near the controls which are in invalid states.
You can decide to prevent the focus change from invalid controls or let the focus change.
You can show a validation summary for your form.
You can also apply DataAnnotations Validations in Windows Forms
IDataErrorInfo Interface
In cases which you have some model classes, the best fit for validation and providing error messages in windows forms is implementing IDataErrorInfo. It's supported by data-binding mechanisms and some windows forms control like DataGridView and ErrorProvider.
To keep things simple you can write validation rules in your class and return error messages using IDataErrorInfo properties. Even if you want to apply a more advanced scenario like using validation engines, at last it's better to implement IDataErrorInfo to gain most consistency with widows forms.
You will use an ErrorProvider to show error messages. It's enough to bind it to your data source and it shows errors automatically.
Validating Event of Controls
In cases that you don't have model classes and all validations should be done against controls, the best option is using Validating event of controls. There you can set e.Cancel = true to set the control state as invalid. Then you can prevent focus change or use the state of control in getting validation summary.
In this case you will use an ErrorProvider to show errors. It's enough to set an error for a control in Validating event this way: errorProvider1.SetError(control1, "Some Error") or you can set an empty error message to remove validation error.
ErrorProvider Component
In both cases when you use databinding or when you use Validating event, as mentioned above, ErrorProvider shows and error icon with a tooltip that shows error message for you near the controls. (DataGridView uses its own mechanism to show errors on rows and cells, without using an ErrorProvider.)
You can also use the component to get a validation summary for your form using GetError method of the component which return the error message of each control.
ValidateChildren Method and AutoValidate Property of Form
You can use ValidateChildren method of form or your container control to check if there is a validation error for your controls or not.
Based on the value of AutoValidate property of your form, it prevents focus change or let the focus change from invalid controls.
Save the names of your controls to be validated into an array and then just loop through them. You can also set a validation function onto them, if you want to.
var elements = new[] {
new { Control = textBox1 },
new { Control = textBox2 }
};
foreach (var elem in elements)
{
elem.Control.BackColor = string.IsNullOrWhiteSpace(elem.Control.Text) ? Color.Yellow : Color.White;
}
Wrap your Elem array into class objects to add a "ok" property.
It really depends how deep you want to delve into that rabbit hole...
You need to decide on the validation statuses - if it's simply a case of Yes/No, then Boolean/bool will suffice, otherwise you should consider creating an enumeration to hold your validation statuses.
You will need to decide whether you want to extend the controls that require validation, or just use the control's Tag property to store the validation status (personally I think that using Tag to do this is hideous).
An Example:
// Provides your validation statuses.
public enum ControlValidation
{
Ok,
NotOk
}
// Provides a contract whereby your controls implement a validation property, indicating their status.
public interface IValidationControl
{
ControlValidation ValidationStatus { get; private set; }
}
// An example of the interface implementation...
public class TextBox : System.Windows.Forms.TextBox, IValidationControl
{
public ControlValidation ValidationStatus { get; private set; }
...
protected override void OnTextChanged(EventArgs e)
{
ValidationStatus = ControlValidation.Ok;
}
}
All winforms components have a "spare" property which you can use: Tag. It's an object and you can assign whatever to it: it's not used for anything by the framework, and it's useful for cases like this.
If this is going to be generalized, you can just derive your controls and add your properties, but for a one-time single-property, Tag could perfectly work.
// OK
myTextBox.Tag = true;
// NOK
myTextBox.Tag = false;
// Undefined
myTextBox.Tag = null;
To check:
if(myTextBox.Tag is bool)
{
var isOk = (bool)myTextBox.Tag;
if(isOk)
{
// It's OK
} else {
// It's NOK
}
} else {
// It's undefined
}
All that said, I use Tag for simple things and simple logics. If you plan to have more properties or it's a generalized thing... either use the validation mechanisms explained in the other answers, or derive your controls:
public class MyTextBox : System.Windows.Forms.TextBox
{
public bool ValidationOK { get; set; }
}
And change the controls to MyTextBox (if you already have them, open the designer.cs file and change all instances of System.Windows.Forms.TextBox to <yourNamespace>.MyTextBox), etc.
I have an ASP.NET checkbox that based on certian logic I need to set its checked value to true server-side. This is easy enough, but it fires the wired up MyCheckBox_CheckedChanged(object sender, EventArgs e) event as well.
That event's code is 100% ok, as long as it is called when the user checks the check box from the client. However, when I'm just trying to set that checkbox to be Checked = true; server-side I don't want the code in the event to run.
The cleanest way I would like to approach this was to inspect the sender object on the event and see if this event was really called by the client or not (like: http://msdn.microsoft.com/en-us/library/aa457091.aspx). However this did not yield any distinguishing information. It still looked like the checkbox being selected called it.
My 2nd thought is to set some session value and inspect this to basically return if not being called by the user. I can easily do this, but I don't like using 'public flags' of sorts unless absolutely necessary. I'd rather (if at all possible) inspect the sender or arguments on that event to determine if that property was set server side on reload of data from the database, or if the user actually selected it.
I saw this Prevent postback on server-side property change and it was not a direct solution to my question, but rather a work around not applicable to my situation.
Is there a way to determine this was set solely server side so that I can bypass running this code?
Add a private boolean variable dontFire to the top of your class with a default value = false.
Then use the following:
dontFire = True;
myCheckbox.Checked = True;
dontFire = False;
Then in the myCheckBox.CheckedChanged event put this at the top:
if (dontFire) return;
Problem solved.
If I am correct you are trying to set the checked property of check box true on load/initialize of the page.
Here are a couple of approaches you may follow:
Another approach to deal with the situation you mentioned could be to dynamically bind the controls (your checkbox's) event on the page load only if you are not setting the checkbox's checked property to true.
Use a simple page property as a flag to signify if the checked property had been set server side, and use it inside the check box's change event handler. You do not need to use session, as you may not need to persist this value across post back.
If possible put the logic to set the checked property of the check box to true in the check box's change event handler, and based on whether or not you are setting the property you can allow/disallow the handler code.
This would be my recommended solution:
public bool Check_CheckBox
{
set
{
checkbox1.Checked = value;
if (value)
{
checkbox1.CheckedChanged -= new EventHandler(this.Check_Clicked);
}
}
get
{
return checkbox1.Checked;
}
}
set the Check_CheckBox property to true based on your logic and it will do the trick.
Hope this helps.
I have a custom control with a bool property. In the designer, I drag the user control to a form and I change this property to "false", which is supposed to hide a child control.
It is indeed hiding it in runtime, but not in design time. How could I "refresh" my user control in design time to reflect the changes to this property?
I don't know why you want to do this. The Control will only be hidden at runtime and this is how it was meant to be. Maybe you can create something to hide it at Design-Time or add another control over it to hide it.
How could I "refresh" my user control in design time to reflect the changes to this property?
You can't. Changes apply automatically the only reason why you still see it is because that's how it should be.
This worked as is using Visual Studio 2012:
public class TestControl : Control {
Button button;
public TestControl() {
button = new Button() { Text = "Click" };
this.Controls.Add(button);
}
public bool ButtonVisible {
get { return button.Visible; }
set {
button.Visible = value;
}
}
}
I'm afraid I didn't ask my question correctly - I was inheriting from a rather complex third-party control and I wanted to see a change in design time.
I ended up overriding OnCreateControl. I appreciate your help nevertheless.
I have a dialog with loads of control in it. Each and evey control will be populated during the loading sequence and it might take a while for it to get completely filled. Mean while, I don't wanna allow the user to click on any of the controls. In other words, I wanna disable the control from receiving the events and I don't wanna disable the controls (as it might look odd).Also, I don't wanna subscribe and unsubscribe for the events regular intervals. Is there any way to stop the controls from listening to the events for a brief time ??
Sudarsan Srinivasan
The whole point of disabling controls is to communicate to the user that the control cannot be used at a particular time. This is a convention that users have learned and are used to, so I would advice to follow that. Not doing that may confuse the users.
The easiest way is to disable the container in which the controls are located in, rather than disabling each and every control. A better way (or at least the way that I prefer) is to have a method that will control the Visible and Enabled properties of controls based on which state the UI is in.
The easiest way is to move the control population out of the load event (if possible). Then in Load do something like:
private bool _LoadComplete;
void OnFormLoad(Object sender, EventArgs e)
{
_LoadComplete = true;
InitializeControls();
_LoadComplete = false;
}
void InitializeControls()
{
// Populate Controls
}
void OnSomeControlEvent()
{
if (_LoadComplete)
{
// Handle the event
}
}
Edit A Couple other Ideas:
Set the Application.Cursor = WaitCursor (typically will disallow clicking, but not a 100% guarantee)
Create a "Spinner" control to let the user know that the screen is busy. When loading bring it to the front so it sits on top and covers all other controls. Once you're done loading set it to visible = false and show your other controls
Unfortunately the only way i know of is to have a class variable (called something like _loading) and in each control handler do something like:
If (! _loading )
{
...
}
And in your loading code set _loading = true; once you have finished loading.
If you just want to disable user input, then you can set the form's Enabled property to false.
This has the effect of blocking user input to any of the form's controls, without changing the appearance of the controls; it's the technique used internally by the ShowDialog method.