C# - Visual Studio Not able to clean textbox after IF Statement - c#

I am making a very simple program. Need some help clearing out a textbox after performing a search. I have used the cboPrograms.Text = string.Empty; but I must not be putting it in the right place. After I choose an option it will not clear.
private void cboPrograms_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboPrograms.Text == "MFValidation")
{
System.Diagnostics.Process.Start("C:\\Program Files (x86)\\Mozilla\\Mozilla.exe");
}
else if (cboPrograms.Text == "Add/Remove Programs")
{
System.Diagnostics.Process.Start("C:\\Program Files\\AddRemove\\addremove.exe");
cboPrograms.Text = string.Empty;
}
{
cboPrograms.Text = string.Empty;
}
}

That's because cboPrograms is not a TextBox but a ComboBox. (Text boxes do not have a SelectedIndexChanged event.)
To clear a combo box you do this:
cboPrograms.SelectedIdex = -1;
Also, reading the text of the combo box is not a good practice. You should have a collection of objects bound to the combo box. Get the selected object by calling SelectedItem and then working with the object's properties. The text you're seeing should just be a textual representation of the object. See here for more info.

You are missing an else statement before this code
{
cboPrograms.Text = string.Empty;
}

Related

c# check textbox autocomplete is empty

The AutoCompleteSource and AutoCompleteMode properties of the TextBox allow me to use automatic completion in textboxes.
I have bound directly a datatable as AutoCompleteSource of the textbox and it works well.
In some situations that the input words is not available in the sources, the auto completion has no result and so, i need to do something else in those situations.
How should i check whether the automatic completion result is empty?
Here is one approach you can take. The following code will get suggestions in the TextChanged event of the textbox when more than 3 characters have been entered. We go get the suggestions and then check if any suggestions were returned. If yes, we set the AutoCompleteCustomSource. Otherwise, we will do something--whatever we want to do.
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextBox t = sender as TextBox;
if (t != null)
{
// Here I am making the assumption we will get suggestions after
// 3 characters are entered
if (t.Text.Length >= 3)
{
// This will get the suggestions from some place like db,
// table etc.
string[] arr = GetSuggestions(t.Text);
if (arr.Length == 0) {// do whatever you want to}
else
{
var collection = new AutoCompleteStringCollection();
collection.AddRange(arr);
this.textBox1.AutoCompleteCustomSource = collection;
}
}
}
}

Clear ComboBox if RadioButton is deactivated

I have five RadioButton and five ComboBox controls.
Each RadioButton is connected to a ComboBox.
When I activate one RadioButton, the corresponding ComboBox, it gets enabled.
Now when I choose another RadioButton, the information in the previously selected ComboBox should clear but does not!
I have tried with ComboBox.Clear() as well as ComboBox.Reset(), but it doesn't work.
Here is my code for one of the ComboBox and RadioButton
if (radioButtondinner.Checked == true)
{
comboBoxdinner.DataSource = DList.Dwork();
comboBoxdinner.DisplayMember = "dinner";
}
As I said in comment: you can use one Combobox and only to change data sources when you check other RadioButton that should work sure
But If you want to have more Combobox then just type in else statements
comboBox.DataSource = null;
// create a check change event and use this.
private void radioButtondinner_CheckedChanged(object sender, EventArgs e)
{
if (!radioButtondinner.Checked)
{
// if you want to clear only the text or selected item text
comboBoxdinner.Text = String.Empty;
// if you want to clear the entire data source
comboBoxdinner.DataSource = null;
}
}

Cannot perform runtime binding on a null reference when using type dynamic

I have a listview and this listview will be updated when a message is coming in.
The code below is about how I get the selected row's value.
private void CallTabLv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string callDetailValue = "";
dynamic selectedCallDetail;
//When a row of call detail is selected, return the selected row's value only
if (LineBtn1.IsChecked == true)
{
selectedCallDetail = CallTabLv1.SelectedItem;
callDetailValue = selectedCallDetail.Value;
}
if (LineBtn2.IsChecked == true)
{
selectedCallDetail = CallTabLv2.SelectedItem;
callDetailValue = selectedCallDetail.Value;
}
if (string.IsNullOrEmpty(callDetailValue))
callDetailValue = string.Empty;
Clipboard.Clear();
Clipboard.SetText(callDetailValue);
}
It worked fine for first coming message and I could get the selected row's value. The problem is when second message came in, my application stopped and returned "Cannot perform runtime binding on a null reference".
By the way, to return single selected row' value, which one should be used: CallTabLv1.SelectedItem or CallTabLv1.SelectedItems[0]? As I tried, if the latter is used, it will return "ArgumentOutOfRange Exception" when second message is coming in.
Please help.
Update:
When the message is coming in, I update the listview by clearing the whole listview and then print it line by line. I'm not sure if it is caused by the way I update the listview.
So this is probably happening because you are clearing the collection in which you have now changed the selected item. Since the item can be null at that time the dynamic object will be unable to access the property "Value"
You are checking if a checkbox is checked which is not necessarily a condition of if the selected item will exist. I would suggest your code be updated as such.
private void CallTabLv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string callDetailValue = "";
dynamic selectedCallDetail;
//When a row of call detail is selected, return the selected row's value only
if (LineBtn1.IsChecked == true)
{
selectedCallDetail = CallTabLv1.SelectedItem;
}
if (LineBtn2.IsChecked == true)
{
selectedCallDetail = CallTabLv2.SelectedItem;
}
// I think the 'invalid' casting is happening with the "selectedCallDetail.Value" as when you clear a listbox it is no longer selected.
callDetailValue = (selectedCallDetail != null) ? selectedCallDetail.Value : string.Empty;
Clipboard.Clear();
Clipboard.SetText(callDetailValue);
}
You should be using the SelectedItem as the SelectedItems collection may be null or empty, If you only ever want one result this is usually the best. also make sure your ListBox only allows for a single item to be selected so that the user cannot crash your code by selecting multiple items using SHIFT or CTRL click

