I'm creating my first app in Xamarin.forms and want to add information about the characters. I followed the Microsoft docs but I keep getting the error that ".Add does not exist in the current context"
I've been the last hour or two searching online but nothing seems to have fixed it. Any help would be greatly appreciated, thanks!
using SQLite;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace CharCreator
{
public class Character
{
[PrimaryKey, AutoIncrement]
public int charIndex { get; set; }
public string charName { get; set; }
public string charClass { get; set; }
public string charRace { get; set; }
public int[] charStats { get; set; }
public int classId { get; set; }
public string className { get; set; }
}
}
public class CharClasses
{
List<CharClasses> classList = new List<CharClasses>();
classList.Add(new CharClasses() {classId = 1, className = "Barbarian"});
}
Your problem begins with the declaration
List<CharClasses> classList = new List<CharClasses>();
You are declaring a List of CharClasses instead of a List of Character. Then you try initialize this list with a first element. But you cannot add code outside a method.
So, if you really need to have CharClasses initialized with a List<Character> containig at least one element then you need to write this
public class CharClasses
{
public List<Character> classList = new List<Character>()
{
new Character {classId = 1, className = "Barbarian"}
};
--- other class method follows
}
This syntax is explained in documentation at Object and Collection Initializers
Related
just trying to do a simple serialize(first time trying).
actually had this working up until I changed a few things and added a deserialize and added a class that made my other way no longer work.
basically I took what I had for deserialize json to object and tried to just reverse the order of things. but now I get an error at a foreach loop I'm not sure if I even need.
Once I get the serialize working I'm sure I will also be stuck on how to format the string as it enters the .json file so it appends properly but that is for another day.
here is error i received
System.NullReferenceException: 'Object reference not set to an instance of an object.'
i receive this exception on the line foreach(var translogs in Logs.transLogs)
here is my event.
Code
private void toolPull_Click(object sender, EventArgs e)
{
double cost = Convert.ToDouble(active_Cost.Text);
int serial = Convert.ToInt32(transactionSerial_Box.Text);
DateTime timeNow = DateTime.Now;
TransactionLogs Logs = new TransactionLogs();
foreach(var translogs in Logs.transLogs)
{
translogs.Employee = transactionEmployee_Box.Text;
translogs.Serial = serial;
translogs.Cost = cost;
translogs.Description = active_Description.Text;
translogs.CurrentDate = timeNow;
}
string stringJson = JsonConvert.SerializeObject(Logs);
StreamWriter sw = new StreamWriter(#"C:\transactionlog.json", append: true);
sw.WriteLine(stringJson);
sw.Close();
}
Here is the class to work with json
namespace QuickType
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class TransactionLogs
{
[JsonProperty("TransactionLog")]
public List<TransactionLog> transLogs { get; set; }
}
public partial class TransactionLog
{
[JsonProperty("employee")]
public string Employee { get; set; }
[JsonProperty("currentDate")]
public DateTime CurrentDate { get; set; }
[JsonProperty("serial")]
public int Serial { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("isPull")]
public bool IsPull { get; set; }
[JsonProperty("cost")]
public double Cost { get; set; }
}
}
and here is json file
{
"TransactionLog":[
{
"employee":"Joey",
"currentDate":"2021-11-03T11:49:13.5741628-04:00",
"serial":1111,
"description":"1/2-20 Threadmill",
"isPull":true,
"_ost":25.68
},
{
"employee":"joey",
"currentDate":"2021-11-03T11:50:34.6344474-04:00",
"serial":1000,
"description":"1/2-20 Threadmill",
"isPull":true,
"cost":25.68
},
{
"employee":"john",
"currentDate":"2021-11-03T11:50:40.9956616-04:00",
"serial":2000,
"description":"1/2-20 Threadmill",
"isPull":true,
"cost":25.68
},
{
"employee":"Jim",
"currentDate":"2021-11-03T11:51:24.5559292-04:00",
"serial":4565,
"description":"1/2-20 Threadmill",
"isPull":true,
"cost":25.68
}
]
}
Let me capture here the outcome of the comments.
There were two problems with these two lines:
TransactionLogs Logs = new TransactionLogs();
foreach(var translogs in Logs.transLogs)
The TransactionLogs's transLogs collection is not initialized, that's caused the NRE
After fixing that the foreach went through on an empty collection
The fix for the first problem:
Logs.transLogs = new List<TransactionLog>();
The fix for the second problem:
var transLogs = new TransactionLog()
{
Employee = transactionEmployee_Box.Text;
Serial = serial;
Cost = cost;
Description = active_Description.Text;
CurrentDate = timeNow;
};
Logs.transLogs.Add(transLogs);
So, rather than iterating through the empty collection, you had to populate it by adding a new member.
I don't know how to inheritance a variables from another class. I write code in C# and I created two classes
First one is Osoba (engl. Person) which has variables ime, prezime, OIB (engl. name, last name, ID) and I have another class Racun (engl. account) which means bank account.
Class Racun has variables podaci o vlasniku računa (engl. account holder information), broj računa (engl. serial number of account) and stanje računa (engl. bank account balance).
Well podaci o vlasniku računa (engl. account holder information) needs to have variables from class Osoba. How can I do that?
I will show you my two created classes with code. If you notice both classes need to have 3 variables, I didn't create first variable in class Racun (engl. account) because the first one need to contain variables from class Osoba (engl. Person).
Osoba.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vjezba6_1
{
class Osoba
{
public string ime { get; set; }
public string prezime { get; set; }
public int oib { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.ime = tempIme;
this.prezime = tempPrezime;
this.oib = tempOib;
}
}
}
Racun.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vjezba6_1
{
class Racun
{
public int brojRacuna { get; set; }
public int stanjeRacuna { get; set; }
public Racun(int tempPovr, int tempbrojRacuna, int tempstanjeRacuna)
{
this.povr = tempPovr;
this.brojRacuna = tempbrojRacuna;
this.stanjeRacuna = tempstanjeRacuna;
}
}
}
If your povr variable needs to hold the same pieces of information as in Osoba, you can either have povr be a reference to an instance of Osoba:
class Racun
{
public Osoba povr { get; set; }
public int brojRacuna { get; set; }
public int stanjeRacuna { get; set; }
public Racun(Osoba tempPovr, int tempbrojRacuna, int tempstanjeRacuna)
{
this.povr = tempPovr;
//etc
Or you could make a struct to hold common information:
namespace Vjezba6_1
{
struct PodaciOVlasnikuRacuna //i'm sure you can shorten this, but i don't know the language
{
public string ime;
public string prezime;
//other account holder information
}
}
And use this in your classes, like so:
namespace Vjezba6_1
{
class Osoba
{
public PodaciOVlasnikuRacuna podaci { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.podaci.ime = tempIme;
this.podaci.prezime = tempPrezime;
this.podaci.oib = tempOib;
}
}
}
namespace Vjezba6_1_v2
{
class Osoba
{
public Podaci povr { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.povr.ime = tempIme;
this.povr.prezime = tempPrezime;
this.povr.oib = tempOib;
}
}
}
My question is pretty much basic but I am not getting idea to do it. Please check the code bellow. My basic goal is to make a public class which will return some static data under a list. The example class model is provided bellow. See in class PaymentMethodDetials has two properties and I want to set value of this two property from class PaymentMethodList as a list then I will be using those list values outside this whole c# class model publically. Now my problem is paymentList.Add() visual studio not allowing me to do Add method. How can I fix that? Thanks in advance
namespace Test.Helpers
{
public class PaymentMethodList
{
List<PaymentMethodDetials> paymentList = new List<PaymentMethodDetials>();
paymentList.Add()//i want to insert data to "PaymentMethodDetials" this class like using "Add" which allowing now
}
public class PaymentMethodDetials
{
public int Id { get; set; }
public string Name { get; set; }
}
}
Try this , hope this helps
namespace Test.Helpers
{
public class PaymentMethodList
{
List<PaymentMethodDetials> paymentList = new List<PaymentMethodDetial();
public PaymentMethodList()
{
paymentList.Add(new PaymentMethodDetials
{
Id=1,
Name="xyz"
});
}
}
public class PaymentMethodDetials
{
public int Id { get; set; }
public string Name { get; set; }
}
}
I am new in the using of DevExpress. I need to design and bind a complex DataGrid.
I have designed it using the Designer. The datagrid is of type Master-Detail, and it contains the 'MainGrid' and other detail grids. One of them is of type: 'advBandedGridView'
The design of the MainGrid is as shown below:
And the design of the 'advBandedGridView' is as follows:
Now, I need to fill my DataGrid using Lists collections, so I used the following Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
ArrayList a = new ArrayList();
Term_Space_Grid t = new Term_Space_Grid("x", "y", true, "z");
t.expansions = new List<MyExpansions>();
t.expansions.Add(new MyExpansions(0, "Aya", 0, 0, 0, 0, 0));
a.Add(t);
resultsGridControl.DataSource = a;
}
}
public class Term_Space_Grid
{
public string x { get; set; }
public string y { get; set; }
public string g { get; set; }
public bool z { get; set; }
public List<MyExpansions> expansions { get; set; }
public Term_Space_Grid(string x, string y, bool z, string g)
{
this.x = x;
this.y = y;
this.z = z;
this.g = g;
}
}
public class MyExpansions
{
public Morphos morphos { get; set; }
public Semantics semantics { get; set; }
public MyExpansions(int morphoID, string morphoDerivation, int synID, int subID, int supID, int hasID, int insID)
{
this.morphos = new Morphos(morphoID, morphoDerivation);
this.semantics = new Semantics(synID, subID, supID, hasID, insID);
}
}
public class Morphos
{
//public List<Morph> morph{ get; set; }
public Morph morph { get; set; }
public Morphos(int morphoID, string morphoDerivation)
{
//this.morph = new List<Morph>();
//this.morph.Add(new Morph(morphoID, morphoDerivation));
this.morph = new Morph(morphoID, morphoDerivation);
}
}
public class Semantics
{
public List<Sem> synonyms { get; set; }
public List<Sem> subClasses { get; set; }
public List<Sem> superClasses { get; set; }
public List<Sem> hasInstances { get; set; }
public List<Sem> instanceOf { get; set; }
public Semantics(int id1,int id2, int id3, int id4, int id5 )
{
this.synonyms = new List<Sem>();
this.subClasses = new List<Sem>();
this.superClasses = new List<Sem>();
this.hasInstances = new List<Sem>();
this.instanceOf = new List<Sem>();
this.synonyms.Add(new Sem(id1));
this.subClasses.Add(new Sem(id2));
this.superClasses.Add(new Sem(id3));
this.hasInstances.Add(new Sem(id4));
this.instanceOf.Add(new Sem(id5));
}
}
public class Morph
{
public int MorphoID { get; set; }
public string MorphoDerivation { get; set; }
public Morph(int morphoID, string morphoDerivation)
{
this.MorphoID = morphoID;
this.MorphoDerivation = morphoDerivation;
}
}
public class Sem
{
public int SemID { get; set; }
//public string MorphoDerivation { get; set; }
public Sem(int semID)
{
this.SemID = semID;
}
}
}
However, I found that the result is built as a new DataGrid that has not any designed form. I mean that the detail tabs that I define in the Designer are not appeared in the resulted grid.
The result is as follows:
Notes
The design of the resulted grid which is totally different from my design, I think it is just like the Lists objects.
The other problem which is the appearance of :
"WindowsFormsApplication2.Morphos" and "WindowsFormsApplication2.Semantics" at the cells of the grid rather than the values that I passed!
Firstly, you should create associations between your data object properties and GridView columns via GridColumn.FildName property.
For your main view (gridView2) it looks like this:
// gridColumn1
this.gridColumn1.Caption = "ID";
this.gridColumn1.FieldName = "x"; // associate this column with Term_Space_Grid.x property
this.gridColumn1.Name = "gridColumn1";
Please read the following article for more details: Creating Columns and Binding Them to Data Fields
Secondly, you can not directly bind columns to object's nested properties (for example to MyExpansions.semantics.subclasses.SemID).
To bypass this restriction you can use several approaches:
The simplest approach is using Unbound Columns and the corresponding ColumnView.CustomUnboundColumnData event (you can handle this event to provide data from nested objects).
You can also use the approach demonstrated in the following KB article: How to display and edit complex data properties in grid columns
Thirdly, to get official and guaranteed answer you should address any urgent question related to any DevExpress products directly to DevExpress Support Center.
This loads a set of values from an XML file and places them into a class for storage. I'm trying to figure out how to output the values as a list so I can place them into a Listbox.
I thought there would be an easy way like a .ToList() method or to be able to foreach through the strings in the class (no public GetEnumerator). I've been able to find out that Foreach hides some of the complexity but not away to do what I want.
I've been searching online with no avail (lacking the correct terminology maybe), unfortunately I left my C# reference books at work :/
Would much appreciate a pointer in the right direction,
Thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
namespace ThereIsOnlyRules
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
listBox1.Items.Clear();
string path = "characterXML.xml";
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.Xml.XmlDocument CXML = new System.Xml.XmlDocument();
CXML.Load(fs);
//Get the number of elements
XmlNodeList elemList = CXML.GetElementsByTagName("unit");
//foreach (var element in elemList)
//{
// listBox1.Items.Add(element);
//}
for (int i = 0; i < elemList.Count; i++)
{
UnitAttributes attributes = new UnitAttributes();
attributes.army = elemList[i].Attributes["army"].Value;
attributes.category = elemList[i].Attributes["category"].Value;
attributes.type = elemList[i].Attributes["type"].Value;
attributes.composition = elemList[i].Attributes["composition"].Value;
attributes.WS = elemList[i].Attributes["WS"].Value;
attributes.BS = elemList[i].Attributes["BS"].Value;
attributes.T = elemList[i].Attributes["T"].Value;
attributes.W = elemList[i].Attributes["W"].Value;
attributes.I = elemList[i].Attributes["I"].Value;
attributes.A = elemList[i].Attributes["A"].Value;
attributes.LD = elemList[i].Attributes["LD"].Value;
attributes.save = elemList[i].Attributes["Save"].Value;
attributes.armour = elemList[i].Attributes["armour"].Value;
attributes.weapons = elemList[i].Attributes["weapons"].Value;
attributes.specialrules = elemList[i].Attributes["specialrules"].Value;
attributes.transport = elemList[i].Attributes["transport"].Value;
attributes.options = elemList[i].Attributes["options"].Value;
//foreach (string item in attributes)
//{
//unit.Add(item);
//}
//listBox1.Items.AddRange(attributes)
}
//Close the filestream
fs.Close();
}
catch (Exception ex)
{
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ThereIsOnlyRules
{
class UnitAttributes
{
public string army { get; set; }
public string category { get; set; }
public string type { get; set; }
public string composition { get; set; }
public string WS { get; set; }
public string BS { get; set; }
public string T { get; set; }
public string W { get; set; }
public string I { get; set; }
public string A { get; set; }
public string LD { get; set; }
public string save { get; set; }
public string armour { get; set; }
public string weapons { get; set; }
public string specialrules { get; set; }
public string transport { get; set; }
public string options { get; set; }
}
}
<?xml version="1.0"?>
<config>
<unit
army="Tyranids"
category="Troops"
type="Infantry"
composition="10-30"
WS="3"
BS="3"
T="3"
W="1"
I="4"
A="1"
LD="6"
Save="6+"
armour="Chitin"
weapons="Claws and Teeth, Fleshborer"
specialrules="Instictive Behaviour - Lurk, Move Through Cover"
transport="If the brood consists of 20 models or less, it may take a Mycetic Spore."
options="Strangleweb, Spinefists, Spike rifle, Devourer, Adrenal Glands, Toxin Sacs"
>
Termagant Brood
</unit>
<unit
army="Tyranids"
category="Troops"
type="Infantry"
composition="10-30"
WS="3"
BS="3"
T="3"
W="1"
I="5"
A="2"
LD="6"
Save="6+"
armour="Chitin"
weapons="Scything Talons"
specialrules="Instictive Behaviour - Feed, Bounding Leap, Fleet, Move Through Cover"
transport="If the brood consists of 20 models or less, it may take a Mycetic Spore."
options="Adrenal Glands, Toxin Sacs"
>
Hormagaunt Brood
</unit>
</config>
Are the members of your class fields or properties? Either way, a little reflection and Linq should allow you to enumerate through the data members of your class, after you have hydrated an instance of it from your XML file.
var fieldDictionary =
(from f in typeof(UnitAttributes).GetFields()
select new {Name = f.Name, Value = (string)(f.GetValue(attributes))})
.ToDictionary(x=>x.Name, x=>x.Value);
fieldDictionary is now a Dictionary<string, string> (which is an IEnumerable<KeyValuePair<string, string>>), which should be suitable for loading into a ListBox.
Be advised; reflection is slow. It would be far more preferable for you to modify or extend your UnitAttributes class to implement IEnumerable (probably of a Tuple, maybe a KeyValuePair). It would also allow you to enumerate the properties of an instance of the class in exactly the order you want, instead of the order in which they're defined, or by some other FieldInfo/PropertyInfo data like the field's name.
Also be aware that a field is not a property, and vice versa. If you have a mix of properties and public fields on your class, I would HIGHLY recommend standardizing to one or the other; otherwise you'll have to reflect BOTH a list of properties and a list of fields using two of the above Linq statements (at a cost of roughly double the run time), and there will be no chance of them being in any custom-defined order.
You'll save yourself a lot of time and effort if you use a common serializer like XmlSerializer to handle converting your objects to/from strings. You don't have to write this type of code from scratch.