How can I get a value returned from the checkbox_CheckChanged event please? Its a winforms app, and both the form and the checkbox are created programmatically. Thanks for all and any help.
The Controls event handlers are always "void" and you cant change the return type. Instead you can take an external variable and you change that value only in when the CheckedChanged Event occurs.
public bool checkedthecheckbox { get; set; }
CheckBox testchbox = new CheckBox();
private void Form1_Load(object sender, EventArgs e)
{
testchbox.CheckedChanged += new EventHandler(testchbox_CheckedChanged);
}
void testchbox_CheckedChanged(object sender, EventArgs e)
{
if (testchbox.Checked)
checkedthecheckbox = true;
else
checkedthecheckbox = false;
}
You can get the value from 'sender' object.
CheckBox chk = (CheckBox) sender;
bool result = chk.Checked;
You can get the state of the Checkbox by casting the sender object from the event arguments:
public void Method1()
{
CheckBox checkBox = new CheckBox();
checkBox.CheckedChanged += new EventHandler(checkBox_CheckedChanged);
}
void checkBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
bool resutlt = c.Checked;
}
Hope this helps!
You can use CheckState.Checked or CheckState.Unchecked, which is built in C#. Example:
for (int i = 0; i < lsbx_layers.Items.Count; i++) {
if (lsbx_layers.GetItemCheckState(i) == CheckState.Checked) {
//set boolean variable to true
} else if (lsbx_layers.GetItemCheckState(i) == CheckState.Unchecked) {
//set boolean variable to false
}
}
I've got an alternative to change the regular check box changed event into an event that provides you with the changed Checked value directly.
You could, for example, use it this way:
var myForm = new MyForm();
myForm.CheckBoxChanged += v =>
{
Console.WriteLine("The value of the checkbox changed to {0}", v);
};
Here's the class definition:
public class MyForm
{
public event Action<bool> CheckBoxChanged;
private CheckBox testchbox = new CheckBox();
private void Form1_Load(object sender, EventArgs e)
{
testchbox.CheckedChanged += (s, e) =>
{
var cbc = this.CheckBoxChanged;
if (cbc != null)
{
cbc(testchbox.Checked);
}
};
}
}
I hope this helps.
Related
I have a groupbox with 16 checkboxes and I need to run an event that knows the button pressed if any of them change states.
I know I can add an on click action for each but is there a cleaner way of doing this?
I realized that you can just reuse actions and cast the sender object:
private void InputSwitched(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
}
You can handle checked events of all the checkboxes of the groupbox, using a single event handler, like this:
public Form1()
{
InitializeComponent();
groupBox1.Controls.OfType<CheckBox>()
.ToList().ForEach(c => c.CheckedChanged += C_CheckedChanged);
}
private void C_CheckedChanged(object sender, EventArgs e)
{
var c = (CheckBox)sender;
MessageBox.Show($"{c.Name} - Checked: {c.Checked}");
}
Here's what I meant in the comments about dynamically creating the controls.
You can do something like this:
private List<CheckBox> _checkBoxes = null;
public Form1()
{
InitializeComponent();
var checkbox_count = 15;
_checkBoxes =
Enumerable
.Range(0, checkbox_count)
.Select(x => new CheckBox()
{
Text = $"CheckBox {x}",
})
.ToList();
foreach (var checkbox in _checkBoxes)
{
flowLayoutPanel1.Controls.Add(checkbox);
checkbox.CheckedChanged += (s, e)
=> checkbox.BackColor =
checkbox.Checked
? Color.Red
: Color.Blue;
}
}
I found lot of answers on Stack Overflow how to disable specific cell in DataGrid in Windows Forms or WPF. Now I want to ask same question in DevExpress. Thank you for your answers!
My current somehow working code prevent user to check specific checkbox in grid but this checkbox dosen't look like it is disabled. How can I visually disable this field making it gray or none visible at all?
bool expression = ... // some expresssion
private void grid_ShownEditor(object sender, EventArgs e)
{
GridView view sender as GridView;
if(view.FocusedColumn.FieldName == "specific column name with checkbox cells")
{
var row = view.GetRow(view.FocusedRowHandle);
view.ActiveEditor.Enabled = expression;
}
}
Use GridView.ShowingEditor and GridView.CustomDrawCell to do what you're after. See:
private bool isDisabled = false;
private bool IsDisabled(int row, GridColumn col)
{
if (col.FieldName == "somename")
return isDisabled;
return false;
}
private void GridView_ShowingEditor(object sender, CancelEventArgs e)
{
var gv = sender as GridView;
e.Cancel = IsDisabled(gv.FocusedRowHandle, gv.FocusedColumn);
}
private void GridView_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
{
if(IsDisabled(e.RowHandle, e.Column))
{
e.Appearance.BackColor = Color.Gray;
e.Appearance.Options.UseBackColor = true;
}
}
If you would like to not show a checkbox at all, you can do this:
private static RepositoryItemTextEdit _nullEdit;
public static RepositoryItemTextEdit NullEdit
{
get
{
if (_nullEdit == null)
{
_nullEdit = new RepositoryItemTextEdit();
_nullEdit.ReadOnly = true;
_nullEdit.AllowFocused = false;
_nullEdit.CustomDisplayText += (sender, args) => args.DisplayText = "";
}
return _nullEdit;
}
}
private void GridView_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
{
if(IsDisabled(e.RowHandle,e.Column))
{
e.RepositoryItem = NullEdit;
}
}
I programmatically create a Form with two textboxes. My goal is to disable one textbox if I type something in the second one and contrariwise. I managed to disable second textbox on first textbox textchange,but can't figure out how enable it when the first textbox.Text is empty.
Here is the code :
private void metaName_TextChanged(object sender,EventArgs e)
{
var ctrl = (Control)sender;
var frm = ctrl.FindForm();
TextBox metaTxt = null;
foreach (var ctr in frm.Controls)
{
if (ctr is TextBox)
{
metaTxt = (TextBox)ctr;
if (metaTxt.Name == "metaHTTPEquiv")
{
metaTxt.Enabled = false;
}
else
if (?)
{
}
}
}
}
I want to make something like this :
if(textBox3.Text == String.Empty)
{
textBox4.Enabled = true;
}
else
if(textBox3.Text != String.Empty)
{
textBox4.Enabled = false;
}
You can check only the textchanged event for each one like the following:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Enabled = !(textBox1.Text.Length >= 1);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Enabled = !(textBox2.Text.Length >= 1);
}
The self textbox has some values, then the enabled will be false for the other one
First set a flag to enable or disable the second control based on the content of the metaName textbox that raises the event, then search for the second textbox using a bit of Linq.
private void metaName_TextChanged(object sender,EventArgs e)
{
TextBox ctrl = sender as TextBox;
if(ctrl != null)
{
bool enable = !string.IsNullOrEmpty(ctrl.Text);
TextBox secondOne = this.Controls
.OfType<TextBox>()
.FirstOrDefault(x => x.Name == "metaHTTPEquiv");
if(secondOne != null)
secondOne.Enabled = enable;
}
}
The same code, reversing the textboxes roles, could be used as the event handler of the second textbox.
Forget about control events and use data binding.
Take the following helper method
static void Bind(Control target, string targetProperty, object source, string sourceProperty, Func<object, object> expression)
{
var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never);
binding.Format += (sender, e) => e.Value = expression(e.Value);
target.DataBindings.Add(binding);
}
and just add something like this in your form load event
Bind(textBox2, "Enabled", textBox1, "Text", value => string.IsNullOrEmpty((string)value));
Ok here is my question. I assign value to each checkboxes I created, and am trying to put them into listbox only when they are checked, after a button click. So here is the code that I have written so far, in which when the button is clicked, both the values are written into listbox, whether they are checked or not, how can I make it work as I explained?
public Form1()
{
InitializeComponent();
btnOne.Click += btnOne_Click;
chckOne.CheckedChanged += chckOne_CheckedChanged;
chckTwo.CheckStateChanged += chckTwo_CheckStateChanged;
}
void btnOne_Click(object sender, EventArgs e)
{
lstOne.Items.Add(number1 + number2);
}
string number1 = "ONE", number2 = "TWO";
void chckOne_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = new CheckBox();
if (chk.Checked == true)
{
lstOne.Items.Add(number1);
}
}
void chckTwo_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = new CheckBox();
if (chk.Checked == true)
{
lstOne.Items.Add(number2);
}
}
Just define one method:
void chkBox_CheckedChanged(object sender, EventArgs e)
{
var chkBox = sender as CheckBox;
if (chk.Checked == true)
{
lstOne.Items.Add(chkBox.Text);
}
else
{
lstOne.Items.Remove(chkBox.Text);
}
}
And attach it all your CheckBox CheckedChanged events:
chckOne.CheckedChanged += chkBox_CheckedChanged;
chckTwo.CheckStateChanged += chkBox_CheckedChanged;
Or if you want to add all checked values in your Button click change your method like this:
void btnOne_Click(object sender, EventArgs e)
{
this.Controls.OfType<CheckBox>()
.Where(c => c.Checked == true)
.Select(c => c.Text)
.ForEach(text => lstOne.Items.Add(text));
}
List<CheckBox> cbList=new List<CheckBox>();
public Form1()
{
InitializeComponent();
btnOne.Click += btnOne_Click;
cbList.Add(chckOne);
cbList.Add(chckTwo);
//All the checkbox should be added into cbList.
}
void btnOne_Click(object sender, EventArgs e)
{
lstOne.Items.Clear();
var checked_checkbox = cbList.Where(cb=>cb.Checked==true).ToList();
if(checked_checkbox.Count>0)
{
checked_checkbox.ForEach(x=>lstOne.Items.Add(x.Text));// Maybe you want put text of checkbox into listbox.
}
}
I have 20 radiobuttons on the page and I want to know which one of them was clicked.
protected void Page_Load(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "Button 1";
PlaceHolder1.Controls.Add(newBTN);
for (int i = 0; i < 20; i++)
{
RadioButton r = new RadioButton();
r.ID = i.ToString();
r.CheckedChanged += RadioButton1_CheckedChanged;
PlaceHolder1.Controls.Add(r);
}
}
New Updated code.. NOTE: THE CODE DOESNT RELATE TO THE ABOVE CODE.
public List<int> ThreadID2Treat { get { return ViewState["Checked"] == null ? null : (List<int>)ViewState["Checked"]; } set { ViewState["Checked"] = value; } }
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
var rad = (CheckBox)sender;
int threadID = int.Parse(rad.ID.ToString());
ThreadID2Treat.Add(threadID);
}
public void DeleteButton_Clicked(object sender, EventArgs e)
{
foreach (var item in ThreadID2Treat)
{
UsefulStaticMethods.DeleteThreads(item);
}
}
How do i find out?
var rad = (RadioButton)sendder;
Response.Write("RadioButton Id :" + rad.Id.ToString());
You could try the above.
Update :
To get all select radio buttons in PlaceHolder make sure the AutoPostBack is not set on the radio buttons. You dont need to add CheckChanged Event. "r.CheckedChanged += RadioButton1_CheckedChanged;" <= remove.
StringBuilder stringBuilder = new StringBuilder();
foreach (var control in placeHolder1.Controls)
{
var rad = control as RadioButton;
if (rad != null)
{
if (rad.Checked)
stringBuilder.AppendLine(String.Format("Radion Button Checked : {0}", rad.ID));
}
}
Response.Write(stringBuilder.ToString());
With the parameter sender you have a direct reference to the event-source control.
var rb = (RadioButton)sender;
If you want to trigger this event and the postback directly, you must set the RadioButton's AutoPostBack-Property to true.
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (sender is RadioButton)
{
RadioButton radioButton = (RadioButton)sender;
//Code to use radioButton's properties to do something useful.
// get the radio button by its ID
string id = radioButton.ID;
}
}
You can try this.
RadioButton r = sender as RadioButton;
Response.Write(r.Id);
Cast sender as RadioButton:
RadioButton r = sender as RadioButton;
if(r != null)
{
//Do stuff
}