I have a combobox with dropdown style and 2 text boxes. I want to add a condition that if the string of either of the 2 text boxes are not null than the combobox should get reset if any item is selected from it.
I'm using combobox.SelectedIndex=-1 in my if clause but it does not work I guess because I'm using it in a wrong event.
Make sure that both your textboxes are using the TextChanged event, and then point them to the same method. If both boxes are not null, then the combobox will reset. If you want it to be one or the other, just changed the && to ||
private void TextBox_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
{
comboBox1.SelectedIndex = -1;
}
}
Try This
combobox.Items.Clear();
or
combobox.DataSource = null;
I hope you managing you Text_Changed event well , cause you have not posted that code
Same as clearselection in c#
the command for WF is
combobox.ResetText()
Related
I have a winform with a group of comboboxes, all of the comboboxes with the same list items in them.
I need a way to confirm that when the user is done selecting a value in each box that they only selected each list value once.
Ex:
cbox1 cbox2 cbox 3
Item A Item B Item A (this needs to flag an error since Item A is already selected in cbox1)
I was thinking trying to use the selectedvaluecommited action (as after i populate the list I change the selected index to -1 so they all show "empty" to start) but the loop to make it work seems to be eluding me.
background: this is choosing fields to build a spreadsheet and the user needs to choose the field order.
You can do it like this (quick and dirty):
Add SelectedIndexChanged handler for all three comboboxes (in Form_Load in example)
comboBox1.SelectedIndexChanged += CheckComboBoxes;
comboBox2.SelectedIndexChanged += CheckComboBoxes;
comboBox3.SelectedIndexChanged += CheckComboBoxes;
in CheckComboBoxes method do your checking:
private void CheckComboBoxes(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == comboBox2.SelectedIndex ||
comboBox1.SelectedIndex == comboBox3.SelectedIndex ||
comboBox2.SelectedIndex == comboBox3.SelectedIndex)
MessageBox.Show("comboboxes are not unique");
}
EDIT:
this is approach when having n comboboxes. Put all items into list, select distinct values and compare that distinct count with items count... Something like this:
private void CheckComboBoxes(object sender, EventArgs e)
{
List<string> comboValues = new List<string>();
foreach (Control c in this.Controls)
{
if (c is ComboBox && !string.IsNullOrEmpty((c as ComboBox).SelectedItem.ToString()))
comboValues.Add((c as ComboBox).SelectedItem.ToString());
}
if (comboValues.Distinct().ToList().Count < comboValues.Count)
MessageBox.Show("not all combos are unique");
}
Here's an approach you can take.
To make the affected comboboxes easy to distinguish, put them all in a GroupBox container.
Write a validation method for your group box.
Subscribe to the group box Validating event by attaching it to your validation method.
In your validation method, loop through all the ComboBox controls in the group box and check if there are any duplicates, and issue an error if so.
For example, assuming the group box is called groupBox1:
private void GroupBox1_Validating(object sender, CancelEventArgs e)
{
base.OnValidating(e);
var selectedIndices = groupBox1.Controls.OfType<ComboBox>().Select(item => item.SelectedIndex);
var anyDuplicates = selectedIndices.GroupBy(x => x).Any(x => x.Count() > 1);
if (!anyDuplicates)
return;
MessageBox.Show("There are duplicates!");
e.Cancel = true;
}
And subscribe to the group box Validating event in the Form1 constructor:
public Form1()
{
InitializeComponent();
groupBox1.Validating += GroupBox1_Validating;
}
Sometimes when validating like this, you need to prevent the validation logic from executing if the user clicks the Cancel button. You're supposed to be able to set the CausesValidation property of the Cancel button to false to prevent this, but I find that it doesn't work for me.
Instead, I just use a bool cancelling field which I set to true in the Cancel button handler:
private void cancelButton_Click(object sender, EventArgs e)
{
cancelling = true;
this.Close();
}
bool cancelling;
And then add the following to the start of GroupBox1_Validating():
if (cancelling)
return;
If it is possible to have different UI design then my suggestion goes as under:
Alternative UI Design - A
Create One ListBox ListFieldsOriginal and populate
Create Second ListBox ListUserSelection, keep it empty initially
Provide buttons as under:
Button '>' means add currently selected item from ListFieldsOrginial to ListUserSelection at end; and remove that item from ListFieldsOriginal
Button '<' means remove currenly selected item from lstUserSelection; and add that item back to ListFieldsOriginal (of course at end)
NOTE: If adding item back to ListFieldsOriginal is your requirement then extra coding is required to find its appropriate index in the ListFieldsOriginal.
Alternative UI Design - B
Create One CheckedListBox ListFieldsOriginal and populate
Create one ListBox ListUserSelection, keep it empty initially
Define ItemCheck event handler for ListFieldsOriginal to add/remove items to/from ListUserSelected.
if (e.CurrentValue==CheckState.Unchecked)
{
string item = ListFieldsOriginal.Items[item];
ListUserSelection.Items.Add(item);
}
else
{
string item = ListFieldsOriginal.Items[item];
ListUserSelection.Items.Remove(item);
}
Good Afternoon,
I am using a ComboBox in visual studio to determine whether a user can use a text field below it on a form.
The Combobox "ReasonBox" is bound to a datasource and sql query that selects the allowed "Reasons" to choose from.
Before I had the dynamic selections I was using:
private void ReasonBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (ReasonBox.SelectedValue != null) `
if (ReasonBox.SelectedItem.ToString() == "Other")
{
{ ReasonTextBox.Enabled = true; }
{ ReasonTextBox.BackColor = Color.White; }
}
}
to enable writing to the TextBox when "Other" was selected.
Unfortuantely now I am unable to figure out how to make this happen with my databound ReasonBox. Any Ideas?
Edit: Thanks for the help guys, I think i've found the reason:
ReasonBox_SelectedIndexChanged
Appears to not be triggering when I change the selection. I'll investigate further in the morning :)
Try SelectedText
You can find the documentation here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedtext%28v=vs.110%29.aspx
try this
ReasonBox.Text == "Other"
Text property gets or sets the text associated with this control.
Try
"ReasonBox.Text" == "Other"
OR
ReasonBox.Items[ReasonBox.SelectedIndex].ToString() == "Other"
Insted of
ReasonBox.SelectedItem.ToString() == "Other"
I have a datagridview. It has 2 columns which are of type boolean. Now what I want to do is, when I click on one checkbox the other check box in the same row should be unchecked. that is, at a time only one check box should be selected in a particular row. The user should not be able to select the 2 check boxes together.
How can I achieve this ? I tried using cellcontentclick and cellcontentChanged events. nothing works.
any inputs ??
You can use CellEndEdit Event or CellLeave event
when ever you will leave the cell after doing edits this event will fire.
In the following snippet Column1 is your first checkbox and Column2 is your other checkbox.
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["Column1"].Value))
dataGridView1.Rows[e.RowIndex].Cells["Column2"].Value = false;
}
Use DataGrid_CellEditEnding
In that iterate through DataSource, if u find any checked colum (boolean true) make it unchecked (boolean false).
hope it will help u
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
foreach (var Item in dataGridView1.ItemsSource)
{
if(Item.isChecked)
Item.isChecked = false;
}
if (Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["Column1"].Value))
dataGridView1.Rows[e.RowIndex].Cells["Column2"].Value = false;
}
How can i check for the bool condition of a check box which is in datagridview. I would like to have true if checked and false if it was unchecked. Can any one help me.
Is it possible to handle this in dataGridView_CellContentClick
This is addressed a little bit on the MSDN pages for the DataGridView here and here.
In particular they say:
For clicks in a DataGridViewCheckBoxCell, this event occurs before the
check box changes value, so if you do not want to calculate the
expected value based on the current value, you will typically handle
the DataGridView.CellValueChanged event instead. Because that event
occurs only when the user-specified value is committed, which
typically occurs when focus leaves the cell, you must also handle the
DataGridView.CurrentCellDirtyStateChanged event. In that handler, if
the current cell is a check box cell, call the DataGridView.CommitEdit
method and pass in the Commit value.
So they recommend against using the CellClick type events (since they never push the value until you leave the cell) but instead use CurrentCellDirtyStateChanged and the CommitEdit method.
So you end up with:
dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name == "CB")
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
And as for getting the checked value - this is just the Value property of the DataGridViewCheckBoxCell.
So if you go:
dataGridView1.Rows[rowindex].Cells[cellindex].Value
you get a boolean value which corresponds to the checkbox (after the change has been committed).
if the checkbox is defined in the designer it would be as simple asreferring to the checkbox´s name and checking its "checked" property for true/false.
But i suspect you are adding the checkbox to the datagrid by code?
in this case youll have to save a reference to the checkbox somwhere.
If i where you i would add all the checkboxes that i add to the datagrid to a list or if you want to refer to them by name i would add them to a dictionary.
You could also bind an event to the checkbox Checked_Changed event by selecting it and clicking the little bolt icon in the properties panel and finding the checkedChanged-event and doubleclicking it.
in the event-code you can obtain the checkbox clicked by typing:
CheckBox mycheckbox = sender as CheckBox;
and then refering to mycheckbox.checked to get a bool for if its checked or not.
You can try to get this in this fashion, say in case you are looping the grid the based on the index you can find the checked state.
bool IsChecked = Convert.ToBoolean((dataGridView1[ColumnIndex, RowIndex] as DataGridViewCheckBoxCell).FormattedValue))
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var checkcell = new DataGridViewCheckBoxCell();
checkcell.FalseValue = false;
checkcell.TrueValue = true;
checkcell.Value = false;
dataGridView1[0, 0] = checkcell; //Adding the checkbox
if (((bool)((DataGridViewCheckBoxCell)dataGridView1[0, 0]).Value) == true)
{
//Stuff to do if the checkbox is checked
}
}
It works 100 %.
private void grd_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
grd.CommitEdit(DataGridViewDataErrorContexts.Commit);
bool Result = Convert.ToBoolean((grd[e.ColumnIndex, e.RowIndex] as DataGridViewCheckBoxCell).Value);
}
HELLO
i have one dropdown box and one listbox ,
my dropdown box values is
1-ALL
2-CUSTOM
my listbox values is retrieved from sql database
email addresses
what i want to do is if i select ALL from the dropdown box , it will disable or hide the list box in the web page. , if i choose "CUSTOM" it will enable it again.
i tried this code, but it doesn't work
if (DropDownList1.Text == "CUSTOM")
{
ListBox1.Visible = true;
}
note : i put visible = false in the properties of the listbox1
where is the problem exactly ? and where should i put this condition on the .cs page ?
You need to add an event to the dropdown box, so that your code is executed when the event fires. If you are using the designer, select the dropdown then above where the properties are there should be a little lightning symbol. Click on that and you will see all the events that the dropdown can fire. In there look for SelectedIndexChanged. Double click in there and it will create some code for you, which will look something like:
protected void mycombobox_SelectedIndexChanged(object o, EventArgs e)
{
}
Put your code in that section.
UPDATED:
If the text in the dropdown is CUSTOM then use this
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "CUSTOM")
{
ListBox1.Visible = true;
}
}
You will also need to set the AutoPostBack="true" on the DropDownList1.