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#

Bind List of objects to datagridview with Fluent NHibernate - ToString override
Try this in your mapping. This will eager load the Objects instead of Lazy Loading by default. References(x => x.Material).Column("IdMaterialu").Not.LazyLoad(); References(x => x.Producent).Column("IdProducenta").Not.LazyLoad();

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#

Adding "hidden (or meta)" column to DataTable that will not be displayed in the bound DataGridView
Change the Visible property of your DataGridViewColumn. From msdn: // Hide a band of cells. private void Button6_Click(object sender, System.EventArgs e) { DataGridViewBand band = dataGridView.Rows[3]; band.Visible = false; }

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

Adding new objects to a list; (For loop not working properly)
Because you are inserting the name data into index [0] of your nameslist array every time, so every loop you are replacing your previous data and at the very end you end up with one item that equals your last entry. You need to assign the proper array index to each. nameslist[i] = new Names(first, last, number);

Categories : Java

Why does adding a list to another list, using add range, remove the elements from the first list?
It's because of the IEnumerable. When you set groupsToAdd to the result of groups1.Where(g => false == groups2.Contains(g)) there is deferred execution, which means that the query is not run until AddRange() and then again at Dump(). Because the list, groups2, now contains the elements they no longer are a result of the original query.

Categories : C#

Filling a DataGridView with a List>()
If you had a class with the properties defined in it, and then have a List<customClass> then it would be simple. Plus it defines the column names for you. Not sure if that is feasible in your situation. public class foo { public string foo1 {get;set;} public string foo2 {get;set;} } public Form1() { InitializeComponent(); var foo = new foo() ; foo.foo1 = "some"; foo.foo2 = "text"; List<foo> _foo = new List<foo>(); _foo.Add(foo); dgv.DataSource = _foo; }

Categories : C#

WPF How to bind list to itemscontrol with each item being paired to a customcontrol and bound to the ith item in list
The DataContext for each UI item in the ItemsControl will automatically be assigned to the corresponding Data Item in the source Collection. Therefore this is valid and will work: <ItemsControl x:Name ="Signalviewer_Control" ItemsSource="{Binding Source = {StaticResource signal_data}, Path = list_of_signals}"> <ItemsControl.ItemTemplate> <DataTemplate> <wpfExp:SignalViewer Signal="{Binding}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>

Categories : Wpf

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

How to sort list of locale objects in list interface using comparator in java
You are using an unmodifiable list. If you put the elements in a modifiable list it can be sorted. Otherwise you could your own sorting algorithm that put the elements in a new list. This approach could be faster. Try this instead: List<Locale> localeList = new ArrayList<Locale>(list); Collections.sort(localeList, comparator);

Categories : Java

