Object Reference not set when using PrinterSettings.StringCollection - c#

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)

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();

How to fill private member List<string> in OOP

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);
}

How to add object to list item in c#

I have following classes:
public class QualifyResponse
{
List<ProviderQualifyResponse> _providerList = new List<ProviderQualifyResponse>();
public List<ProviderQualifyResponse> ProviderList
{
get { return _providerList; }
set { _providerList = value; }
}
}
public class ProviderQualifyResponse
{
private string _providerCode = string.Empty;
public string ProviderCode
{
get { return _providerCode; }
set { _providerCode = value; }
}
private List<QuestionGroup> _questionGroupList = new List<QuestionGroup>();
public List<QuestionGroup> QuestionGroupList
{
get { return _questionGroupList; }
set { _questionGroupList = value; }
}
}
I have QualifyResponse object which is populated with ProviderQualifyResponse but QuestionGroupList is empty. Now I want to fill QuestionGroupList. When I try to do it like this:
QualifyResponse qualifyResponse = response;
qualifyResponse.ProviderList.QuestionGroupList = new List<DataTypes.BuyFlow.Entities.QuestionGroup>();
I get error:
System.Collections.Generic.List' does not
contain a definition for 'QuestionGroupList' and no extension method
'QuestionGroupList' accepting a first argument of type
'System.Collections.Generic.List' could be
found (are you missing a using directive or an assembly reference?)
How can I add a List<QuestionGroup> to my qualifyResponse.ProviderList?
The error is this expression:
qualifyResponse.ProviderList.QuestionGroupList
ProviderList is of type List. You'll have to change it so you populate the correct item. Something like this:
int index = ...;
qualifyResponse.ProviderList[index].QuestionGroupList = ...
Problem is that QuestionGroupList is property of class ProviderQualifyResponse and if you want to add List, you need to assign it to property of object.
Example how to do that for all providers:
QualifyResponse qualifyResponse = response;
foreach(var provider in qualifyResponse.ProviderList)
{
provider.QuestionGroupList = new List<DataTypes.BuyFlow.Entities.QuestionGroup>();
}
Given that qualifyResponse.ProviderList is of type List<ProviderQualifyResponse>, you are trying to access List.QuestionGroupList, which doesn't exist as the error states.
You'll either need to iterate through the instances in the list to access the instance properties, if that's your intention, or select an instance from the list you wish to instantiate.
QualifyResponse qualifyResponse = response;
foreach (var providerQualifyResponse in qualifyResponse.ProviderList)
{
providerQualifyResponse.QuestionGroupList = new List<DataTypes.BuyFlow.Entities.QuestionGroup>();
}

C# - How to return an Array to set a Class property

I am trying to create a Class Method which can be called to Query the Database. The function itself works but for some reason, when the Array is returned, they're not set.
My function code is:
public Configuration[] tbl_bus(string type, string match)
{
// Create Obejct Instance
var db = new rkdb_07022016Entities2();
// Create List
List<Configuration> ConfigurationList = new List<Configuration>();
// Allow Query
if (type.ToLower() == "bustype")
{
foreach (var toCheck in db.tblbus_business.Where(b => b.BusType == match))
{
// Create Class Instance
var model = new Configuration { Name = toCheck.Name, BusinessID = toCheck.BusinessID };
// Append to the property
ConfigurationList.Add(model);
}
}
else if (type.ToLower() == "businessid")
{
foreach (var toCheck in db.tblbus_business.Where(b => b.BusinessID == match))
{
// Create Class Instance
var model = new Configuration { Name = toCheck.Name, BusinessID = toCheck.BusinessID };
// Append to the property
ConfigurationList.Add(model);
}
}
return ConfigurationList.ToArray();
}
And my Configuration code is:
public class Configuration
{
// Properties of the Database
public string Name { get; set; }
public string BusinessID { get; set; }
public string Address { get; set; }
}
public Configuration Config { get; set; }
public Controller()
{
this.Config = new Configuration();
}
On my Handler I am doing:
// Inside the NameSpace area
Controller ctrl;
// Inside the Main Void
ctrl = new Controller();
ctrl.tbl_bus("bustype", "CUS");
context.Response.Write(ctrl.Config.Name);
I tried watching the Class function and it does create the Array, only, when I watch the ctrl.Config.Name it is always set to NULL. Could anyone possibly help me in understanding why the return isn't actually setting the properties inside the Configuration class?
Edit: The function does run and it fetches 3006 rows of Data when matching the bus_type to customer. (Its a large Database) - Only, the properties are never set on return.
Edit: Is there a specific way to return an Array to a Class to set the Properties?
Thanks in advance!
Change your Configs in Controller to array
public Configuration[] Configs { get; set; }
Change your tbl_bus function to void, and set the Configs inside the function.
public void tbl_bus(string type, string match)
{
// do your code
// set the configs here
Configs = ConfigurationList.ToArray();
}
Hope it helps.
Although this is not a complete answer to your question, the problem probably lies in the fact that you're not doing anything with the array returned by the method. You're simply discarding it right away. If you change your code to
ctrl = new Controller();
Configuration[] config = ctrl.tbl_bus("bustype", "CUS");
you will be able to reference the array later on.
Console.WriteLine(config.Length);
Now you can use it to set any properties you like.

How to bind object's property to another object's property? (C#)

I'm making a graphic control class Info which should display some text on screen. The text is some object's string. I'd like to be able to get that object's latest value from within an instance of Info class.
class Info
{
public string Text;
}
void Program()
{
ClassA obj = new ClassA();
obj.name = "Instance of ClassA";
Info wind1 = new Info();
wind1.Text = obj.name; // this just copies current value, but should be a reference or something
/* obj.name value changes several times before it's time to display it again */
// Info window drawing method
foreach (var item in Windows) // Windows is List<Info>
Draw(item.Text); // this doesn't get the latest value
}
How should I change the code so I can get the latest string value from within the drawing section?
Update: If you need something that'll work for any type, you'll have to use delegates. For example:
class Info
{
private Func<string> getText;
public Info(Func<string> getText)
{
getText = getText;
}
public string Text
{
get
{
return getText();
}
}
}
void Program
{
ClassA obj = new ClassA();
obj.name = "Instance of ClassA";
Info wind1 = new Info(() => obj.name);
// Now do your stuff.
}
In this case, Info is given an anonymous function that returns a string. When you access its Text property, the function is evaluated to retrieve that string. How the string is retrieved, and where it comes from, is determined by the client code (i.e. the Program method). This way, Info doesn't rely on any particular type.
You could pass the ClassA object into your Info instance, so that it can get the value of.name itself.
Something like this, perhaps?
class Info
{
public Info(ClassA obj)
{
TheObject = obj;
}
public ClassA TheObject
{
get;
set;
}
public string Text
{
get
{
return TheObject.name;
}
}
}
void Program
{
ClassA obj = new ClassA();
obj.name = "Instance of ClassA";
Info wind1 = new Info(obj);
// Now do your stuff.
}

Categories