How to fill private member List<string> in OOP - c#

I want to add all of the items from a listbox inside of a list. This list is a string-list and a part of the private members from my object "Deur".
When i try to loop over the listbox listitems and add them inside this list, i get an error saying "System.NullReferenceException: 'Object reference not set to an instance of an object.'"
I've tried to Convert the "Listbox.Text" item to a string (which it alredy is), but that didn't help.
Here is the code where i try to add it to my list:
LBSupplementen is the ListBox, b.SupplementenLijst is the List.
if (LBSupplementen.Items.Count > 0)
foreach (ListItem i in LBSupplementen.Items)
b.SupplementLijst.Add(Convert.ToString(i.Text));
and here is where i define my List in my object class "Deur":
private List<string> _SupplementLijst;
public Deur()
{
_GaasID = GaasID;
_Gaas = Gaas;
_ProductID = ProductID;
_Product = Product;
_Hoogte = Hoogte;
_Breedte = Breedte;
_KleurID = KLeurID;
_Kleur = Kleur;
_SupplementLijst = SupplementLijst;
_SupplementLijstID = SupplementLijstID;
_Prijs = Prijs;
}
public List<string> SupplementLijst
{
get { return _SupplementLijst; }
set { _SupplementLijst = value; }
}

Have you instantiated the list in your "Deur" class? If not, make sure you instantiate your list in the constructor like this:
private List<string> MyList;
public Deur()
{
MyList = new List<string>(); // Add this here
}
If you want your list to stay private, add a method to your "Deur" class that you can use to put items in your list from outside, like this:
public void AddToList(string item)
{
MyList.Add(item);
}

Related

C# Form is displaying an extra object

So I have a parent class called SalesRep and a child class called SeniorSalesRep. I have got it so it displays both classes polymorphically to a listbox. The issue I'm having is that I have a combo box that gives the user the choice of displaying a report of the objects in the SalesRep class which should also display the SeniorSalesRep objects and if it's selected just SeniorSalesRep it only shows SeniorSales Rep objects. However, when I'm implementing this it creates an extra object called object which displays only SalesRepObjects and not SeniorSalesRep objects. How can I get rid of that extra object in my combo box?
public void LoadTypeComboBox()
{
List<string> salesRepTypes = new List<string>();
foreach (SalesRep thisSalesRep in allSalesReps)
{
string s = thisSalesRep.GetType().Name;
string baseType = thisSalesRep.GetType().BaseType.Name;
if (!salesRepTypes.Contains(s))
{
salesRepTypes.Add(s);
}
if (!salesRepTypes.Contains(baseType))
{
salesRepTypes.Add(baseType);
}
}
cboObjectType.DataSource = salesRepTypes;
}
private void cboObjectType_SelectedIndexChanged(object sender, EventArgs e)
{
lstSalesReps.DataSource = null;
lstSalesReps.Items.Clear();
foreach (var i in allSalesReps)
{
if (i.GetType().Name == cboObjectType.SelectedItem.ToString())
{
lstSalesReps.Items.Add(i);
}
else if (i.GetType().BaseType.Name == cboObjectType.SelectedItem.ToString())
{
lstSalesReps.Items.Add(i);
}
}
}
Form Output
The code that shows object in combobox is this:
string baseType = thisSalesRep.GetType().BaseType.Name;
The base type of SalesRep is object. You should either remove object from your collection or never add in the first place.
GetType gives you the runtime type of the object. So I don't think you need .BaseType. Try this:
public void LoadTypeComboBox()
{
List<string> salesRepTypes = new List<string>();
foreach (SalesRep thisSalesRep in allSalesReps)
{
string type = thisSalesRep.GetType().Name;
if (!salesRepTypes.Contains(s))
{
salesRepTypes.Add(s);
}
}
cboObjectType.DataSource = salesRepTypes;
}
Or even better with Linq:
cboObjectType.DataSource = allSalesReps
.Select(r => r.GetType().Name)
.Distinct()
.ToList();