How to convert list of group-by objects into html unordered list in Java?
public String convertToHTML(ArrayList<CountData> stuffs){ StringBuilder sb = new StringBuilder() sb.append(“<ul> ”); for(CountData cd : stuffs){ sb.append(“<li>”+cd.getCountry()+” (“+cd.getCount()+”) ”); sb.append(“ <ul>); sb.append(“ <li>”+cd.getState()+” (“+cd.getCount()+”) ”); sb.append(“ <ul>); sb.append(“ <li>”+cd.getCity()+” (“+cd.getCount()+”) ”); sb.append(“ <ul>); sb.append(“ <li>”+cd.getMfc()+” (“+cd.getCount()+”)</li> ”); sb.append(“ </ul>); sb.append(“ </li>); sb.append(“ </ul>); sb.append(“ </li>); sb.app

Categories : Java

Using linq group by to get from a list of objects with a DateTime property to a list with an interval StartDate, EndDate
You can use GroupBy in combination with SelectMany and Aggregate for this: var setups = bookedRooms.GroupBy(x => Tuple.Create(x.TimePeriodId, x.VenueId)) .SelectMany(x => x.Aggregate( new List<EventSetup>(), AccumulateRooms)) .OrderBy(x => x.StartDate) .ToList(); List<EventSetup> AccumulateRooms(List<EventSetup> existingSetups, BookedRoom currentRoom) { var setup = existingSetups.LastOrDefault(); if(setup == null || setup.EndDate.AddDays(1) != currentRoom.Day.Date) { setup = new EventSetup { VenueId = currentRoom.VenueId, TimePeriodId = currentRoom.TimePeriodId, StartDate = currentR

Categories : C#

Append different object into list but the list result in same objects repeating
Whenever you call neighbor_list.append(neighbor) you just add a reference to neighbor, rather than a new list. This means that every list in neighbor_list is just the current value of neighbor. To fix this, you should make a copy of the list like this: neighbor_list.append(copy.copy(neighbor) Documentation for copy

Categories : Python

Getting unique values from a list of objects with a List as a property
If I understand, you want a list of all of the unique certifications among all of the employees. This would be a job for SelectMany: var uniqueCerts = empList.SelectMany(e => e.Certifications).Distinct().ToList();

Categories : C#

conditionally adding multiple items to a list of lists via python list comprehension
The line html = BeautifulSoup(urllib2.urlopen('http://domain.com').read(), 'lxml') implies you have lxml installed, so you could use an XPath using | to pull out text or attribute values: import urllib2 import lxml.html as LH html = LH.parse(urllib2.urlopen('http://domain.com')) clean_data = [[elt for elt in tr.xpath('td/a/text() | td/a/@href | td/text()')] for tr in html.xpath('//table[@id="targeted_table"]/tr')] print(clean_data) yields [['http://domain.com', 'data 01', 'data 02', 'data 03', 'data 04'], ['http://domain.com', 'data 11', 'data 12', 'data 13', 'data 14'], ['http://domain.com', 'data 01', 'data 22', 'data 23', 'data 24'], ['http://domain.com', 'data 01', 'data 32', 'data 33', 'data 34']] You could also do it with a single call to the xpath met

Categories : Python

Adding checked items in a custom list view to array list in android
initialize the "ArrayList" ArrayList<List> selectedItems; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_page); selectedItems = new ArrayList<List>(); }

Categories : Android

knockoutjs - How to Create a List style app in with entry before adding list items
You are in fact very close to making it work. The problem was that you did not define the donationAmount observable property in the main view model, which resulted in KnockoutJS failing when binding this unavailable property to the input tag. Here is the part of the code that had to be changed so that it works now: function DonationsViewModel() { var self = this; self.donationAmount = ko.observable(); // .... } and here's some little change to your HTML: <div> <select data-bind="options: availableDonations, optionsCaption: 'Please select...', value: selectedDonation, optionsText: 'label'"></select> <input data-bind="value: donationAmount"/> <button typ="button" data-bind="click: addDonation">Add Donation<

Categories : Knockout Js

Adding specific items from a list to a new list, index out of range error
The simple fix is to wrap your append in a try catch statement. for item in stock_data: try: closing_prices.append(stock_data[count]) except IndexError: break print (closing_prices) count = count + 6 the reason you are getting to the error is that when you get to the 5th to the last item in the list then add 6 to it you are now out of range of the lists maximum index so to speak. Another possible solution is to use a while loop. closing_prices = [] count = 10 while count < len(stock_data): closing_prices.append(stock_data[count]) count += 6 print closing_prices

Categories : Python

Selenium adding items from a Web element list to a string array list
Please try using following sample code, change xpath/data accordingly List<WebElement> resultList = _driver.findElements(By.xpath("//img[contains(@src,'tab-close.png')]/preceding-sibling::span[@class='tab-name ng-binding']")); for (WebElement resultItem : resultList){ String tabname=resultItem.getText(); if(resultItem.getText().equalsIgnoreCase("Dashboard")){ GlobalFunctions.clickOnButtonCustomised(false, _driver, By.xpath("//span[@class='tab-name ng-binding' and contains(text(),'"+tabname+"')]/following-sibling::img[contains(@src,'tab-close.png')]"), ""); } }

Categories : Java

Reflect changes made to database on datagridview
Try grid_display.ResetBindings(); According to MSDN- This method causes a control bound to the BindingSource to reread all the items in the list and refresh their displayed values.

Categories : C#

Should adding a new item to a list<> update previous items in the list?
You're not adding several different items to the list, you're adding the same exact item several times and modifying it each time. Classes in C# are reference types; that means each variable doesn't hold the data for the object itself, it just hold onto a reference to where that object is. Assigning an object to another variable doesn't create a new object, it just copies the reference to that same object. The issue is that you should be creating a new object (i.e. using the new keyword) each time you go to add a new item to the list. From the looks of your code it would seem that StaticLists.GetStockMultibuyForBarcode(sBarcode) isn't returning a new item each time; it's just returning the same item, or at the very least one of the existing items. You should be creating a new item, co

Categories : C#

python adding list inside list unexpected behavior
You are manipulating the same list over and over again, not a copy. Create a new list in the loop instead: for elemento in lista_base: listado = [elemento, elemento + 1, elemento + 2] tabla.append(listado) or create a copy of the list: for elemento in lista_base: listado[0] = elemento listado[1] = elemento+1 listado[2] = elemento+2 tabla.append(listado[:]) where [:] returns a full slice of all the elements. You could also use list(listado) or import the copy module and use copy.copy(listado) to create a copy of the existing list. Appending a list to another list only adds a reference, and your code thus created many references to the same list that you kept changing in the loop. You could have seen what was happening had you printed tabla on every loop. Pri

Categories : Python

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

Kendo grid custom editor dropdown list doesn't reflect the selection
The way I commonly solve this problem in the Kendo grid is to create lookups of the available selection items which I can then use to retrieve the value to be displayed in the grid by its id: window.lookups = {}; var userTypeLookup = window.lookups["user_type"] = {}; $.each(user_type, function (idx, value) { userTypeLookup[value.typeid] = value.typename; }); In the column template I can reference the lookup to get the display value: { field: "typeid", editor: userTypeList, template: '#= lookups["user_type"][typeid] #' } Here is an updated Fiddle which implements this approach: http://jsfiddle.net/uMws5/4/

Categories : Javascript

Deserializing List of objects yields empty list
Ok, I've reimplemented your solution in C#, and what makes the difference is the fact that you didn't provide the namespace for TaskRequests in MobileRequest class. To summarize: 1) You mix attributes for DataContractSerializer and XmlSerializer which makes this code hard to manage, I've used only XmlSerializer related attributes. 2) The XML you've provided cannot be the result of serializing the classes you've presented. It contains "MyNameSpace" on TaskReqests field, whereas in your code there are no namespaces for XmlSerializer (only for DataContractSerializer which is not relevant here). 3) The minimal fix of your code to make XML you've given deserialize correctly (see edit below) is: [Serializable] public class MobileRequest { [XmlArray(Namespace="MyNameSpace")] //note the n

Categories : Xml

Create a list of integer elements from list of objects
Use a set: sorted(set().union(first, second)) #returns a sorted list of unique items Demo: >>> first = [0,1,2,3,4,5] >>> second = [4,5,6,7,9] >>> sorted(set(first + second)) [0, 1, 2, 3, 4, 5, 6, 7, 9] If the original order matters: >>> first = [0,1,2,3,4,5] >>> seen = set(first) >>> first += [x for x in second if x not in seen and not seen.add(x)] >>> first [0, 1, 2, 3, 4, 5, 6, 7, 9] For large lists the set approach is going to be efficient as sets provide O(1) lookup, for tiny lists your approach is also okay.

Categories : Python

Insert list of attributes into list of objects in python
I'd do something like this: for i, o in enumerate(objs): o.attr = i enumerate(objs) is sort of like zip(range(len(objs)), objs), so in case you actually want to take values from another sequence, you can: for i, o in zip(sequence, objs): o.attr = i For efficiency you might use itertools.izip there too.

Categories : Python

Python List help: TypeError: cannot concatenate 'str' and 'list' objects
You changed jkjk to a list here: jkjk = os.listdir("/Users/"+getpass.getuser()+"/Desktop/"+jkjk) And then you're trying to concatenate it to a string: os.listdir("/Users/"+getpass.getuser()+"/Desktop/"+jkjk+execfilepy): If you want the original jkjk then assign the list to some new variable: jkjk = jkjk+"/Files/Executable" lis = os.listdir("/Users/"+getpass.getuser()+"/Desktop/"+jkjk) for exfilepy in lis: #your code

Categories : Python

Modifying one object in list modifies all objects in list
def touchingBlocks(sourceBlock): touching = [] for t in range(6): touching.append(sourceBlock) # Here is your error touching[0].x += 1 touching[1].x -= 1 touching[2].y += 1 touching[3].y -= 1 touching[4].z += 1 touching[5].z -= 1 return touching You are adding the same object 6 times. Everytime you edit one object, you edit them all. You should create copies of your obect using copy.depcopy (deepcopy will copy the nested objects as well, not just their reference) import copy [...code...] touching.append(copy.deepcopy(sourceBlock))

Categories : Python

Conversion of list of nullables to list of objects
Nullable<T> is a value type, and generic covariance doesn't apply for value types (so there's no conversion from IEnumerable<int> to IEnumerable<object> either, for example): Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type. The simplest fix would be to use Cast: IEnumerable<object> bind2 = list2.Cast<object>();

Categories : C#

Is there a way to find objects in a list without iterating through the list?
You can use in to check for membership (literally, if something is in a container). This works for lists, strings, and other iterables. >>> li = ['a','b','c'] >>> 'a' in li True >>> 'x' in li False

Categories : Python

List of data.frames to list of xts objects
I'm not sure what's wrong with your dlply call, but you should use xts instead of as.xts. ur <- split(LAUPS55030003, LAUPS55030003$series_id) xl <- lapply(ur, function(x) xts(x$value, x$date)) # and if you want each series in a column: xc <- do.call(merge, xl)

Categories : R

How to get a List of Maps from a List of Objects in Scala
you can use the map function to transform a list of MyObject to a list of Map by: val list = List( MyObject(id, name, status), ..., MyObject(id, name, status) ) val result = list map {o => Map("key" -> o.id)} scala school from twitter is a good reading for beginners, and if you want to know the architecture of the Scala collections framework in detail, please refer to scala doc

Categories : Scala

adding item to a list then have list appear in a Combobox
EDIT: I am going to assume this question is mis-tagged as WPF and is really about winforms in which case my answer doesn't make sense profselect.ItemsSource = datalist; (not DataSource) and indeed it probably should be outside the loop

Categories : C#

Adding to List on For Loop (What do I set the List to initially?)
You can use map with operator.add: >>> from operator import add >>> map(add,*dict1.values()) [3, 5, 7] >>> map(add,*dict2.values()) [4, 6, 8, 10] or zip with a list comprehension if you don't want to import anything: >>> [sum(x) for x in zip(*dict1.values())] [3, 5, 7] >>> [sum(x) for x in zip(*dict2.values())] [4, 6, 8, 10] Update: def func(dic, *keys): return [sum(x) for x in zip(*(dic[k] for k in keys))] >>> dict1 = {'a': [0,1,2], 'b': [3,4,5], 'c':[6,7,8]} >>> func(dict1,'a') [0, 1, 2] >>> func(dict1,'a','b') [3, 5, 7] >>> func(dict1,'b','c') [9, 11, 13] >>> func(dict1,'b','c','a') [9, 12, 15]

Categories : Python

How can i get the Radio buttons to reflect what is in the database when i select rows in my DataGridView
compare the value retrieved from database and based on whether its Yes or No set the Checked property of the radio button. //dbValue: Database field value bound to radio button radioButton1.Checked = dbValue.Equals("Yes", StringComparison.OrdinalIgnoreCase) ? true : false;

Categories : C#

Unable to add objects and list together into a list of objects
Looking at last line of your test class: ArrayList<Book> lb = (ArrayList<Book>) responseList.getList().get(1); If you evalulate responseList.getList().get(1); I think you will find this returns an instance of Book. You are trying to cast this to an ArrayList. If you look at your addObjects method: Book book1 = new Book(); book1.setName("Book2"); book1.setAuthor("Author2"); Book book2 = new Book(); book2.setName("Book3"); book2.setAuthor("Author3"); ArrayList<Book> Blist = new ArrayList<Book>(); Blist.add(book1); Blist.add(book2); ArrayList<Object> list = new ArrayList<Object>(); list.add(bookstore); list.addAll(Blist); You add all items of "Blist" to the ArrayList after adding the bookstore, so the second element of this ArrayList is a Boo

Categories : Java

Create a list from a list of objects
No matter if there is any other way or not, but eventually it will be done via iteration only. Further, I don't think there is any direct API that can help you in achieving that. So, whatever you are doing is the best way of doing this. And one more thing, you can do it while populating Employee VOs. At that time you can either create a Map or a separate List for employee ids. But again, it will be just an optimization.

Categories : Java

WPF ComboBox Bound List set on DropDownOpened Event
The following change (suggested by Abe Heidebrecht) fixed the problem, but I don't know why. Anyone willing to lend an explanation? WPF: <ComboBox DropDownOpened="deviceSelector_DropDownOpened" Name="deviceSelector"/> C# code-behind: private void deviceSelector_DropDownOpened(object sender, EventArgs e) { var dev = new List<String>(); dev.Add("Device 1"); dev.Add("Device 2"); deviceSelector.ItemsSource = dev; }

Categories : C#



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