Creating an item(Under the key) is easy,but how to add subitems(Value)?
listView1.Columns.Add("Key");
listView1.Columns.Add("Value");
listView1.Items.Add("sdasdasdasd");
//How to add "asdasdasd" under value?
You whack the subitems into an array and add the array as a list item.
The order in which you add values to the array dictates the column they appear under so think of your sub item headings as [0],[1],[2] etc.
Here's a code sample:
//In this example an array of three items is added to a three column listview
string[] saLvwItem = new string[3];
foreach (string wholeitem in listofitems)
{
saLvwItem[0] = "Status Message";
saLvwItem[1] = wholeitem;
saLvwItem[2] = DateTime.Now.ToString("dddd dd/MM/yyyy - HH:mm:ss");
ListViewItem lvi = new ListViewItem(saLvwItem);
lvwMyListView.Items.Add(lvi);
}
Like this:
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add("SubItem");
listView1.Items.Add(lvi);
Suppose you have a List Collection containing many items to show in a ListView, take the following example that iterates through the List Collection:
foreach (Inspection inspection in anInspector.getInspections())
{
ListViewItem item = new ListViewItem();
item.Text=anInspector.getInspectorName().ToString();
item.SubItems.Add(inspection.getInspectionDate().ToShortDateString());
item.SubItems.Add(inspection.getHouse().getAddress().ToString());
item.SubItems.Add(inspection.getHouse().getValue().ToString("C"));
listView1.Items.Add(item);
}
That code produces the following output in the ListView (of course depending how many items you have in the List Collection):
Basically the first column is a listviewitem containing many subitems (other columns). It may seem strange but listview is very flexible, you could even build a windows-like file explorer with it!
I've refined this using an extension method on the ListViewItemsCollection. In my opinion it makes the calling code more concise and also promotes more general reuse.
internal static class ListViewItemCollectionExtender
{
internal static void AddWithTextAndSubItems(
this ListView.ListViewItemCollection col,
string text, params string[] subItems)
{
var item = new ListViewItem(text);
foreach (var subItem in subItems)
{
item.SubItems.Add(subItem);
}
col.Add(item);
}
}
Calling the AddWithTextAndSubItems looks like this:
// can have many sub items as it's string array
myListViewControl.Items.AddWithTextAndSubItems("Text", "Sub Item 1", "Sub Item 2");
Hope this helps!
I think the quickest/neatest way to do this:
For each class have string[] obj.ToListViewItem() method and then do this:
foreach(var item in personList)
{
listView1.Items.Add(new ListViewItem(item.ToListViewItem()));
}
Here is an example definition
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public DateTime DOB { get; set; }
public uint ID { get; set; }
public string[] ToListViewItem()
{
return new string[] {
ID.ToString("000000"),
Name,
Address,
DOB.ToShortDateString()
};
}
}
As an added bonus you can have a static method that returns ColumnHeader[] list for setting up the listview columns with
listView1.Columns.AddRange(Person.ListViewHeaders());
Create a listview item
ListViewItem item1 = new ListViewItem("sdasdasdasd", 0)
item1.SubItems.Add("asdasdasd")
ListViewItem item = new ListViewItem();
item.Text = "fdfdfd";
item.SubItems.Add ("melp");
listView.Items.Add(item);
add:
.SubItems.Add("asdasdasd");
to the last line of your code so it will look like this in the end.
listView1.Items.Add("sdasdasdasd").SubItems.Add("asdasdasd");
Generally:
ListViewItem item = new ListViewItem("Column1Text")
{ Tag = optionalRefToSourceObject };
item.SubItems.Add("Column2Text");
item.SubItems.Add("Column3Text");
myListView.Items.Add(item);
Great !! It has helped me a lot. I used to do the same using VB6 but now it is completely different.
we should add this
listView1.View = System.Windows.Forms.View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
Related
Is it possible to sum up all of the item's price inside a ListBox? I have this ListBox that displays items from a DataGridView, and each of their prices are in priceTextBox Please refer from the picture below.
What I want to do is to display the sum of all the item's price and display it at the totalTextBox.
I have already done this code but I think this won't work.
private void menuListBox_SelectedValueChanged(object sender, EventArgs e)
{
int x = 0;
string Str;
foreach (DataGridViewRow row in menuDataGrid.Rows) //this part displays the price of each item to a textbox so this is good.
{
if (row.Cells[3].Value.ToString().Equals(menuListBox.SelectedItem.ToString()))
{
pricetxtbox.Text = row.Cells[5].Value.ToString();
break;
}
}
foreach (string Str in row.Cells[5].Value.ToString().Equals(menuListBox.SelectedItem.ToString())) //now this is the part where I want to happen the adding the prices of all items in the listbox. this also gives me an error at row saying it doesn't exist in the context
{
x = x + Convert.ToInt32(Str);
totaltxtbox.Text = x;
}
}
Will appreciate any help! Thanks!
Try this out...
Func<string, DataGridViewRow> getRow = (menuCode) =>
{
return menuDataGrid.Rows.Cast<DataGridViewRow>()
.First(r => ((string)r.Cells[3].Value).Equals(menuCode));
};
var selected = menuListBox.SelectedItem.ToString();
pricetxtbox.Text = getRow(selected).Cells[5].Value.ToString();
totaltxtbox.Text = menuListBox.Items.Cast<object>()
.Select(o => o.ToString())
.Select(i => (int)getRow(i).Cells[5].Value)
.Sum()
.ToString();
I think you should change your approach, by separating completely data and display.
To do that, you could create a class which will contain data for each row of your DataGrid :
public class MyItem
{
public string Caption { get; set; }
public int Price { get; set; }
}
And then in your codebehind, you store a list of these items :
private List<MyItem> AllItems = new List<MyItem>();
Finally, you set this collection as the source of your DataGrid :
menuDataGrid.DataSource = AllItems;
Then, all your data is stored in a collection you own, and to sum prices it's much simpler :
using System.Linq;
private int ComputeSum()
{
return (AllItems.Sum(item => item.Price));
}
The next step is to use Binding and a BindingList, wich allows the DataGrid to refresh automatically when new items are added in "AllItems": see this well explained post.
In my project I need to create several lisview dinamically, I have a array with some value string[] = array{"BILL", "ORDER", "DELEVERY FORM", "RCL", "ESTIMATION", ...}; And I would like create a listview to each value from array.
void CreateListView(string[] array)
{
foreach(value in array)
{
ListView listView[value] = new ListView();
this.Controls.Add(listView[value]);
}
}
From my understanding you want to create the listviews and name them according to the given array. If that is the case, then this should satisfy.
void CreateListView(string[] array)
{
foreach (var value in array)
{
ListView listView = new ListView {Name = value};
Controls.Add(listView);
}
}
The below code has a list and loops through each string item in that list and adds it to a ComboBox. This functions correctly, but I am curious if there is a possible way to pass a string list and ComboBox into a function and return the ComboBox with each item in the string list being added.
Example: gets a string list, then adds each string item to the list. This is great if there's one ComboBox; but if there are 3 or more, to avoid code repetition, passing in a list and ComboBox would save code.
List<string> myList = getList();
foreach (string listItem in myList)
{
myComboBox.Items.Add(listItem);
}
you can make method like
private void FillCombo(ComboBox myComboBox, List<string> list);
{
foreach (string listItem in myList)
{
myComboBox.Items.Add(listItem);
}
//alternatively, you can add it like fubo suggested in comment
//myComboBox.Items.AddRange(myList.ToArray());
}
and call it from somewhere in code
List<string> myList = getList();
FillCombo(this.comboBox1, myList);
FillCombo(this.comboBox2, myList);
// etc...
When running my code i put several string on different lines of the textbox but it breaks saying there is a Null Exception Error on "Items.Add(item)" I am not sure why I am getting
this error because in visual studio the string in the variable item is not null it contains
a return character through so I am not sure if that is an issue.. for example item = "uno\r". Also, Items is a list of strings. Does anyone know why I keep getting this Null Exception?
public List<string> Items;
public void getItemsFromTextBox(TextBox textbox)
{
string[] lines = textbox.Text.Split('\n');
foreach (string item in lines)
{
if (!String.IsNullOrWhiteSpace(item))
Items.Add(item);
}
}
You have not initialized your list, it's null! Add
public List<String> Items = new List<String>();
You must create instance of Items list:
public void getItemsFromTextBox(TextBox textbox)
{
Items = new List<string>();
string[] lines = textbox.Text.Split('\n');
foreach (string item in lines)
{
if (!String.IsNullOrWhiteSpace(item))
Items.Add(item);
}
}
Just try with following code.I guess your Items list is global one and shared list .so better to check that List is initialize or if not then initialize first and do the rest of the thing.
public List<string> Items;
public void getItemsFromTextBox(TextBox textbox)
{
if(null == Items)
{
Items = new List<string>();
}
foreach (string item in textbox.Text.Split('\n'))
{
if (!String.IsNullOrWhiteSpace(item))
Items.Add(item);
}
}
You must have create an instance of List Items.
use
public List<String> Items = new List<String>();
or use the below code
public void getItemsFromTextBox(TextBox textbox)
{
List<string> Items = !string.IsNullOrWhiteSpace(textbox.Text) ? textbox.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList() : new List<string>();
}
Make sure that you have instantiated "Items".
Hi i'm trying to use the tag item of a listbox.
heres my code.
int number = 0;
foreach (ListViewItem item in listBox1.Items)
{
Tag tag = (Tag) item.Tag;
saveSlide(showid, tag.photoid, enumber);
number++;
}
problem im havin is when i run the program i get an error message sayin cannot convert type string to system.ListView but i haven't declared item as a string anywher in my program
This is where i add the items to the listbox. Please help. Im on a dead line and have sooo much more to do
private void buttonAdd_Click(object sender, EventArgs e)
{
//add selected item into listBox
DataRowView drv = (DataRowView)listBox1.SelectedItem;
Tag tag = new Tag();
string title = drv["title"].ToString();
ListViewItem item = new ListViewItem(title);
item.Tag = tag;
tag.photoid = (int)drv["photoid"];
listBox1.Items.Add(title);
}
Poppy you are adding title to listBox1.Items.
title is of type string.
So when you access it use string type like this foreach (string item in listBox1.Items).
Try. Does it help?
int number = 0;
foreach (string item in listBox1.Items)
{
Tag tag = (Tag) item.Tag;
saveSlide(showid, tag.photoid, enumber);
number++;
}
This works, you need to show the code where you add items to the list:
private class Tag
{
public override string ToString()
{
return "Tag";
}
}
ListBox listBox = new ListBox();
listBox.Items.Add(new ListViewItem { Tag = new Tag() });
foreach (ListViewItem item in listBox.Items)
{
Tag tag = (Tag)item.Tag;
Console.WriteLine(tag);
}
Edit following more code:
You are adding strings to your ListBox instead of the ListViewItem:
listBox1.Items.Add(title); should be listBox1.Items.Add(item);
ListBox.Items is an ObjectCollection. That means you can choose the kind of object to put in it.
When you're doing this:
string title = drv["title"].ToString();
listBox1.Items.Add(title);
you are putting string objects into it, so you would need to get them out like this:
foreach (string item in listBox1.Items)
Instead, you probably want your code to be more like this:
ListViewItem item = new ListViewItem(title);
item.Tag = tag;
tag.photoid = (int)drv["photoid"];
listBox1.Items.Add(item); // The difference is here - add *item* not *title*
then you'll be able to use this the way you initially wrote it:
foreach (ListViewItem item in listBox1.Items)
Does Tag has a member named photoid? Maybe you need a cast in there to convert your 'tag' to whatever it's supposed to be?
//Tag tag = (Tag) item.Tag;
MyObject tag = (MyObject)item.Tag;
saveSlide(showid, tag.photoid, enumber);
number++;
Unless you named things weird I'd say the error is that you're trying to get a ListViewItem from a ListBox.
Just change the last line of code of the second code-snippet and everything will be ok, which is as follows.
listBox1.Items.Add(item);
About the Error
You added strings to the listBox as items and in the foreach an item(which is a string) is tried to convert(caste) to ListViewItem implicitly to hich doesn't work and the compiler gives the error.
Hope it will work.