Object Reference not set when using PrinterSettings.StringCollection

I am attempting to list the currently installed printers using PrinterSettings.StringCollection. However, I get this error:
Object Reference not set to an instance of an object
Code is as follows:
namespace DropDownLibrary
{
public class DropDownExample : DSDropDownBase
{
public DropDownExample() : base("item") { }
public static PrinterSettings.StringCollection InstalledPrinters { get; }
public override void PopulateItems()
{
// The Items collection contains the elements
// that appear in the list.
Items.Clear();
// Create a number of DynamoDropDownItem objects
// to store the items that we want to appear in our list.
var newItems = new List<DynamoDropDownItem>();
{
foreach (String name in InstalledPrinters)
{
new DynamoDropDownItem("{0}", name);
}
};
Items.AddRange(newItems);
// Set the selected index to something other
// than -1, the default, so that your list
// has a pre-selection.
SelectedIndex = 0;
}
public override IEnumerable<AssociativeNode> BuildOutputAst(List<AssociativeNode> inputAstNodes)
{
// Build an AST node for the type of object contained in your Items collection.
var intNode = AstFactory.BuildIntNode((int)Items[SelectedIndex].Item);
var assign = AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(0), intNode);
return new List<AssociativeNode> { assign };
}
}
}
This is covered in this post. The 'Object reference not set to instance of an Object" error is caused by you trying to use a variable that is null. For instance, you can get a null reference error by doing:
object nullObject = null;
nullObject.ToString():
In your code, it doesn't look like the value for InstalledPrinters ever gets set.
Before your code reaches this line:
foreach (String name in InstalledPrinters)
It looks like you copy pasted this from this link:
public static PrinterSettings.StringCollection InstalledPrinters { get; }
This is a property on the PrinterSettings class that you can access. You should access it like so:
var installedPrinters = System.Drawing.Printing.PrinterSettings.InstalledPrinters;
foreach (String name in installedPrinters)

How can I add array values into a combobox?

