Listview filling issue - c#

I need to know what are the things going on here.Actually my aim is to add a column additionally and display the contents.I Added column but i want to know
the codeflow required to finish to display items in that column
ManagedDeviceCollection list = new ManagedDeviceCollection();
try
{
if(SpoServer == null)
return;
_listSelected.BeginUpdate();
_listAvailable.BeginUpdate();
#region populate the selected list
// Collect selected items.
object[] selected = new object[_listSelected.SelectedItems.Count];
_listSelected.SelectedItems.CopyTo(selected, 0);
// Clear listview.
_listSelected.Items.Clear();
// Add systems.
ResourcePolicySystemsLVI item;
foreach(ManagedDevice md in PolicySystemsList)
{
item = new ResourcePolicySystemsLVI(md);
item.Update();
foreach(object obj in selected)
{
item.Selected = (((ResourcePolicySystemsLVI)obj).Data == item.Data);
break;
}
_listSelected.Items.Add(item);
}
// Sort list.
_listSelected.Sort();
// Ensure selected items are visible.
if(_listSelected.SelectedItems.Count > 0)
{
_listSelected.SelectedItems[_listSelected.SelectedItems.Count
- 1].EnsureVisible();
_listSelected.SelectedItems[0].EnsureVisible();
}
#endregion
#region populate the available list
// Collect selected items.
selected = new object[_listAvailable.SelectedItems.Count];
_listAvailable.SelectedItems.CopyTo(selected, 0);
// Clear listview.
_listAvailable.Items.Clear();
// Add systems.
ResourcePolicyAvailSystemsLVI item2;
foreach(ManagedDevice md in AvailableSystemsList)
{
item2 = new ResourcePolicyAvailSystemsLVI(md);
item2.Update();
foreach(object obj in selected)
{
item2.Selected = (((ResourcePolicyAvailSystemsLVI)obj).Data
== item2.Data);
break;
}
_listAvailable.Items.Add(item2);
}
// Sort list.
_listAvailable.Sort();
// Ensure selected items are visible.
if(_listAvailable.SelectedItems.Count > 0)
{
_listAvailable.SelectedItems[_listAvailable.SelectedItems.Count
- 1].EnsureVisible();
_listAvailable.SelectedItems[0].EnsureVisible();
}
#endregion
_listSelected.EndUpdate();
_listAvailable.EndUpdate();

To display text in columns after the first, use the ListViewItem.SubItems collection. For example, you might modify your main loop as follows:
item2 = new ResourcePolicyAvailSystemsLVI(md);
// skipped some of your code
item2.SubItems.Add("My second piece of info"); // this is what puts data into the second column
I wasn't sure from your question whether you had already added the requisite column to the ListView: if not, you must do so using ListView.Columns.Add in order to display the subitem.

Related

Listview group works wierdly

In my app, I display a listview with a few entries. I can group them by groups and it works well.
When I do the same in Excel/MatLab via the API I created (based on the same code) the groups doesn't work, see pictures:
In the application:
And in the API:
As you can see, it doesn't work. Here's the code I use:
// Sets the ListView to the groups created for the specified column.
private void SetGroups(Hashtable groups,int column)
{
// Remove the current groups.
listView1.Groups.Clear();
// Copy the groups for the column to an array.
ListViewGroup[] groupsArray = new ListViewGroup[groups.Count];
groups.Values.CopyTo(groupsArray, 0);
// Sort the groups and add them to the ListView.
Array.Sort(groupsArray, new ListViewGroupSorter(listView1.Sorting));
listView1.Groups.AddRange(groupsArray);
// Iterate through the items in the ListView, assigning each
// one to the appropriate group.
foreach (ListViewItem item in listView1.Items)
{
// Retrieve the subitem text corresponding to the column.
string subItemText = item.SubItems[column].Text;
// For the Title column, use only the first 3 letters.
if (column == 0)
{
subItemText = subItemText.Substring(0,3);
}
// Assign the item to the matching group.
item.Group = (ListViewGroup) groups[subItemText];
}
}
How can I fix this?
Put Application.EnableVisualStyles(); in constructor of form:
public Form1()
{
InitializeComponent();
Application.EnableVisualStyles();
}

The best overloaded method match for 'ColConfigSubsystem.Database.GetChromeMakeByYear(int)' has some invalid arguments

I have an event in C# that populates dropdown lists from a class file (database.cs) with the associated values from a different database via oracle stored procedures contained in the class file mentioned above. This is the code that I am currently using:
///<summary>
///Populates the model dropdownlist with available chrome data associated with
///the year selected
/// </summary>
private void PopulateChromeModel()
{
//define a counter
int itemCounter = 1;
//create a database object
Database cmake = new Database();
//call GetChromeMakeByYear to retrieve the available models according to
//the year
DataTable table = cmake.GetChromeMakeByYear(ddlVehicleYear.SelectedItem);
Trace.Write("populating models");
//create a flag showing whether an item should be selected. Preset it to false
bool selected = false;
//we may need to select, then later deselect, an item based on the model.
int selectedItemByModel = 0;
//preset the current selected code to ""
string currentSelectedCode = "";
//define a flag to indicate whether we've already selected an item. Preset it to false.
bool hasSelected = false;
//create a list item for the 0 position
ListItem firstItem = new ListItem("-- SELECT --", "");
//first see if there is a currently selected item. If so, set the current selected model.
//this is done because we have to clear all of the selected items before adding the new list.
//but we want to be able to select the model that is already selected.
if (ddlVehicleModel.SelectedIndex > 0)
{
currentSelectedCode = ddlVehicleModel.SelectedValue;
}
//clear any items from the list
ddlVehicleModel.Items.Clear();
//add the first item
ddlVehicleModel.Items.Add(firstItem);
//loop through the table and add items for each row.
foreach (DataRow row in table.Rows)
{
//get this record's chrome id
string id = row["CHROME_ID"].ToString();
//get this record's make
string make = row["CHROME_MAKE"].ToString();
//set a flag specifying whether the item should be selected based on year
bool selectBasedOnYear = false;
if (currentSelectedCode == id)
{
selected = true;
}
else
{
selected = false;
selectBasedOnYear = false;
}
Trace.Write(string.Format("{0}: {1}: {2}: {3}", id, make, selected, selectBasedOnYear));
//create a new list item for this model
ListItem newItem = new ListItem(id, make);
//if we have thrown either selected flag and we have not already selected an item,
//mark this option as selected
if ((selected || selectBasedOnYear) && !hasSelected)
{
Trace.Write("-- Either selected or selectedBasedOnYear was true, and hasSelected was false");
//first make sure the first item is deselected
firstItem.Selected = false;
Trace.Write("-- deselected the first item.");
//next deselect and items that were selected due to year. This allows the user selected
//region to override the default model for year.
if (selectBasedOnYear != null)
{
Trace.Write(string.Format(" -- deselecting item {0}, which was selected due to year", selectBasedOnYear));
ddlVehicleMake.Items[selectedItemByModel].Selected = false;
}
//select this item
newItem.Selected = true;
Trace.Write(" -- selected the current item");
//only throw the hasSelected flag if this was a user-selected region
if (selected)
{
hasSelected = true;
Trace.Write(" -- set hasSelected to true");
}
}
//add the model to the list
ddlVehicleMake.Items.Add(newItem);
itemCounter++;
}
//if there's no items selected and we have more than just the default item,
//default to the first item
if (ddlVehicleMake.Items.Count > 0 && !hasSelected && selectedItemByModel == 0)
{
ddlVehicleMake.SelectedIndex = 1;
}
}
The error is being thrown at the following line:
//call GetChromeMakeByYear to retrieve the available models according to
//the year
DataTable table = cmake.GetChromeMakeByYear(ddlVehicleYear.SelectedItem);
I have included my inline comments and summary to help with the scope of this event. I am not quite sure what the reason is for the error.
You need to unbox the value to an integer.
DataTable table = cmake.GetChromeMakeByYear((int)ddlVehicleYear.SelectedItem);
When items are retrieved from a dropdown list they are retrieved in the form of objects, because you can store any type of data in them. The compiler doesn't know that the item you are specifying in the list is in fact an integer (and not say a string) and so doesn't know what function you are trying to call.
More about unboxing and boxing here: http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
Try This:
DataTable table = cmake.GetChromeMakeByYear((int) ddlVehicleYear.SelectedValue);

moving one value form list to another delete next value from list

I have two listboxes when i swap value to another listbox it always remove next value from the list and when i try to swap last value from the list it take top one value form the list . I try to find the problem but i don't get any result. Below is the code part for review.
private void MoveListBoxItems(ListBox lstEmployeelist, ListBox lstSelectedEmployees)
{
ListBox.SelectedObjectCollection sourceItems = lstEmployeelist.SelectedItems;
List<Master> newsource = this.masterBindingSource.DataSource as List<Master>;
List<Master> _selectedSource = this.masterSellectedBindingSource.DataSource as List<Master>;
try
{
if (lstEmployeelist.Items.Count > 0)
{
for (int i = 0; i <= sourceItems.Count -1 ; i++)
{
Master item = sourceItems[i] as Master;
this.masterSellectedBindingSource.AddNew();
Master sitems = masterSellectedBindingSource.Current as Master;
sitems.Empno = item.Empno;
sitems.FirstName = item.FirstName;
newsource.Remove((Master)item);
}
if (sourceItems.Count > 0)
this.masterBindingSource.RemoveCurrent();
this.masterSellectedBindingSource.EndEdit();
lstSelectedEmployees.DataSource = masterSellectedBindingSource;
lstSelectedEmployees.DisplayMember = "FirstName";
lstSelectedEmployees.ValueMember = "Empno";
}
}
catch (Exception ex)
{
throw ex;
}
}
I believe the problem is with the way you iterate through sourceItems.
Because you are doing it using a for loop (presumably because you cannot do it with a foreach because you cant then modify the collection), when you remove say item 1 from the collection and add it to the 2nd list, item 2 and all items after move up 1.
So item 2 becomes the new item 1 and item 3 becomes item 2, etc, etc...
To fix this, when you decide to move an item you also need to decrease i by 1 (i--;) so that when the for loops round again and i is increased it is back to the same index.
IF you are moving ALL items and not only select items, then you should not use a for loop, use a while instead like this:
while (sourceItems.Count > 0)
{
// code here
}

ListPicker not calling SummaryForSelectedItemsDelegate when dismissed

I am using a multi-selection ListPicker (the new one in the 7.1/Mango control toolkit from Nov '11).
My code is below - a "vanilla" use case for the ListPicker, except that I initialize the SelecetedItems dependency property with a new List so I can add things to it and properly initialize the selected state for the ListPicker. Although this issue repro's whether or not I do this...
The SummaryForSelectedItemsDelegate does get called when initializing the list (e.g. when I call contactPicker.SetValue(ListPicker.SelectedItemsProperty)), but NOT when I click the "done" button on the ListPicker (although my SelectionChanged event handler does get called).
Once I dismiss the ListPicker, I only get the string corresponding to the first selected item in the "summary" for the control (as opposed to the control calling my delegate and getting a comma-delimited list of selected items).
Is this a bug? Has anyone else run into this? Is there a workaround?
var contactPicker = new ListPicker()
{
MinWidth = minWidth,
ExpansionMode = ExpansionMode.FullScreenOnly,
SelectionMode = SelectionMode.Multiple,
SummaryForSelectedItemsDelegate = (list) => { return CreateCommaDelimitedList(list); },
IsTabStop = true
};
contactPicker.ItemsSource = listOfItems;
contactPicker.DisplayMemberPath = "Name";
contactPicker.SetValue(ListPicker.SelectedItemsProperty, new List<Item>());
// initialize the list picker selected values
foreach (var contactRef in listOfSelectedContacts)
contactPicker.SelectedItems.Add(contactRef);
contactPicker.SelectionChanged += new SelectionChangedEventHandler((o, ea) =>
{
// add all the newly added items
foreach (var added in ea.AddedItems)
{
Item addedItem = added as Item;
if (addedItem == null)
continue;
listOfSelectedContacts.Items.Add(addedItem);
}
// remove all the newly removed items
foreach (var removed in ea.RemovedItems)
{
Item removedItem = removed as Item;
if (removedItem == null)
continue;
listOfSelectedContacts.Items.Remove(removedItem);
}
});
I should have posted my my summary delegate... which is actually where my bug was :-(
Even though I was creating the SelectedItems as a List, and each of the elements in the IList passed in are typed "Item", the concrete type of the IList passed in is NOT List. Therefore the null check succeeds and the method returns null. And of course my breakpoint was right after that line so it looked like the method wasn't getting invoked. Duh.
private string CreateCommaDelimitedList(IList ilist)
{
IList<Item> list = ilist as IList<Item>;
if (list == null)
return null;
// build a comma-delimited list of names to display in a control
List<string> names = list.Select(it => it.Name).ToList();
StringBuilder sb = new StringBuilder();
bool comma = false;
foreach (var name in names)
{
if (comma)
sb.Append(", ");
else
comma = true;
sb.Append(name);
}
return sb.ToString();
}

Select the specific column of ListView and print it in a new messagebox in C#.net

I've just started to use ListView in C#.net.
I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.
I want to know how to do this.
I found this code to list a specific selected data from a row:
ListView.SelectedIndexCollection sel = listView1.SelectedIndices;
if (sel.Count == 1)
{
ListViewItem selItem = listView1.Items[sel[0]];
MessageBox.Show(selItem.SubItems[2].Text);
}
That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?
private string[] GetListViewItemColumns(ListViewItem item) {
var columns = new string[item.SubItems.Count];
for (int column = 0; column < columns.Length; column++) {
columns[column] = item.SubItems[column].Text;
}
return columns;
}
I would recommend some caution against doing this. A ListView is really meant to display information, it is not a great collection class. Getting the data out of it is slow and crummy, it can only store strings. Keep the data in your program in its original form, maybe a List<Foo>. Now it is simple and fast.
foreach (ListViewItem item in listView1.Items) {
// Do something with item
}
you could do this by
foreach(ListViewItem item in listView1.Items)
{
foreach(var subtem in item.SubItems)
{
// Do what ever you want to do with the items.
}
}

Categories

Resources