w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Make DataGridView Show Properties of Derived Class Objects when Using List of Base Class Objects
One way is to cast back each element in the list,do the next change and you will get 1,2,3 in the datagridview: col.DataPropertyName = "MyPropertyDerived"; dataGridView.Columns.Add(col); dataGridView.DataSource = list.ConvertAll(c => c as MyDerivedClass);

Categories : C#

adding multiple class objects to a single list and returning the values from the objects
You can provide an overload of the ToString method for each class: class classOne:onetwo { int item1 = 10; int item2 = 11; public override string ToString() { return string.Format("item1: {0}, item2: {1}", item1, item2); } } class classTwo:onetwo { string item3 = "red"; string item4 = "blue"; public override string ToString() { return string.Format("item3: {0}, item4: {1}", item3, item4); } } Another alternative is to provide a custom method in your base class to generate a formatted string via reflection: class onetwo { public virtual string ToPrintableString() { return string.Join(", ", this.GetType() .GetFields() .Select(p => p.Name + ": " + p.G

Categories : C#

Unmarshall xml list of objects to java list without class list
You could use JAXB with StAX to do the following: import java.util.*; import javax.xml.bind.*; import javax.xml.stream.*; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(User.class); XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource("src/forum17047306/input.xml"); XMLStreamReader xsr = xif.createXMLStreamReader(xml); List<User> users = new ArrayList<User>(); Unmarshaller unmarshaller = jc.createUnmarshaller(); while(xsr.getEventType() != XMLStreamReader.END_DOCUMENT) { if(xsr.isStartElement() && "User".equals(xsr.getLocalName())) {

Categories : Java

Windows Form partial class resets value when declared from another form
Its not because of partial classes. You have to pass the selected device to the Device_Options class through constructor or a property. public partial class Device_Options : Form { public Device_Options() { InitializeComponent(); deviceLabel.Text = devices.selectedDevice; } public Device_Options(Device selectedDevice) { InitializeComponent(); deviceLabel.Text = selectedDevice; } } On Devices Call as follows, new Device_Options(selectedDevice).Show();

Categories : C#

Fetching objects of class B stored in a list inside class A with Hibernate Criteria
This is the expected result. You are running the query on the User class so, the output would be a collection of User and not notification public List<Notification> getNotifications(Long id){ //Start the transaction //do some error handling and transaction rollback User user = session.createQuery("from User where id = :id").setParameter("id", id).uniqueParameter(); List<Notification> notifications = new ArrayList<Notification>(); for (Notification notification : user.getNotifications()){ if (notification.getDate.before(calendar.getTime()){ notifications.add(notification); } } //commit the transaction //close the session return notifications; } Or the other way of doing it would be to use Filters. You can find a tutorial on filters here

Categories : Java

Comparing objects from two instances of a Class and storing result in List
The best way to do this is to make ESHClass know how to compare itself for equality. See this link for a fairly in-depth example, or this question for a more minimal set. Basically, you give the code enough information to be able to evaluate eshlist[0] == eshlist[1] directly.

Categories : C#

Adding Sharepoint List Item to Windows form list
Completely untested, made fresh while drinking morning coffee. Good luck! var list = siteWeb.Lists.TryGetList(listName); if (list == null) { return; } var items = list.GetItems(query); var countOfItems = items.Count; if (countOfItems == 0) { return; } var listItemFieldObjects = items.Cast<SPListItem>().Select(item => item[1]); foreach (var item in listItemFieldObjects) { var listViewItem = new ListViewItem("Object's value"); listView.BeginUpdate(); listViewItem.SubItems.Add(item.ToString()); listView.Items.Add(listViewItem); listView.EndUpdate(); }

Categories : Sharepoint

Serializing and deserializing a list of objects in a Windows Phone 8 app
I'm using these methods to Save and Load from a XML file in/to the IsolatedStorage : public static class IsolatedStorageOperations { public static async Task Save<T>(this T obj, string file) { await Task.Run(() => { IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream stream = null; try { stream = storage.CreateFile(file); XmlSerializer serializer = new XmlSerializer(typeof (T)); serializer.Serialize(stream, obj); } catch (Exception) { } finally { if (stream != n

Categories : Windows Phone 8

Django CBV form using list of objects
I ended up adding a post() function to the ListView which processes the form data, but I am having trouble redirecting without a valid HttpResponse object and am getting an error when one of the boxes isn't checked in the form. Here is the additional post() code that I added for the time being: def post(self, request, *args, **kwargs): cars = Car.objects.all() # initially reset "self.send" field == False for i in range(len(cars)): cars[i].send = False cars[i].save() cars = Car.objects.filter(id__in=request.POST.getlist('car')) for i in cars: i.send = True i.save() return HttpResponseRedirect(reverse('cars:email_preview')) Any suggestions on how to make the form re-render with an error msg if no boxes are checked? Thanks

Categories : Python

Post a List of Objects to Controller Without a Form
You need to specify a Prefix in your Action like this: [HttpPost] public ActionResult TestMethod([Bind(Prefix = "testList")] List<TestViewModel> testList) { // irrelevant code here }

Categories : C#

List of objects in a parent class
Use some sort of queue void Main() { Events.Queue(new Message(){ Text = "Hit points +5" }); Events.Queue(new Message(){ Text = "Hit points +6" }); Events.Queue(new Message(){ Text = "Hit points +7" }); while(Events.HasNext()) { Console.WriteLine(Events.GetNext().Text); } } public static class Events { private static Queue<Message> messages = new Queue<Message>(); public static void Queue(Message message) { messages.Enqueue(message); } public static Message GetNext() { return messages.Dequeue(); } public static bool HasNext() { return messages.Count > 0; } } public class Message { public string Text {get; set;} } In a more dynamic way, you can use interfaces to build a

Categories : C#

Populate Class from List of Objects C#
This is a great tool if you have to do lots of mapping from one object to another. Gives you a standard way of doing it. AutoMapper

Categories : Dotnet

Integrating a windows form in OutLookAddIn project and calling the OutLookAddIn class form winform?
Do the following, first create a new instance of the ThisAddin class, then call the Validate method in the ThisAddin class from the new created instance. Change: public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } } To: public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { ThisAddin ta = new ThisAddin(); ta.Validate(); } } Change the ThisAddin class from: public partial class ThisAddIn { private void

Categories : C#

Spring MVC Form binding a group of two or more fields into a list of objects
This may not be the best technique for this, but here is how I would implement a solution for your question. Create a field for each of the phone fields in the PhoneForm. This will be useful, if for nothing else, to set the value on your page. Create a method in the PhoneForm class (perhaps called getMobilePhoneList()) that creates a list of Phone objects for the mobile phones. Create a method in the PhoneForm class that creates a list of Phone objects for the personal phones. Create a method in the PhoneForm class that creates a list of Phone objects for the work phones. Use the PhoneForm getters to populate fields on the page and during validation. Use the getxxxPhoneList() methods in java when you need them.

Categories : Java

Passing a list of objects between events in a single ASP.NET form from DevExpress
Store the list of selected items in Session cache, like this: protected void buttonResend_Click(object sender, EventArgs e) { List<Items> listOfSelectedItems = new List<Items>(); // Put logic here for populating listOfSelectedItems // Store listOfSelectedItems in Session cache Session["SelectedItems"] = listOfSelectedItems; } Note: I made up the Items class that is stored in List<T>; obviously whatever class you have for holding the selected items will work or even just a list of strings. Now in the "other" page, you can retrieve the listOfSelectedItems in Session, like this: if(Session["SelectedItems"] != null) { List<Items> listOfItems = Session["SelectedItems"] as List<Items>; // Put logic here to work with list of selected it

Categories : C#

Can PFBC (Php form builder class) submit JSON objects?
So I figured out have to force a submit of a JSON string. Basically this line has to be changed to this: data: {data: JSON.stringify(objectifyArray($("#" + $id.id).serializeArray()))} Explanation: #$id is written in php, and you'd expect it to be the id of the form in question (which Jquery somehow interprets it as) with an appended "#" for jquery, as is normally the case when including variables in strings. However, it's actually the whole damn form in a text-string (I have no idea how/why though :/), therefor "#" + $id.id has to replace it, to get the actual ID-property of the form in question. After that's done, it's just a matter of formatting the form to a correct JSON string, which the line does, with the help of objectifyArray and the JSON.js javascript library. function

Categories : PHP

Calling a Windows Form by its class name
VS2012 VB.NET does have default instances, just like in VS2010. Most likely you have defined a custom Sub New() with a parameter list, e.g. Sub New(a As Integer). When this is the case no default instance is generated, you need to explicitly create the form.

Categories : Vb.Net

How to store class objects in a list in android?
Simply create a list of Objects, something like this: List<Object> objList = new ArrayList<Object>(); and then add the objects of your classes like this: objList.add(obj);

Categories : Java

Array / List / collection of objects of a class in R
Try using replicate nodeID <- replicate(100, new("node"), simplify="list") is(nodeID) # [1] "list" "vector" is(nodeID[[1]]) # [1] "node" Using something like nodeID[100] <- new("node") as you found, does not work. What that (is attempting) to do is look for an object called nodeID and if found, try to set its 100th element to new("node"). It does not, say, create an object nodeID and populate it with 100 elements. Also, notice that you can avoid your for loop by instead using, say, lapply: eg, instead of: for(i in 1:dim(nodeID)) { nodeID[i]@capacity <- 1000 blah blah.... } use: lapply(nodeID, function(n) {blah balh...} )

Categories : R

sorting a list with objects of a class as its items
your_list.sort(key = lambda x : x.anniversary_score) or if the attribute name is a string then you can use : import operator your_list.sort(key=operator.attrgetter('anniversary_score'))

Categories : Python

Send a list of class objects through a socket or tcp
The usual problems: not processing the return value of Read thinking that the available-bytes represents complete units of data the lack of logical framing (usually via a length-prefix) Personally I'd also say that using BinaryFormatter is problematic, but that isn't the biggest issue. See http://marcgravell.blogspot.com/2013/02/how-many-ways-can-you-mess-up-io.html

Categories : C#

How can i mapp list of objects in the same class with same type
Firstly, I would use a Set, instead of a List as duplicates are disallowed. Also, in your database table, you will need to have a Person_Id (Primary Key) and a Parent_Person_Id (Foreign Key that references the Person_Id PK). This will then ensure the relationship between a person (a parent) and a set of people (the children in the relationship). One example is that of a Manager and Employees. A manager is a Person and so is an Employee, but the manager manages many Employees and in this case the parent is the Manager and the Employees are children. So your Person class would look like: public class Person { // normal properties/attributes Set<Person> persons; // getters and setters // addPerson to the Set method } Then, you could use the following mapping: <

Categories : Hibernate

How to use map() to call class methods on a list of objects
If the contents of the list are all instances of the same class, you can prefix the method name with the class name. class Fred: def __init__(self, val): self.val = val def frob(self): return self.val freds = [Fred(4), Fred(8), Fred(15)] print map(Fred.frob, freds) Result: [4, 8, 15] This can also be done if the elements of the list are subclasses of the specified class. However, it will still call the specified implementation of the method, even if that method is overridden in the subclass. Example: class Fred: def __init__(self, val): self.val = val def frob(self): return self.val class Barney(Fred): def frob(self): return self.val * 2 freds = [Fred(4), Barney(8), Barney(15)] #You might expect the barneys to return twi

Categories : Python

how to call python class list objects
You have to instantiate your class before: ship1 = Ship( pos, vel, angle, image, info) After that you can use the class methods and attributes: posx, posy = ship1.pos From the our comments I think this would fit your needs: class Ship: def __init__(self, pos, vel, angle, image, info): self.pos = list(pos) self.vel = list(vel) def move(self, key): if key=='left': self.pos[0] -= self.vel[0] if key=='right': self.pos[0] += self.vel[0] if key=='down': self.pos[1] -= self.vel[1] if key=='up': self.pos[1] += self.vel[1] #example ship1 = Ship( (0,0), (10,10), angle=None, image=None, info='') def keystroke(key): global current_key ship1.move(key) I am not sure how does simplegui works, but in this way you can effici

Categories : List

WCF Return list of baseclass objects containing derived class
Try adding a KnownTypeAttribute to your Animal class for each subclass you'd like to have serialized: [DataContract] [KnownType(typeof(Snake))] [KnownType(typeof(Pig))] public class Animal { }

Categories : C#

Correct way to change value of an item in a list of class objects
Dinosaurs.Last() returns the last item, not its index, so this: Dinosaurs.Last().Location.X = pixelMousePositionX; If you want to do it by index, then this: Dinosaurs[Dinosaurs.Count - 1].Location.X = pixelMousePositionX;

Categories : C#

Android json objects to array list in Parcelable class
You can use droidQuery to simplify JSON parsing. To convert your JSONObject to a Key-Value mapping, you can use this: List<String> items = new ArrayList<String>();//this will contain your JSONObject strings Map<String, ?> data = null; try { JSONObject json;//this references your JSONObject data = $.map(json); } catch (Throwable t) { Log.e("JSON", "Malformed JSON Object"); } Then, to loop through each element, just do this: if (data != null) { for (Map.Entry<String, ?> entry : data.entrySet()) { items.add(entry.value().toString()); } } Now your List items is populated with the String representation of your JSONObejcts. Later, if you want to parse this JSON, just do: int index = 2;//the index of the JSONObject you want try { Map

Categories : Android

Looking for guidance in creating a helper class for Sql Queries and Windows Form
Make a method return a List of strings from your database query and put this method in antoher class (e.g. called SQLHelper). You can put all your SQL related methods here. Make the return types independant from SQL specific classes. Like a list of strings, specific person objects, whatsoever. Make this SQL helper class a member of your Form class and call it's methods when you need to. Use it's return values to do the stuff you have to do. public class SQLHelper { public IList<Person> GetPersons() { try { var result = new List<Person>(); conn = new MySqlConnection(connstring); conn.Open(); MySqlCommand myCommand = new MySqlCommand("SELECT * FROM person", conn); MySqlDataReader myReader;

Categories : C#

Create a XML Serialization and Deserialization for generic list in C# windows form application?
you have to have a base class to present your data and is an example: [XmlIncludeAttribute(typeof(ConcreteFooOne))] [XmlIncludeAttribute(typeof(ConcreteFooTwo))] [XmlIncludeAttribute(typeof(ConcreteFooThree))] [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar")] public abstract partial class AbstractFoo { } [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar")] public class ConcreteFooOne : AbstractFoo { public string MyProp { get; set; } } [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar")] public class ConcreteFooTwo : AbstractFoo { } [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar")] public class ConcreteFooThree : AbstractFoo { } class Program { static void Main() {

Categories : C#

How to get List data from class to Form
Have method Foo return the final questions variable... public List<Question> Foo(string TopicId, string[] conf) { // do all the same stuff... return finalQuestions; } Then, in your GroupExmStart method do the following... Question qsn = new Question(); string[] conf = db.GetConfiguration(Convert.ToInt16(DurationID)).Split('|'); QuestionSet = string.Join(",", qsn.Foo(TopiID, conf)); int z = Quiz(QuestionSet); Edit per comment #1 A better way, IMO, would be to not join them to begin with; and just pass the list of questions into the Quiz method directly. So you would have to alter the Quiz method to take a list of Questions like: int Quiz(List<Question> questions) And then remove the string.Join from above. Question qsn = new Question(); string[] conf = db.GetC

Categories : C#

python dict of class objects that inherits attributes from class objects
This is a bit of an odd question, but it very much depends on what 'D' is structurally. If D is just a data structure, then it is perfectly valid to pack the dictionary with the objects, subcript and call the functions like so: class A(object): def __init__(self,x): self.x = x def first(self): return self.x a = A(7) b = A(3) d = {'X':a,'Y':b} print d['X'].first() Alongside this, if you want all "firsts" then you can do something like this: firsts = {} for i,j in d: firsts[i]=j.first() However, it seems like your challenge is a little more complex, plus unsafe: what if an objecy in the dictionary has a keys() method? Which takes precedence, and if its the dictionaries, how do I access the keys() method of the contents? What I'd suggest is reframing, or reaski

Categories : Python

How to pass multiple model objects from controller and how to pass all as command objects into the form:form in spring mvc?
Just add both person and address into an enveloping object called personDetails and pass that to the form. class PersonDetails { private Person person; private Address address; ... } PersonDetails personDetails = new PersonDetails(); personDetails.setPerson(new Person()); personDetails.setAddress(new Address()); model.addAttribute(“personDetails”, personDetails); <form:form action=”registration” command=”personDetails”> Once you do that, you'll have to modify the paths appropriately. <form:input path="firstName" /> becomes <form:input path="person.firstName" /> Other more elegant option is to enclose Address within the Person and just expose the Person as a command. Just as @Seabook mentioned in his answer below.

Categories : Java

C++ - Copying of objects of derived class into objects of base class
You cannot convert a base object to a derived object because there isn't enough information. It's like having an empty sandwich and pretending its a BLT! The problem with downcasting an object is that the derived class may be bigger so wouldn't fit in the available memory but the pointer is allowed since the derived class is exactly and more of the base class. Continuing the sandwich metaphor: if you ignore the filling, a BLT is just an empty sandwich. In your example mgr6 thinks it is pointing to a manager but say there was a getter for bool salaried called IsSalaried() what should happen if when you call mgr6->IsSalaried(). This is obviously not logical therefore it is not allowed.

Categories : C++

How to use a case class to deserialize an array of json objects to List[Map[String,String]]
As I replied to you on the Salat mailing list, Salat doesn't support deserializing nested collections right now. https://github.com/novus/salat/wiki/Collections

Categories : Scala

I have a list that stores PointD objects. PointD is a class for storing x and y in double
First, I would redefine the PointD class like this: class PointD { public double M_dPointDx; public double M_dPointDy; public PointD(double x, double y) { M_dPointDx = x; M_dPointDy = y; } } Define the following class which implements the IEqualityComparer<PointD> interface: class MyComparer : IEqualityComparer<PointD> { public bool Equals(PointD x, PointD y) { //Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) return true; //Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; //Check whether the PointD' properties are equal. return x.M_dP

Categories : C#

Extraction of list of objects from list of objects in Java
There is a solution. This uses Guava. You need a Function<A, B>, then apply that function using Lists.transform(): final Function extractB = new Function<A, B>() { @Override public B apply(final A input) { return input.getB(); } } // And then: final List<B> listOfB = Lists.transform(listOfA, extractB); Note that Java 8 will have Function, among other niceties "invented" by Guava (Predicate is another example).

Categories : Java

Custom List Box (or) custom Panel in windows form
I've tried writing this to let you see how a custom panel looks like (:), this is not a complete list control and need to be extended more but it meets most of your demands. I think this is a good example for you and helps you get started so that you can build your own custom control easily: public class ListPanel : Panel { public ListPanel() { AutoScroll = true; BorderStyle = BorderStyle.FixedSingle; } private List<ListPanelItem> items = new List<ListPanelItem>(); public void AddItem(ListPanelItem item) { item.Index = items.Count; items.Add(item); Controls.Add(item); item.BringToFront(); item.Click += ItemClicked; } public int SelectedIndex { get; set; } public ListPanelIte

Categories : C#

How to pass a List of objects from a controller to a view and access the properties of every objects?
Have you tried: <select> @foreach (var contact in ViewBag.ListeContacts) { <option>@Html.DisplayName(contact["nom_contact"].ToString())</option> } </select> It looks like you have a list of Contact and you are trying to get a DataRow from the collection? EDIT: Also make sure the property you are referencing exists, i.e. nom_contact

Categories : Asp Net

How can I add objects to an array list using the equals method to exclude similar objects?
There is a lot to discover in the Java Collection. You are using the wrong data structure, you can add two different objects in a List because the purpose of the list is to be : An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. So you have the elements in a given order which is kept when adding objects and you can access objects at any given index in this order. Now it seems that's not what you want, you'd rather have no duplicate elements rather than an order, right ? If so you need to use a class that implements the Set interface which purpose is to be : A collection that

Categories : Java

can we have multiple form in a single form in windows form application?
Create a windows form. This will be your main form. Assuming your using Visual Studio this is realatively easy. Once you have your main form up, drag and drop a user controller onto your form. Have your main form contain the 5 buttons,and your data grid on the other form.

Categories : Windows



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.