I have defined variables as string arrays. I also have a form called form4 and on this form I have 1 textbox and 1 combobox.
I have this code in a class:
public class food
{
public string[] name1 = new string [20];
public string[] name2 = new string [50];
public string[] name3 = new string [40] ;
public string[] name = new string [20];
public string[] type = new string [15];
//private const int total = 11;
public int[] calories_ref;
public int i, i2;
public Form4 form = new Form4();
public food(string[] Name1, string[] Name, string[] Type1, int[] kcal)
{
name1 = Name1;
name = Name;
type = Type1;
calories_ref = kcal;
}
public food()
{
}
private void settypes()
{
type[0] = "Bebidas não alcoólicas";
type[1] = "Bebidas Alcóolicas";
type[2] = "Fruta";
type[3] = "Hidratos de Carbono";
type[4] = "Peixe";
type[5] = "Carne";
type[6] = "Cereais";
type[7] = "Lacticínios";
type[8] = "Óleos/Gorduras";
type[9] = "Leguminosas";
type[10] = "Legumes";
for (int i = 0; i < type.Length; i++)
{
form.comboBox1.Items.Add(type[i]);
}
}
In the settypes() method I define the various types of food, more concretly the food wheel. How can I can use these values as items in the combobox that is in form4?
You can add an array of strings using method AddRange(array[]) from comboBox.
form.comboBox1.Items.AddRange(type);
Here is a void you can use if you want to go beyond just one array.
public void AddToCombo(Array array, ComboBox c)
{
foreach(var a in array)
{
c.Items.Add(a);
}
}
You shouldn't be storing a Form4 object in your food class. Your code as it is creates a brand new Form4 every time the food object is created. As shown in the line:
public Form4 form = new Form4();
This won't actually be shown on screen though as you do nothing else with the form except add items to the ComboBox, which also wouldn't show on the screen.
Even if you were to get it shown on the screen, you will still get an error similar to:
Form4.comboBox1 is inaccessible due to its protection level
This is due to the fact that the ComboBox is created internally with private access modifier. (See http://msdn.microsoft.com/en-us/library/ms173121.aspx for more details).
What you need to do is get your existing Form4 to ask the food object to populate it's ComboBox by passing the ComboBox to a method on the food object similar to this example (in your Form4 code not your food code):
private void Form4_Load(object sender, EventArgs e)
{
food f = new food(); //or however you wanted to create the object
f.AddTypesToComboBox(this.comboBox1);
}
The AddTypesToComboBox method would be defined like this in your food object:
public void AddTypesToComboBox(ComboBox box)
{
for (int i = 0; i < type.Length; i++)
{
box.Items.Add(type[i]);
}
}
Also, at the moment the function won't actually add anything to the ComboBox as your type array is not being filled with data. You need to call settypes(); in the food object's constructors like this:
public food(string[] Name1, string[] Name, string[] Type1, int[] kcal)
{
settypes();
name1 = Name1;
name = Name;
type = Type1;
calories_ref = kcal;
}
public food()
{
settypes();
}
You will need to remove public Form4 form = new Form4(); from your variable declaration section as well as removing the following from your settypes() method:
for (int i = 0; i < type.Length; i++)
{
form.comboBox1.Items.Add(type[i]);
}
Your settypes() should only fill the data into the array, and not try and add it to the ComboBox.
If you want the items to be in the ComboBox just set the array as its datasource. You don't need to loop through the array and add the items one by one. It's a lot less code than the other solutions here.
public void SetTypes()
{
comboBox1.DataSource = new[]{
"Bebidas não alcoólicas",
"Bebidas Alcóolicas",
"Fruta",
"Hidratos de Carbono",
"Peixe",
"Carne",
"Cereais",
"Lacticínios",
"Óleos/Gorduras",
"Leguminosas",
"Legumes"
};
}
Not at my computer at the moment, but this should do it:
foreach(var type in type[])
{
form.comboBox1.Items.Add(type);
}
As simple as this:
public void yourMethodName() {
yourComboBoxName.removeAllItems();
for (YourObjectName object: yourArrayListName) {
yourComboBoxName.addItem(object.getWhatYouWanaGet());
}
}
Your remove the actual item from the list than you add the item you want to add :)
If this is an Array in Class1:
public static string[] session = new string[] { "2023-2024", "2022-2023","2021-2022" };
In C# (Windows Forms):
comboBox1.Items.Clear();
comboBox1.Items.AddRange(Class1.session);

Need C# Class method that persists information already in Object

I have created a class in my ASP.Net project called LitHoldModifications. Here's the code:
[Serializable]
public class LitHoldModifications
{
private Boolean _changed;
private Hashtable _added;
private Hashtable _deleted;
public Boolean Changed
{
get { return _changed; }
set { _changed = value; }
}
public Hashtable Added
{
get { return _added; }
set { _added = value; }
}
public Hashtable Deleted
{
get { return _deleted; }
set { _deleted = value; }
}
public Hashtable Add(String item1, String item2)
{
Added = new Hashtable();
Added.Add(item1, item2);
return Added;
}
public Hashtable Delete(String item1, String item2)
{
Deleted = new Hashtable();
Deleted.Add(item1, item2);
return Deleted;
}
}
The problem I'm having is that I need to be able to Add multiple items to an instance of this class. The code I have to do this is (in an aspx page):
public LitHoldModifications AffectedEmployeeModifications
{
get
{
if (ViewState["AffectedEmployeeModifications"] != null)
return (LitHoldModifications)ViewState["AffectedEmployeeModifications"];
else
return null;
}
set
{
ViewState["AffectedEmployeeModifications"] = value;
}
}
protected void ProcessAffectedviaJavascript()
{
string[] employees = HiddenEmployeesPopup.Value.Split('|');
if (employees.Length>1) {
foreach (string s in employees)
{
if (s.Length > 1)
{
string Anumber = s.Split('#')[0];
string AName = s.Split('#')[1];
ListItem item = new ListItem();
item.Text = AName;
item.Value = Anumber;
lstSelEmployees.Items.Add(item);
//Clear values in temp hidden field:
HiddenEmployeesPopup.Value = "";
AffectedEmployeeModifications.Add(Anumber, AName);
AffectedEmployeeModifications.Changed = true;
}
}
}
When I run my code and get to ProcessAffectedviaJavascript(), the string[] employees is populated with multiple names, but each time the code gets to the line AffectedEmployeeModifications.Add.... a new Hashtable is created and returned by the Add method, so any earlier strings from employees that have been added to AffectedEmployeeModifications are lost. The only way I can think to get around this is to change the Add method to take AffectedEmployeeModifications as a parameter and do this:
public Hashtable Add(Hashtable lhm, String item1, String item2)
{
lhm.Add(item1, item2);
return lhm;
}
and then, in my aspx.cs:
AffectedEmployeeModifications = AffectedEmployeeModifications.Add(AffectedEmployeeModifications, Anumber, AName);
This doesn't seem very OOP-y though, and my OOP skills are clearly wanting. How should I do this?
You should be constructing the objects that your class needs in a constructor for the class. You should add a default constructor like this:
public LitHoldModifications()
{
Added = new Hashtable();
Deleted = new Hashtable();
}
Then you can remove the assignments in your Add() and Delete() methods, because you can assume in these methods that those member variables will already be valid.
I would also recommend changing your Add/Delete methods to returning void. If you want access to the Added/Deleted hashtables, you can just reference that property instead.
var myLitInstance = new LitHoldModifications();
myLitInstance.Add("value1", "value2");
Hashtable tbl = myLitInstance.Added;

difficulty inserting a name to an inserted object of a checkedlistbox

I am abit new in C# and i am trying to insert an object to a CheckedListBox,
so this inserted item will have a title inside the checked list (my object contains a string field inside it which I want to be displayed in the CheckedListBox).
for example this is my class:
public class InfoLayer
{
private string LayerName;
private List<GeoInfo> GeoInfos;
public InfoLayer()
{
LayerName = "New Empty Layer";
GeoInfos = new List<GeoInfo>();
}
public InfoLayer(string LayerName)
{
this.LayerName = LayerName;
GeoInfos = new List<GeoInfo>();
}
public InfoLayer(string LayerName,List<GeoInfo> GeoInfosToClone):this(LayerName)
{
foreach (GeoInfo item in GeoInfosToClone)
{
GeoInfos.Add((GeoInfo)((ICloneable)item).Clone());
}
}
public GeoInfo SearchElement(long id)
{
foreach (GeoInfo info in GeoInfos) // foreach loop running on the list
{
if (info.INFOID == id)
return info; // return the item if we found it
}
return null;
}
public GeoInfo SearchElement(string name)
{
foreach (GeoInfo info in GeoInfos)
{
if (info.INFONAME.CompareTo(name)==0)
return info;
}
return null;
}
public override string ToString()
{
string toReturn = "";
for (int i = 0; i < GeoInfos.Count; i++) // for loop running on the list
{
toReturn += String.Format("{0}\n",GeoInfos[i].ToString()); // piping another geoinfo
}
return toReturn;
}
public string LAYERNAME{get{return LayerName;}}
my class also contains a tostring overrider inside her (not what i want to display)
thanks in advance for your help.
Override ToString() in your class, the class that the object is an instance of.
Edit:
You don't want to display the contents of ToString(). You want to display the LayerName, don't you? Perhaps you should display the values with Databinding instead. Then you can set DisplayMember to your new LAYERNAME property.
I believe this is what you are trying to achieve:
checkedListBox1.Items.Add(yourObject.stringField);
((MyObjectType)checkedListBox1.Items(index)).Name = "whatever"
You will have to know the index of the object you want to change.
You'll just have to override the ToString method in your class so that it returns this Name property value.
public overrides string ToString() {
return Name;
}
It will then display its name when added to your CheckedListbox.

Categories