I'm having issues trying to pass a list as an argument. I'm not sure what I'm doing wrong. In the following I have an AssociatedTexts list that I am adding to a Books list with the addBook function. The AssociatedTexts that are being selected aren't being saved and assigned to that specific list item in the Books list.
Book dictionary = new Book(ID, textBox1.Text, Product.AssociatedTexts);
Inventory.addBook(dictionary);
The addBook function looks like this:
public static void addBook(Book dictionary)
{
Books.Add(dictionary);
}
And here's the constructor for Book:
public Book(int bookID, string name, BindingList<Book> assocText)
{
BookID = bookID;
Name = name;
AssociatedTexts = assocText;
}
You requested the entire Book class so here it is:
public class Book
{
public static BindingList<Text> AssociatedTexts { get; set; }
public string Name { get; set; }
public int BookID { get; set; }
public int TextID { get; private set; }
public Book()
{
}
public Book(int bookID, string name)
{
BookID = productID;
Name = name;
}
public Book(int bookID, string name, BindingList<Text> assocText)
{
BookID = bookID;
Name = name;
AssociatedTexts = assocText;
}
public static void addAssociatedTexts(Text text)
{
AssociatedTexts.Add(text);
}
public static bool removeAssociatedText(int textID)
{
bool ret = false;
if (Book.AssociatedTexts.Count > textID)
{
Book.AssociatedTexts.RemoveAt(textID);
ret = true;
}
else
{
ret = false;
}
return ret;
}
public Part lookupAssociatedTexts(int searchPart)
{
for (int i = 0; i < AssociatedTexts.Count; i++)
{
if (AssociatedTexts[i].TextID == searchPart)
{
return AssociatedTexts[i];
}
}
return null;
}
What I am trying to accomplish is for each entry in the list of Books to have it's own list of AssociatedTexts. I am mapping these onto datagridviews and the user is able to add their own books with their own varying associatedtexts onto it but I am having trouble associating each associatedtexts list with each Book
As each book shall have its own list of associated texts, AssociatedTexts must not be static. Otherwise, all books will share the same list.
Also, I suggest to replace BindingList by List as Book is a typical model class and should not contain such UI-related members.
public class Book
{
public List<Text> AssociatedTexts { get; set; }
public string Name { get; set; }
public int BookID { get; set; }
public Book(int bookID, string name, IEnumerable<Text> assocText)
{
BookID = bookID;
Name = name;
AssociatedTexts = assocText.ToList();
}
public void addAssociatedText(Text text)
{
AssociatedTexts.Add(text);
}
public bool removeAssociatedText(int textID)
{
bool ret = false;
if (AssociatedTexts.Count > textID)
{
AssociatedTexts.RemoveAt(textID);
ret = true;
}
else
{
ret = false;
}
return ret;
}
public Part lookupAssociatedTexts(int searchPart)
{
for (int i = 0; i < AssociatedTexts.Count; i++)
{
if (AssociatedTexts[i].TextID == searchPart)
{
return AssociatedTexts[i];
}
}
return null;
}
}
Related
How do I grab something like Name using the ID?
Code:
//PROPRIEDADES
public int Id
{
get { return id; }
set
{
if (value < 0)
throw new Exception("ID inválido");
id = value;
}
}
public string Username { get; set; }
public string Password { get; set; }
public string Nome_Completo { get; set; }
public string Email { get; set; }
...
CollectionBase:
public string idToName(int id)
{
foreach (Pessoa p in this.List)
{
if (p.Id == id)
{
return p.Nome_Completo;
}
}
return null;
}
Final result:
TABLE A: https://imgur.com/a/NuHG0sN NEED TO GET THE NOME_COMPLETO
TABLE B: https://imgur.com/a/xrf1GAU
Me trying to get the NAME FROM ID:
private void LoadListView()
{
lstvEncomendas.Items.Clear();
foreach (Encomenda en in brain.encomendas)
{
string[] subitems = new string[] { en.Id.ToString(), brain.pessoas.idToName(en.PessoaID)/*en.PessoaID.ToString()*/, en.Morada, en.Telefone, en.Descricao, en.Attachfile.ToString(), en.VoluntarioID.ToString(), en.Estado};
ListViewItem lviItem = new ListViewItem(subitems);
lstvEncomendas.Items.Add(lviItem);
}
}
Trying to populate an ObservableCollection from a database using the Entity Framework. Everything was fine until I started working with linked tables.
I created the DeviceCategory and DeviceComplexity model, and now in the WyeModel I try to integrate them into the DeviceCategoryViewModel. Further, in DeviceCategoryViewModel, I indicated a request for taking information from the database, but I ran into a problem. How to fill in ObservableCollection with this information? I tried different ways, but it didn’t lead to anything, I just got more confused.
DeviceCategoriesViewModel
class DeviceCategoryViewModel
{
TechDContext dc = new TechDContext();
public int Device_category_id { get; set; }
public string Device_category_name { get; set; }
public int Device_complexity_id { get; set; }
public string Device_complexity_name { get; set; }
public static DeviceCategoryViewModel DeviceCaterogyVM(DeviceCategory deviceCategory, DeviceComplexity deviceComplexity)
{
return new DeviceCategoryViewModel
{
Device_category_id = deviceCategory.Device_category_id,
Device_category_name = deviceCategory.Category_name,
Device_complexity_id = deviceCategory.Device_complexity_id,
Device_complexity_name = deviceComplexity.Device_complexity_name
};
}
public void FillDeviceDategories()
{
var q = from cat in dc.DeviceCategories
join com in dc.DeviceComplexities on cat.Device_complexity_id equals com.Device_complexity_id
select new
{
Device_category_id = cat.Device_category_id,
Category_name = cat.Category_name,
Device_complexity_id = com.Device_complexity_id,
Device_complexity_name = com.Device_complexity_name
};
items = q;
deviceCategories = Convert(items);
}
public ObservableCollection<DeviceCategoryViewModel>
Convert(IEnumerable<object> original)
{
return new ObservableCollection<DeviceCategoryViewModel>(original.Cast<DeviceCategoryViewModel>());
}
private IEnumerable<object> items;
public IEnumerable<object> Items
{
get
{
return items;
}
}
private ObservableCollection<DeviceCategoryViewModel> deviceCategories;
public ObservableCollection<DeviceCategoryViewModel> DeviceCategories
{
get
{
FillDeviceDategories();
return deviceCategories;
}
}
DeviceCategory Model
[Table("device_categories")]
public class DeviceCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Device_category_id { get; set; }
public string Category_name { get; set; }
//[ForeignKey]
public int Device_complexity_id { get; set; }
public DeviceCategory()
{
}
public DeviceCategory(string name, int complexity_id)
{
Category_name = name;
Device_complexity_id = complexity_id;
}
}
DeviceCompexity Model
[Table("device_complexities")]
public class DeviceComplexity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Device_complexity_id { get; set; }
public string Device_complexity_name { get; set; }
public DeviceComplexity()
{
}
public DeviceComplexity(string name)
{
Device_complexity_name = name;
}
}
I now get an error in the conversion method
You'd try to cast your LINQ query result to ObservableCollection<DeviceCategoryViewModel> in separate Convert function.
Why not to directly collect your LINQ query result to ObservableCollection<DeviceCategoryViewModel>
Just use like this
var q = from cat in dc.DeviceCategories
join com in dc.DeviceComplexities on cat.Device_complexity_id equals com.Device_complexity_id
select new DeviceCategoryViewModel // <= Note This Line
{
Device_category_id = cat.Device_category_id,
Category_name = cat.Category_name,
Device_complexity_id = com.Device_complexity_id,
Device_complexity_name = com.Device_complexity_name
};
deviceCategories = new ObservableCollection<DeviceCategoryViewModel>(q);
OR if you want to get result after list then simply use q.ToList()
deviceCategories = new ObservableCollection<DeviceCategoryViewModel>(q.ToList());
First, i'm a beginning in c#. I'm try to code some game. I don't know how to return enum value as string.
Here my code.
public class CARDS {
public CARDS(int id, int atk, ClassType ctype, string name) {
this.CARD_ID = id;
this.C_TYPE = ctype;
this.ATK = atk;
this.NAME_EN = name;
}
public CARDS() {
this.CARD_ID = -1;
}
public int CARD_ID { get; set; }
public ClassType C_TYPE { get; set; }
public int ATK { get; set; }
public string NAME_EN { get; set; }
public enum ClassType {
Warrior,
Mage,
Archer,
Thief,
Bishop,
Monk,
Guardian,
Destroyer,
Chaser,
Hermit,
Alchemy
}
}
.......
Here I try to do.
public class CardCollection : MonoBehaviour {
private List<CARDS> dbase = new List<CARDS>();
private JsonData cardsdata;
private JsonData card;
void Start() {
cardsdata = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/Json/card.json"));
ConstructCardData();
Debug.Log(dbase[1].NAME_EN + " " + dbase[23].NAME_EN);
}
void ConstructCardData() {
card = cardsdata["CARDS"];
for (int i = 0; i < card.Count; i++) {
dbase.Add(new CARDS((int)card[i]["CARD_ID"], (int)card[i]["ATK"], card[i]["C_TYPE"].ToString(), card[i]["NAME_EN"].ToString()));
}
}
}
// card[i]["C_TYPE"].ToString()
It say can't convert from string to CARDS.ClassType
What about :
public class CARDS
{
public CARDS(int id, int atk, ClassType ctype, string name)
{
this.CARD_ID = id;
this.C_TYPE = Enum.GetName(ctype.GetType(), ctype); //Use Enum.GetName to get string
this.ATK = atk;
this.NAME_EN = name;
}
public CARDS()
{
this.CARD_ID = -1;
}
public int CARD_ID { get; set; }
public string C_TYPE { get; set; } //change type to string
public int ATK { get; set; }
public string NAME_EN { get; set; }
public enum ClassType
{
Warrior,
Mage,
Archer,
Thief,
Bishop,
Monk,
Guardian,
Destroyer,
Chaser,
Hermit,
Alchemy
}
}
ToString() on the enum values return the string value of the enum. Custom string values can also be returned for the enum values, check these links, link1 , link2
Examples:
ClassType.Warrior.ToString();
ctype.ToString();
I have this:
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
public List<???prpClass???> Whatever(string prpClass)
where string prpClass can be "Blah" or "Doh".
I would like the List type to be class Blah or Doh based on what the string prpClass holds.
How can I achieve this?
EDIT:
public List<prpClass??> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result;
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result;
}
return null
}
}
you have to have a common supertype:
public interface IHaveAnId
{
int id { get;set; }
}
public class Blah : IHaveAnId
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh : IHaveAnId
{
public int id {get;set;}
public string dohh { get; set; }
public string mahh { get; set; }
}
then you can do:
public List<IHaveAnId> TheList = new List<IHaveAnId>();
and in some method:
TheList.Add(new Blah{id=1,blahh = "someValue"});
TheList.Add(new Doh{id =2, dohh = "someValue", mahh = "someotherValue"});
to iterate through the list:
foreach(IHaveAnId item in TheList)
{
Console.WriteLine("TheList contains an item with id {0}", item.id);
//item.id is allowed since you access the property of the class over the interface
}
or to iterate through all Blahs:
foreach(Blah item in TheList.OfType<Blah>())
{
Console.WriteLine("TheList contains a Blah with id {0} and blahh ='{1}'", item.id, item.blahh);
}
Edit:
the 2 methods and a int field holding the autovalue:
private int autoValue = 0;
public void AddBlah(string blahh)
{
TheList.Add(new Blah{id = autovalue++, blahh = blahh});
}
public void AddDoh(string dohh, string mahh)
{
TheList.Add(new Doh{id = autovalue++, dohh = dohh, mahh = mahh});
}
Another Edit
public List<object> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result.Cast<object>().ToList();
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result.Cast<object>.ToList();
}
return null;
}
}
in the view you then have to decide what type it is. In asp.net MVC you can use a display template and use reflection to get a good design. But then i still don't know what technology you are using.
Yet another Edit
TestClass:
public class SomeClass
{
public string Property { get; set; }
}
Repository:
public static class Repository
{
public static List<object> Whatever(string prpClass)
{
switch (prpClass)
{
case "SomeClass":
return new List<SomeClass>()
{
new SomeClass{Property = "somestring"},
new SomeClass{Property = "someOtherString"}
}.Cast<object>().ToList();
default:
return null;
}
}
}
And a controller action in mvc:
public JsonResult Test(string className)
{
return Json(Repository.Whatever("SomeClass"),JsonRequestBehavior.AllowGet);
}
then i called it with: http://localhost:56619/Home/Test?className=SomeClass
And got the result:
[{"Property":"somestring"},{"Property":"someOtherString"}]
Is this what you are trying to do?
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
class Program
{
public static List<T> Whatever<T>(int count) where T: new()
{
return Enumerable.Range(0, count).Select((i) => new T()).ToList();
}
static void Main(string[] args)
{
var list=Whatever<Doh>(100);
// list containts 100 of "Doh"
}
}
I have an object myBook.
Can I implement a better structure for that kind of data?
public class myRow{
public int ID = 0;
public int number = 0;
public String param1 = null;
public decimal param2 = null;
public string parm3 = "";
public int param4 = null;
}
public class mySubChapter{
public int ID = 0;
public string title = "";
public List<myRow> rows;
internal bool sort(){...} //sort rows by ID
}
public class myChapter{
public int ID = 0;
public string title = "";
public List<mySubChapter> subChapters;
internal bool sort(){...} //sort subChapters by ID
}
public class myBook{
public int ID = 0;
public string title = ""
public List<myChapter> chapters;
internal bool sort(){...} //sort chapters by ID
}
If you really want to model your book structure in a tree, you could use a generic tree implementation like the one presented here. Then, you could form a tree using code like this
DTreeNode<string> root = new DTreeNode<string>();
DTreeNode<string> temp;
temp = root.Nodes.Add("Hello");
temp.Nodes.Add("olleH");
temp = root.Nodes.Add("World");
temp.Nodes.AddRange(new string[]
{ "dWorl", "ldWor", "rldWo", "orldW" } );
In my opinion, I'll merge subchapter and chapper class into one myChaper class and add new property is chapterLevel in it. Because I think subChapter is a chapter too with just difference level(children of chapter may be). Sorry for my English.
public class myRow{
public int ID = 0;
public int number = 0;
public String param1 = null;
public decimal param2 = null;
public string parm3 = "";
public int param4 = null;
}
public class myChapter{
public int ID = 0;
public string title = "";
public int chapterLevel = 0;
internal bool sort(){...} //sort chapters by ID and level
}
public class myBook{
public int ID = 0;
public string title = ""
public List<myChapter> chapters;
internal bool sort(){...} //sort chapters by ID
}
Another tree implementation:
public interface INode
{
int Id { get; set; }
INode Parent { get; }
ReadOnlyCollection<INode> Children { get; }
void SetParent(INode node);
void AddChild(INode node);
}
public class Node : INode
{
private INode _parent;
private IList<INode> _children;
public Node()
{
_children = new List<INode>();
}
public int Id { get; set; }
public INode Parent
{
get { return _parent; }
}
public ReadOnlyCollection<INode> Children
{
get
{
return new ReadOnlyCollection<INode>
(_children.OrderBy(c => c.Id).ToList());
}
}
public virtual void AddNode(INode node)
{
_children.Add(node);
node.SetParent(this);
}
public virtual void SetParent(INode node)
{
_parent = node;
}
}
The classes, Row, Chapter, Book can derive from the Node class, e.g.
public class Book : Node
{
public override void SetParent(INode node)
{
throw new InvalidOperationException();
}
public string Title { get; set; }
}