Null Exception Error when checking string for null? - c#

When running my code i put several string on different lines of the textbox but it breaks saying there is a Null Exception Error on "Items.Add(item)" I am not sure why I am getting
this error because in visual studio the string in the variable item is not null it contains
a return character through so I am not sure if that is an issue.. for example item = "uno\r". Also, Items is a list of strings. Does anyone know why I keep getting this Null Exception?
public List<string> Items;
public void getItemsFromTextBox(TextBox textbox)
{
string[] lines = textbox.Text.Split('\n');
foreach (string item in lines)
{
if (!String.IsNullOrWhiteSpace(item))
Items.Add(item);
}
}

You have not initialized your list, it's null! Add
public List<String> Items = new List<String>();

You must create instance of Items list:
public void getItemsFromTextBox(TextBox textbox)
{
Items = new List<string>();
string[] lines = textbox.Text.Split('\n');
foreach (string item in lines)
{
if (!String.IsNullOrWhiteSpace(item))
Items.Add(item);
}
}

Just try with following code.I guess your Items list is global one and shared list .so better to check that List is initialize or if not then initialize first and do the rest of the thing.
public List<string> Items;
public void getItemsFromTextBox(TextBox textbox)
{
if(null == Items)
{
Items = new List<string>();
}
foreach (string item in textbox.Text.Split('\n'))
{
if (!String.IsNullOrWhiteSpace(item))
Items.Add(item);
}
}

You must have create an instance of List Items.
use
public List<String> Items = new List<String>();
or use the below code
public void getItemsFromTextBox(TextBox textbox)
{
List<string> Items = !string.IsNullOrWhiteSpace(textbox.Text) ? textbox.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList() : new List<string>();
}

Make sure that you have instantiated "Items".

Related

Return ComboBox From Function?

The below code has a list and loops through each string item in that list and adds it to a ComboBox. This functions correctly, but I am curious if there is a possible way to pass a string list and ComboBox into a function and return the ComboBox with each item in the string list being added.
Example: gets a string list, then adds each string item to the list. This is great if there's one ComboBox; but if there are 3 or more, to avoid code repetition, passing in a list and ComboBox would save code.
List<string> myList = getList();
foreach (string listItem in myList)
{
myComboBox.Items.Add(listItem);
}
you can make method like
private void FillCombo(ComboBox myComboBox, List<string> list);
{
foreach (string listItem in myList)
{
myComboBox.Items.Add(listItem);
}
//alternatively, you can add it like fubo suggested in comment
//myComboBox.Items.AddRange(myList.ToArray());
}
and call it from somewhere in code
List<string> myList = getList();
FillCombo(this.comboBox1, myList);
FillCombo(this.comboBox2, myList);
// etc...

List for both checkedlist box and combobox

I want to add all selected items of checkedlistbox and combobox to a list and use that list in a for each loop in c#
I tried this
List<String> list=new List<String>();
if (rbtnMultipleScenario.Checked == true)
{
foreach ( CheckedListBox str in clbScenario.SelectedItems)
{
lstitems.Add(str);
}
}
By using String, I am not able to add all the selected items of Checkedlistbox.
Which type of list I have to use?
List<string> list=new List<string>();
if (rbtnMultipleScenario.Checked == true)
{
foreach ( string str in clbScenario.SelectedItems)
{
lstitems.Add(str);
}
}
This assumes that SelectedItems contains a collection of strings (which by your exception it does)

How to display form variables based on variable name

I have a list of variable names, lets say:
List<string> list = new List<string>();
list.Add("size");
list.Add("width");
list.Add("name");
list.Add("zip");
and i have text controls with those exact names, is there a way to loop through the list and only display what the value of the text control that i am asking for, like lets say something like this:
foreach (string txtctl in list)
{
Response.Write(Request.Form[txtctl]);
}
When i run this code the value just displays blank. Any suggestions?
string str = "";
foreach (string item in list)
{
TextBox txt = (TextBox)Form.FindControl(item);
if (txt != null)
{
str += item+":"+ txt.Text+"<br>";
}
}
Response.Write(str);

Exception in C# when trying to add a string to strings List

