I am getting the error "reference not set to an instance of an object" when the following code occurs on startup:
switch (Popup_Data_Type_ComboBox.SelectedItem.ToString())
{
I am pretty sure that this error is occurring as Popup_Data_Type_ComboBox has not yet been created therefore its not possible to get the sting value. How Can I get around this problem?
Ok thanks a lot for all the help I threw in a check if Popup_Data_Type_ComboBox.SelectedItem == null and it now works fine
Add a check before the switch, assuming the code is in a method that just handles the Popup_Data_Type_ComboBox.SelectionChanged-event or the likes:
if (Popup_Data_Type_ComboBox == null
|| Popup_Data_Type_ComboBox.SelectedIndex < 0)
{
// Just return from the method, do nothing more.
return;
}
switch (...)
{
}
The most likely issue is that your combo box hasn't been created, or doesn't have a selected item. In this case, you'd have to explicitly handle that:
if (Popup_Data_Type_ComboBox != null && Popup_Data_Type_ComboBox.SelectedItem != null)
{
switch (Popup_Data_Type_ComboBox.SelectedItem.ToString())
{
//...
}
}
else
{
// Do your initialization with no selected item here...
}
I'd verify first that Popup_Data_Type_ComboBox is instantiated, and then verify that an item is selected. If you are running this on startup as you said, then it is likely no item is selected. you can check with:
if(Popup_Data_Type_ComboBox.SelectedItem != null)
{
switch (Popup_Data_Type_ComboBox.SelectedItem.ToString())
{
//.....
}
}
Related
I have a checkedListBox where the user can select whatever they want to update. I want them to be able to freely update 1 up to 5 characteristics of a machine. So when they only want to update 1 thing, they do not have to provide the other 4 characteristics. Also, when they want to update 5 characteristics, they
can do it in one go. For that purpose I have the following if statements:
if (clbCharacteristicsToUpdate.CheckedItems.Count != 0)
{
if (clbCharacteristicsToUpdate.GetSelected(0))
{
currentITime = Convert.ToDouble(tbCurrentITime.Text);
MessageBox.Show(currentITime.ToString());
dh.UpdateCurrentITime(machineNr, currentITime);
}
if (clbCharacteristicsToUpdate.GetSelected(1))
{
cycleTime = Convert.ToDouble(tbCycleTime.Text);
MessageBox.Show(cycleTime.ToString());
dh.UpdateCycleTime(machineNr, cycleTime);
}
if (clbCharacteristicsToUpdate.GetSelected(2))
{
nrOfLinesPerCm = Convert.ToInt32(tbNrOfLinesPerCm.Text);
MessageBox.Show(nrOfLinesPerCm.ToString());
dh.UpdateNrOfLinesPerCm(machineNr, nrOfLinesPerCm);
}
if (clbCharacteristicsToUpdate.GetSelected(3))
{
heightOfLamallae = Convert.ToDouble(tbHeightOfLamallae.Text);
MessageBox.Show(heightOfLamallae.ToString());
dh.UpdateHeightOfLamallae(machineNr, heightOfLamallae);
}
if (clbCharacteristicsToUpdate.GetSelected(4))
{
if (rbLTB.Checked)
{
machineType = 2;
MessageBox.Show(machineType.ToString());
}
else if (rbSTB.Checked)
{
machineType = 1;
MessageBox.Show(machineType.ToString());
}
if(!rbLTB.Checked && !rbSTB.Checked)
{
MessageBox.Show("Select a machine type to update!");
return;
}
dh.UpdateType(machineNr, machineType);
}
}
My problem is that, when I choose and update 1 thing it works perfectly. But when I choose multiple ones, it only executes the last if statement that returns true. I thought about using if-else but then only the first one that returns true will be executed. I also thought about having if statements for each possibility. But since I have 5 characteristics I can update, this would make 25 possibilities and I do not want to have 25 if statements. Thanks in advance!
GetSelected does not check whether the item has been checked, but that it is actually selected.
For example, in the below image "Item 2" will will return true for GetSelected. It is selected, not checked.
Instead you could do something like checking the clbCharacteristicsToUpdate.CheckedItems property to get the items that are actually checked.
The GetSelected method actually comes from the ListBox class, which CheckedListBox inherits from.
Try this:
This is a helper method I created on a button.
private void button1_Click(object sender, EventArgs e)
{
CheckList();
}
This method looks if items are checked and iterates over the collection of checked ones, calling the last metod.
private void CheckList()
{
if (clbCharacteristicsToUpdate.SelectedItems.Count != 0)
{
foreach (int indexChecked in clbCharacteristicsToUpdate.CheckedIndices)
{
CheckSelectedItem(indexChecked);
}
}
}
And finally, here the appropriate actions are taken based on indexes.
private void CheckSelectedItem(int index)
{
if (index == 0)
{
//Do stuff on Zero
MessageBox.Show("Zero");
}
if (index == 3)
{
//Do stuff on One
MessageBox.Show("Three");
}
}
I'm trying to make an if statement to check whether a TextBox has text it.
So something like this:
if (textbox1 has text)
{
//Then do this..
}
How would I write "textbox1 has text"?
if (textbox1.Text.Length > 0)
{
...
}
or
if (!string.IsNullOrEmpty(textbox1.Text))
{
...
}
You can get the text stored in the TextBox using Text property of the TextBox and then check whether it is null or empty like this :-
string text = textBox1.Text ;
if(String.IsNullOrEmpty(text))
{
// Do something
}
Check the length of the text box text.
if (textbox1.Text.Length > 0)
{
//do the process here
}
Please try
if(!string.IsNullOrWhiteSpace(textbox1.Text))
{
//
}
Checking the Length
if (textBox1.Text.Length > 0)
{
// perform task
}
Using the Null
if (!string.IsNullOrEmpty(textBox1.Text))
{
// perform a task
}
Using Trim would be nice for checking if a user is only putting spaces.
if (textBox1.Text.Trim().Length > 0)
{
// perform a task
}
Try any one of these and it should work. There are way more ways but since this question is a bit broad it's up to you.
Simple. Check out this MSDN page: string.IsNullOrEmpty
if (!string.IsNullOrEmpty(textBox1.Text))
{
}
Alternatively, you could use a property. This is especially helpful when you need to check multiple times to see if the textbox has text:
// a public property is not necessary for this
bool HasText
{
get
{
return !string.IsNullOrEmpty(textBox1.Text);
}
}
...
if (HasText)
{
}
Another way to go about doing this is by using an extension method:
public static class TextBoxUtility
{
public static bool HasText(this TextBox textBox)
{
return !string.IsNullOrEmpty(textBox.Text);
}
}
...
if(textBox1.HasText())
{
}
I prefer the latter instead of a property because it works across all textboxes.
the simpliest logic is this:
if (textBox1.Text != "")
MessageBox.Show("The textbox is not empty!");
else
MessageBox.Show("The textbox is empty!");
I have seen all the other answers on the page, suggesting solutions like
if (tb.Text == "")
{
// Is empty
} else {
// Is not empty
}
However this could easily break, and return that a text box is not empty, when it actually is. For example, a few spaces in the text box (and nothing else) would pass as not empty, when in fact, while not technically empty, you would probably want to report it as empty. A solution to this is the C# string.Trim() method. This removed all whitespace. Now changing my solution to this:
if (tb.Text.Trim() == "")
{
// Is empty
} else {
// Is not empty
}
... it would no longer report a text box full with spaces as not empty.
if(textBox1.Text!=null)
{
///code
}
or
if(textBox1.Text!=string.Empty)
{
//code
}
if(textbox.Text.Trim().Length > 0)
{
// Do something
}
I created the code below wich never gave me any error:
foreach (var item in clb_frente_campos.CheckedItems)
{
if (item == "numero_carteira")
{
clb_frente_impressao.Items.Add(item);
break;
}
else
{
if (!clb_frente_impressao.Items.Contains(item))
{
clb_frente_impressao.Items.Add(item);
break;
}
}
}
This code is a button to pass the checked value from one CheckedListBox to another.
Notice that, while the item numero_carteira is checked it will be added over and over to my other CheckedListBox. Because the item numero_carteira is the only item that can be added more than once. But I wanted him to be added ONLY when it was selected, that's why I made this new code:
foreach (var item in clb_frente_campos.CheckedItems)
{
if (item == "numero_carteira")
{
if (clb_frente_campos.SelectedItem.ToString() == "numero_carteira")
{
clb_frente_impressao.Items.Add(item);
break;
}
}
else
{
if (!clb_frente_impressao.Items.Contains(item))
{
clb_frente_impressao.Items.Add(item);
break;
}
}
}
And this new code is what are giving me that error that are in the title.
Also and the most strange thing i ever seen. When I use breakpoints and debug it step by step... It works How?Why?
If it works when you use the debugger, you almost certainly have a threading issue. It's difficult to debug without seeing the rest of your code, but my gut feeling is to look for other places you might loop on clb_frente_impressao.Items.
I have an control that inherits from another control (TxTextControl). I have a SelectedText property that basicaly wraps the base SelectedText property, which is apparently needed because my control is implementing an interface with that property. The code is this:
public string SelectedText
{
get
{
return base.Selection.Text; // Error here (#1042)
}
set
{
if (base.Selection == null)
{
base.Selection = new TXTextControl.Selection(0, 0);
}
base.Selection.Text = value;
}
}
When I drop this control on a form, no problems. It compiles and runs. Everything looks great. However, when I save, close then reopen the form, the form designer shows this error:
Object reference not set to an instance of an object.
1. Hide Call Stack
at Test.FormattedTextBox2.get_SelectedText() in C:\Projects\Test\FormattedTextBox2.cs:line 1042
Anyone know what is going on? I'm about to pull out my last hair...
UPDATE:
darkassisin93's answer wasn't exactly correct, but that was because my posted code wasn't exactly accurate. I needed to test if base.Selection was null before attempting to access a property of that object. In any case, that answer got me headed in the right direction. Here is the actual solution:
public string SelectedText
{
get
{
string selected = string.Empty;
if (base.Selection != null)
{
selected = base.Selection.Text;
}
return selected;
}
set
{
if (base.Selection == null)
{
base.Selection = new TXTextControl.Selection(0, 0);
// Have to check here again..this apparently still
// results in a null in some cases.
if (base.Selection == null) return;
}
base.Selection.Text = value;
}
}
Try replacing
return base.SelectedText;
with
return base.SelectedText ?? string.Empty;
It's most likely because the base class's SelectedText property is set to null.
When I set SelectedNode to null the tree updates correctly but BeforeSelect and AfterSelect do not fire.
Is there any way to tell when the selection has been changed to null?
My first thought is to extend the control and add an event though I would have thought something like this would already be available.
I think your solution is good. However, I just discovered this control (keep an eye on SO's right column :)):
http://treeviewadv.sourceforge.net/
which supports what you're looking for, maybe has other goodies too...
It seems the only way I could do this was to create a new control and provide a new implementation for SelectedNode, even OnAfterSelect and OnBeforeSelect weren't getting called.
public new TreeNode SelectedNode {
get { return base.SelectedNode; }
set {
// Remember, if `value' is not null this will be called in `base'.
if (value == null) {
TreeViewCancelEventArgs args
= new TreeViewCancelEventArgs(value, false, TreeViewAction.Unknown);
OnBeforeSelect(args);
if (args.Cancel)
return;
}
base.SelectedNode = value;
// Remember, if `value' is not null this will be called in `base'.
if (value == null) {
OnAfterSelect(new TreeViewEventArgs(value, TreeViewAction.Unknown));
}
}
}