How to set Textbox.Enabled from false to true on TextChange? - c#

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));

Related

Combobox passed as a Control template then as a popup

I have a combobox "recent_users" as a control template and then as a poppup. How can I pass the selected value of the popup to the method below?(popup click)
recent_users.SelectedItem.ToString() always returns null.
private void usernameEnter_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
Trace.WriteLine("testing dropdown");
ControlTemplate ct = recent_users.Template;
Popup popup1 = ct.FindName("PART_Popup", recent_users) as Popup;
if (popup1 != null)
{
popup1.Placement = PlacementMode.Top;
}
recent_users.IsDropDownOpen = true;
popup1.PreviewMouseUp += new MouseButtonEventHandler((s,e) => popupClick(s,e,recent_users.SelectedItem.ToString()));
}
private void popupClick(object sender, MouseButtonEventArgs e, String recent)
{
usernameEnter.Text = recent;
Trace.WriteLine("appending norms");
}
}
}
Isn't it because the user has not made any selection in the ComboBox? I have re-written the code slightly
private void usernameEnter_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
ControlTemplate ct = recent_users.Template;
Popup popup1 = ct.FindName("PART_Popup", recent_users) as Popup;
if (popup1 != null)
{
popup1.Placement = PlacementMode.Top;
}
recent_users.IsDropDownOpen = true;
// if none selected, set first as selected
if (recent_users.SelectedIndex < 0 && recent_users.HasItems)
{
recent_users.SelectedIndex = 0;
}
var selectedItem = recent_users.SelectedItem as ComboBoxItem;
var selectedUser = selectedItem.Content.ToString();
popup1.PreviewMouseUp += new MouseButtonEventHandler((s, e) => popupClick(s, e, selectedUser));
}
But I was wondering adding a handler for PreviewMouseUp event (in the last line) is something that you really want. I would have fetched the selected user in the SelectionChanged of the recent_users rather.

How to disable some cells in DataGrid?

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;
}
}

Canceling textboxes if I type in other textbox

I got few textboxes in my form. I would like to type in one textbox and the other textboxes will be automatically canceled (Canceled so the user wont be able to type anymore in the other textboxes).
If the user delete the word he typed in the textbox (or in other words: if the textbox is empty) all other textboxes will be enabled again.
Here is what I got so far:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 0)
{
// Disable other textboxes (I have no idea how can I do that).
}
else if (textBox1.Text.Trim().Length == 0)
{
// Enable other textboxes
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 0)
{
// Keep this comboBox enabled while typing in textBox1.
}
}
How can I disable other textboxes while typing in priticillar textbox? (also keeping comboBox enabled).
DO NOTICE: I would like to do the same on textBox2 (when I type in textBox2, textbox 1 and 3 will be disabled) and textBox3.
You don't need a condition on your 'else if', just 'else' will do, as if the length is more than 0, the only other possibility is 0. Also you can use the sender instead of hardcoding the control name.
Then set the Enabled property for the textbox's you want disabled. You can loop through all the textbox's on the form, excluding the one you are typing into, or just manually list them. SImpler is putting the textbox's in a groupbox, then if you disable the groupbox it will disable the controls with in it.
private void textBox1_TextChanged(object sender, EventArgs e)
{
var senderTextBox = (TextBox)sender;
var textBoxesEnabled = senderTextBox.Text.Trim().Length == 0;
textBox2.Enabled = textBoxesEnabled;
textBox3.Enabled = textBoxesEnabled;
// OR
groupBox1.Enabled = textBoxesEnabled;
}
REPLY EDIT: You can chain of textbox's, say 4 of them, disable the last 3, then:
void TextBox1TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox2.Enabled = !isTextEmpty;
}
void TextBox2TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox1.Enabled = isTextEmpty;
textBox3.Enabled = !isTextEmpty;
}
void TextBox3TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox2.Enabled = isTextEmpty;
textBox4.Enabled = !isTextEmpty;
}
void TextBox4TextChanged(object sender, System.EventArgs e)
{
var isTextEmpty = ((TextBox)sender).Text.Trim() == "";
textBox3.Enabled = isTextEmpty;
}
But for a large amount of textbox's, another alternative is having multiple textbox share the same TextChanged event. You need to click on each TextBox control, go into the Events list and manually select the method for TextChanged. Here is the method:
private void TextBoxGroup_TextChanged(object sender, EventArgs e)
{
var groupOrder = new List<TextBox>() { textBox1, textBox2, textBox3, textBox4 };
var senderTextBox = (TextBox)sender;
var senderIndex = groupOrder.IndexOf(senderTextBox);
var isTextEmpty = senderTextBox.Text.Trim() == "";
if (senderIndex != 0) groupOrder[senderIndex - 1].Enabled = isTextEmpty;
if (senderIndex != groupOrder.Count - 1) groupOrder[senderIndex + 1].Enabled = !isTextEmpty;
}
Use Controls collection and some LINQ:
if (textBox1.Text.Trim().Length > 0)
{
var textboxes = this.Controls.OfType<TextBox>().Where(x => x.Name != "textBox1");
foreach(var tBox in textboxes)
tBox.Enabled = false;
}

DevExpress & C# : Validate RepositoryItemLookUpEdit cell after choosing value

I have a GridView in which i have this column :
bandedGridColumn.ColumnEdit = InitEdit_Material();
Here is the InitEdit_Material method :
public static RepositoryItemLookUpEdit InitEdit_Material()
{
RepositoryItemLookUpEdit riMaterial = new RepositoryItemLookUpEdit();
riMaterial.Columns.Add(new LookUpColumnInfo("ID", "ID"));
riMaterial.Columns.Add(new LookUpColumnInfo("CustomsMaterial.Name", "Name"));
riMaterial.DataSource = Service.GetAll(svc.EntityTypeToGet.Material).Data.All_Material;
riMaterial.DisplayMember = "MaterialFullname";
riMaterial.ValueMember = "ID";
riMaterial.AutoSearchColumnIndex = 1;
riMaterial.BestFitMode = BestFitMode.BestFitResizePopup;
riMaterial.NullText = "";
return riMaterial;
}
This is what it looks like :
I want to perform some actions (set other cell's value based on current cell value) whenever user choose a new value in this cell, but the problem is all the possible event i know only fires once the cell lost focus, i've tried :
private void vwVD_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e)
{
if (vwVD.FocusedColumn.Name == "colMaterialID")
MessageBox.Show("only show when focus lost");
return;
}
private void vwVD_CellValueChanged(object sender, CellValueChangedEventArgs e)
{
if (e.Column.Name != "colMaterialID") return;
MessageBox.Show("only show when focus lost");
}
You can try to use GridView.CellValueChanging event:
private void vwVD_CellValueChanging(object sender, CellValueChangedEventArgs e)
{
if (vwVD.FocusedColumn.Name == "colMaterialID")
{
//Perform some actions. Use e.Value.
}
}

return a value from checkbox_CheckChanged

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.

Categories