I get an exception on the List.Add line when trying to run this code:
string searchText = searchByInterestBox.Text;
List<string> checkedItems = null;
if (m_BusinessLogic != null)
{
if (searchText != string.Empty)
{
try
{
interestResultBox.Items.Clear();
foreach (var itemChecked in InterestsCheckedListBox.CheckedItems)
{
checkedItems.Add(itemChecked.ToString());
}
While debugging, when reaching the last line of code (checkedItems.Add) it says "Object Reference not set to an instance of an object"
Any idea what did I do wrong with the string list?
Thanks a lot.
Itzik.
checkedItems is null, so you are getting an exception. You need to initialize it.
Instead of:
List<string> checkedItems = null;
Do:
IList<string> checkedItems = new List<string>();
You shouldn't initialize the list with null:
List<string> checkedItems = new List<string>();
You have never created an instance of the list, try:
List<string> checkedItems = new List<string>();
The exception means your list has not been created yet (and is still null).
List<string> checkedItems = new List<string>();

C#: How to add subitems in ListView

Creating an item(Under the key) is easy,but how to add subitems(Value)?
listView1.Columns.Add("Key");
listView1.Columns.Add("Value");
listView1.Items.Add("sdasdasdasd");
//How to add "asdasdasd" under value?
You whack the subitems into an array and add the array as a list item.
The order in which you add values to the array dictates the column they appear under so think of your sub item headings as [0],[1],[2] etc.
Here's a code sample:
//In this example an array of three items is added to a three column listview
string[] saLvwItem = new string[3];
foreach (string wholeitem in listofitems)
{
saLvwItem[0] = "Status Message";
saLvwItem[1] = wholeitem;
saLvwItem[2] = DateTime.Now.ToString("dddd dd/MM/yyyy - HH:mm:ss");
ListViewItem lvi = new ListViewItem(saLvwItem);
lvwMyListView.Items.Add(lvi);
}
Like this:
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add("SubItem");
listView1.Items.Add(lvi);
Suppose you have a List Collection containing many items to show in a ListView, take the following example that iterates through the List Collection:
foreach (Inspection inspection in anInspector.getInspections())
{
ListViewItem item = new ListViewItem();
item.Text=anInspector.getInspectorName().ToString();
item.SubItems.Add(inspection.getInspectionDate().ToShortDateString());
item.SubItems.Add(inspection.getHouse().getAddress().ToString());
item.SubItems.Add(inspection.getHouse().getValue().ToString("C"));
listView1.Items.Add(item);
}
That code produces the following output in the ListView (of course depending how many items you have in the List Collection):
Basically the first column is a listviewitem containing many subitems (other columns). It may seem strange but listview is very flexible, you could even build a windows-like file explorer with it!
I've refined this using an extension method on the ListViewItemsCollection. In my opinion it makes the calling code more concise and also promotes more general reuse.
internal static class ListViewItemCollectionExtender
{
internal static void AddWithTextAndSubItems(
this ListView.ListViewItemCollection col,
string text, params string[] subItems)
{
var item = new ListViewItem(text);
foreach (var subItem in subItems)
{
item.SubItems.Add(subItem);
}
col.Add(item);
}
}
Calling the AddWithTextAndSubItems looks like this:
// can have many sub items as it's string array
myListViewControl.Items.AddWithTextAndSubItems("Text", "Sub Item 1", "Sub Item 2");
Hope this helps!
I think the quickest/neatest way to do this:
For each class have string[] obj.ToListViewItem() method and then do this:
foreach(var item in personList)
{
listView1.Items.Add(new ListViewItem(item.ToListViewItem()));
}
Here is an example definition
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public DateTime DOB { get; set; }
public uint ID { get; set; }
public string[] ToListViewItem()
{
return new string[] {
ID.ToString("000000"),
Name,
Address,
DOB.ToShortDateString()
};
}
}
As an added bonus you can have a static method that returns ColumnHeader[] list for setting up the listview columns with
listView1.Columns.AddRange(Person.ListViewHeaders());
Create a listview item
ListViewItem item1 = new ListViewItem("sdasdasdasd", 0)
item1.SubItems.Add("asdasdasd")
ListViewItem item = new ListViewItem();
item.Text = "fdfdfd";
item.SubItems.Add ("melp");
listView.Items.Add(item);
add:
.SubItems.Add("asdasdasd");
to the last line of your code so it will look like this in the end.
listView1.Items.Add("sdasdasdasd").SubItems.Add("asdasdasd");
Generally:
ListViewItem item = new ListViewItem("Column1Text")
{ Tag = optionalRefToSourceObject };
item.SubItems.Add("Column2Text");
item.SubItems.Add("Column3Text");
myListView.Items.Add(item);
Great !! It has helped me a lot. I used to do the same using VB6 but now it is completely different.
we should add this
listView1.View = System.Windows.Forms.View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;

Categories