Can I load my combo box with values from an array using Data Binding

I am currently loading information to a second & third combo box depending on the selection on my first combo box. I am loading the information from an array. It is working fine but the set of codes is really long. Is there a way to make it more neater and reduce the amount of code. One other way I thought of is to use data binding and read around. But I can't grasp how to data bind my array values to the combo box. Thanks for advice.
//1st combo box name - secondaryTable
//2nd combo box name - stCombo1
//3rd combo box name - stCombo2
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
if (((ComboBoxItem)secondaryTable.SelectedItem).Content.ToString() == "Agents")
{
stCombo1.Items.Clear();
stCombo2.Items.Clear();
foreach (string x in tableArray)
{
stCombo1.Items.Add(x);
stCombo2.Items.Add(x);
}
}
else if (((ComboBoxItem)secondaryTable.SelectedItem).Content.ToString() == "Missions")
{
stCombo1.Items.Clear();
stCombo2.Items.Clear();
foreach (string x in attributeArray)
{
stCombo1.Items.Add(x);
stCombo2.Items.Add(x);
}
}
else
{
stCombo1.Items.Clear();
stCombo2.Items.Clear();
foreach (string x in jobsArray)
{
stCombo1.Items.Add(x);
stCombo2.Items.Add(x);
}
}
}
To Build on Peter's answer, you can also directly bind the combobox's ItemsSource to the array of strings you want to use. Should look something like:
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
switch (((ComboBoxItem)secondaryTable.SelectedItem).Content.ToString())
{
case "Agents":
stCombo1.ItemsSource = tableArray;
stCombo2.ItemsSource = tableArray;
break;
case "Missions":
stCombo1.ItemsSource = attributeArray;
stCombo2.ItemsSource = attributeArray;
break;
default:
stCombo1.ItemsSource = jobsArray;
stCombo2.ItemsSource = jobsArray;
break;
}
}
Assuming these are just arrays of strings, the databinding should be very simple. If it's not, you have a little bit of extra work to do.

Validating if a combobox it's SelectedText property is empty always fails

Simple problem: I am checking to see if a combobox has had an item selected with string.IsNullOrEmpty(). Problem is, even if is is selected, the error message appears. What am I doing wrong?
Here is my code:
private void button1Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(comboBox1.SelectedText))//here should skip to else - but doesn't
{
MessageBox.Show("You must select a conversion type", "Error");
}
else
{
if (comboBox1.SelectedText == "Currency")
{
double input = Convert.ToDouble(textBox1.Text);
if (!string.IsNullOrEmpty(comboBox2.SelectedText))
{
string type = comboBox2.SelectedText;
double result = convertCurrency(type, input);
if (result != -1)
{
label1.Text = Convert.ToString(result);
}
}
else
{
MessageBox.Show("You must select a conversion type", "Error");
}
}
else
{
MessageBox.Show("curency");
}
}
}
Note: This is my second ever C# program - so please don't yell at me if I'm being stupid.
Generally a few observations/suggestions.
First you're using string values and are basing logic on these values, you might want to look into using an Enum and binding all it's values to the combo box. Then use the SelectedItem property and compare it to the Enum.
When nothing is selected the SelectedItem will return NULL, another option is using SelectedIndex which will return -1 when no item has been selected.
So with the SelectedIndex it would become something like;
if (comboBox1.SelectedIndex == -1)//Nothing selected
{
MessageBox.Show("You must select a conversion type", "Error");
}
else
{
//Do Magic
}
Generally using string comparisons should only be done when anything "strong" like an int comparison or even better an enum comparison is not possible. (Maybe it's just me though but strings change to often and are just scary for this sort of stuff.)
For the enum suggestion possibly look at one of these links;
Binding an enum to a WinForms combo box, and then setting it
Load values of enum type into a combobox
Is it possible to load items from an Enum to a ComboBox in .NET 3.5?
Binding a ComboBox to an Enumeration
I'm not sure which .NET version and things you're using as binding is alot easier in WPF then in the old windows form (in my opinion).
from the MSDN doc, this answers your question exactly
You can use the SelectedText property to retrieve or change the
currently selected text in a ComboBox control. However, you should be
aware that the selection can change automatically because of user
interaction. For example, if you retrieve the SelectedText value in a
button Click event handler, the value will be an empty string. This is
because the selection is automatically cleared when the input focus
moves from the combo box to the button.
private void button2_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex==-1)
{
MessageBox.Show("You must select a conversion type", "Error");
}
else
{
MessageBox.Show("Selected");
}
}
Another solution:
You can check whether the combobox has had an item selected by checking a condition with an Index which is out of range (which item is impossible to have), then, if it is not having a possible value, you can set it manually.
if (comboBox1.SelectedIndex == -1) //index out of range
{
//show the error message
comboBox1.SelectedIndex = 1; //set the first value to the combo box
}
else
{
//continue
}
Poor naming on microsoft's part. You should use comboBox.Text to get what you are looking for.
comboBox.SelectedIndex the index of the selected value
comboBox.SelectedItem if you using a DataSource, this is the item seleted in the datasource
comboBox.SelectedValuethe ValueMember of the Datasource or the currently selected value if you added your own Items
comboBox.Text The text that you see, even if it is not in the list
.SelectedText, refers to and text selected (highlighted) within the .Text
private void Resetbtn_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
//Student is a combobox elements.Add again.
comboBox1.Items.Add("Student");
comboBox1.Items.Add("Staff");
}

Categories