how to get data from a listview?

how to get data from a listview?

Page 1 of 1

14 Replies - 77597 Views - Last Post: 19 June 2011 - 06:38 AM Rate Topic: -----

#1 Extas  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-April 08

how to get data from a listview?

Posted 15 April 2008 - 10:17 AM

hello,
i've only been programming for a few weeks now and this is also my first time posting on this forum so i will try and get everything formatted correctly with the code and what not.

first of all im using visual studio 2008, programing in c#, and making a wpf application.

what im trying to make is a program that i can use for balancing my checkbook. to give an idea of how it works, it has two radio buttons, one for writing checks and one for making deposits. then it has 5 text boxes that you input the date, amount, who its to, exct. after you click the add button it adds that data plus the balance to a listview. (this part of my program works correctly)

this is the code that i have used to do this.
(i found this way of adding things to a listview on the internet and it was the only way i was able to do it, if this is the main source of my problem please let me know. i thoutht an array would be better but i havent figured out how to add an array correctly.)

<ListView Margin="17,84,14,89" Name="ledgerView">
			<ListView.View>
				<GridView>
					<GridViewColumn Header="Date" DisplayMemberBinding="{Binding LedgerDate}" Width="120"/>
					<GridViewColumn Header="Check Number" DisplayMemberBinding="{Binding LedgerCheckNumber}" Width="132"/>
					<GridViewColumn Header="Transaction Type" DisplayMemberBinding="{Binding LedgerTransactionType}" Width="120"/>
					<GridViewColumn Header="Description" DisplayMemberBinding="{Binding LedgerDescription}" Width="280"/>
					<GridViewColumn Header="Amount" DisplayMemberBinding="{Binding LedgerAmount}" Width="120"/>
					<GridViewColumn Header="Balance" DisplayMemberBinding="{Binding LedgerBalance}" Width="120"/>
				</GridView>
			</ListView.View>
		</ListView>


that is the xaml code for the listview and here is the actual code that takes place when you click the add transaction button.

public void AddTransaction()
		{
			try
			{
				string date = dateBox.Text;
				string checkNumber = checkNoBox.Text;
				string description = descriptionBox.Text;
				double amount = double.Parse(amountBox.Text);
				string transactionType;
				double currentBalance = double.Parse(balanceBox.Text);

				if (writingRadio.IsChecked.HasValue && writingRadio.IsChecked.Value)
				{
					transactionType = "Withdrawal";
					amount = 0 - amount;

				}
				else
				{
					transactionType = "Deposit";
					amount = 0 + amount;
				}

				double newBalance = currentBalance + amount;
				balanceBox.Text = newBalance.ToString("0,0.00");

				ledgerView.Items.Add(new Transaction()
				{
					LedgerDate = date,
					LedgerCheckNumber = checkNumber,
					LedgerTransactionType = transactionType,
					LedgerDescription = description,
					LedgerAmount = amount.ToString("0,0.00"),
					LedgerBalance = newBalance.ToString("0,0.00")
				});

				ClearInput();
			}
			catch (FormatException)
			{
				MessageBox.Show("Amount value must be numbers only " + amountBox.Text + " will not work");
			}
			
		}



here is the Transaction class that is used.

public class Transaction
		{
			public string LedgerDate { get; set; }
			public string LedgerCheckNumber { get; set; }
			public string LedgerTransactionType { get; set; }
			public string LedgerDescription { get; set; }
			public string LedgerAmount { get; set; }
			public string LedgerBalance { get; set; }


*edit: It is a forward slash to end the code tags, not a backslash. Thanks for using them. :code:


now as i said all that works fine it adds all the correct information to the listview.

the problem comes when i want to delete a transaction. i use this code to perform the actual removal of the entire row from the listview.

ledgerView.Items.RemoveAt(0);

that also works fine but the problem i need help with is that before using that code, i need to some how get the value of the amount that is being deleted and use that to recalculate the balance. i havent been able to find any way of doing that and i have tried figuring it out on my own to no avail.

thanks in advance for any help you can give me. sorry the post is so long and if my code is sloppy.

This post has been edited by Martyr2: 15 April 2008 - 11:02 AM


Is This A Good Question/Topic? 0
  • +

Replies To: how to get data from a listview?

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4307
  • View blog
  • Posts: 12,088
  • Joined: 18-April 07

Re: how to get data from a listview?

Posted 15 April 2008 - 11:11 AM

Well you just need to get a reference to the ListViewItem and then you will see it has a subcollection called "Subitems". So if we ant the third item of the first ListViewItem we can go...

ListView1.Items[0].SubItems[2].Text



This is saying get the first ListViewItem from the ListView1 control, then access its third SubItem (remember indexes start at 0, so the third item is 2), and lastly return its Text value.

Now doing this will return the text of the third subitem of listviewitem 1, so be sure to convert it to a double value (since it is money) and subtract that.

Hopefully this makes sense and works for you.

"At DIC we be listview subitem hunting code ninjas!" :snap:
Was This Post Helpful? 0
  • +
  • -

#3 Extas  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-April 08

Re: how to get data from a listview?

Posted 15 April 2008 - 11:35 AM

first of all thanks for your response, but i still cant get it to work.

(the name of my listview item is ledgerView)

when i type in
ledgerView.Items[0].


intellisense only offers me 4 methods
Equals,GetHashCode, GeType, and ToString.

is their something i am supposed to do before i can use this code, i noticed you said something about creating a reference to the item but im not sure how to do this (it sounds familiar but my mind is drawing blank).
i tried something like this but it didnt work
ListViewItem amountDel;
amountDel = new ListViewItem();
amountDel = ledgerView.Items[0].(same problem occured here)


This post has been edited by Extas: 15 April 2008 - 11:45 AM

Was This Post Helpful? 0
  • +
  • -

#4 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4307
  • View blog
  • Posts: 12,088
  • Joined: 18-April 07

Re: how to get data from a listview?

Posted 15 April 2008 - 12:30 PM

When you go...

ledgerView.Items[



Does intellisense show that you can put an index there and if so, what does it say the return type is in the yellow tooltip box? Does it say ListViewItem like the one pictured below?

Attached Image

You should see such a tooltip as soon as you type the opening square bracket.
Was This Post Helpful? 0
  • +
  • -

#5 Extas  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-April 08

Re: how to get data from a listview?

Posted 15 April 2008 - 12:39 PM

ledgerView.Items[

tooltip says

object ItemCollection [int index]
index:
the zero-based index of the item.

there is no up down arrow as yours has two different paramater sets mine is only showing this one.

maybe its cause of the way i added the row as a new Transaction(); look at my first post and you'll see what im talking about, if there is another way i should be adding text from the textboxes to the listview let me know i dont mind chaning it.

This post has been edited by Extas: 15 April 2008 - 12:40 PM

Was This Post Helpful? 0
  • +
  • -

#6 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4307
  • View blog
  • Posts: 12,088
  • Joined: 18-April 07

Re: how to get data from a listview?

Posted 15 April 2008 - 01:46 PM

Are you able to cast the object to a ListViewItem object?

ListViewItem item = Ctype(ledgerView.Items[0],ListViewItem);

or

ListViewItem item = (ListViewItem)ledgerView.Items[0];



There should be some way to get out a ListViewItem from that collection. In it will have the subitems you need.
Was This Post Helpful? 0
  • +
  • -

#7 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1638
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: how to get data from a listview?

Posted 15 April 2008 - 01:56 PM

You should be able to use the SelectedValue property of the WPF ListView control


System.Data.DataRowView value = (System.Data.DataRowView)ledgerView.SelectedValue;
MessageBox.Show(value.Row[0].ToString());


Was This Post Helpful? 0
  • +
  • -

#8 Extas  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-April 08

Re: how to get data from a listview?

Posted 15 April 2008 - 02:04 PM

View PostMartyr2, on 15 Apr, 2008 - 01:46 PM, said:

Are you able to cast the object to a ListViewItem object?

ListViewItem item = Ctype(ledgerView.Items[0],ListViewItem);

or

ListViewItem item = (ListViewItem)ledgerView.Items[0];



There should be some way to get out a ListViewItem from that collection. In it will have the subitems you need.


ListViewItem item = (ListViewItem)ledgerView.Items[0]; compiles correctly but if my delete buttons is this.

ListViewItem item = (ListViewItem)ledgerView.Items[0];
LedgerView.Items.RemoveAt(0);


causes the program to crash so the casting doesnt seem to be working propperly.

i think the source of the problem is because i used a class to attach the values to the databindings in the listview xaml.

if i populated my listview the same way you would then i think your suggested code would work to get the data from it. so let me ask you, how would add five variables to a new row in a listview box.





View PostPsychoCoder, on 15 Apr, 2008 - 01:56 PM, said:

You should be able to use the SelectedValue property of the WPF ListView control


System.Data.DataRowView value = (System.Data.DataRowView)ledgerView.SelectedValue;
MessageBox.Show(value.Row[0].ToString());



i tired this, the program compiled but it crashed, the dubbuger says
"InvalidCastException was unhandled"

Unable to cast object of type 'Transaction' to type 'System.Data.DataRowView'.

This post has been edited by Extas: 15 April 2008 - 02:19 PM

Was This Post Helpful? 0
  • +
  • -

#9 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4307
  • View blog
  • Posts: 12,088
  • Joined: 18-April 07

Re: how to get data from a listview?

Posted 15 April 2008 - 03:42 PM

Quote

Unable to cast object of type 'Transaction' to type 'System.Data.DataRowView'.


Ahhhh that is what I was looking for. Yes you are right it is the way you are storing the valuing into the Listview. So what you need to do is first create a ListviewItem object, one of its constructors should take an array of strings (String[]) or you could use any of its overloaded constructors you like. The goal here is to get the ListViewItem into the Listview, not your transaction object. Then you will be able to cast it back to ListViewItem (using the code I gave you) and thus get access to subitems. :)
Was This Post Helpful? 0
  • +
  • -

#10 Extas  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-April 08

Re: how to get data from a listview?

Posted 15 April 2008 - 05:14 PM

ok i am trying to do what you said but im not sure about one thing.

this is what i have so far
string[] newTransaction;

newTransaction = new string[6];

newTransaction[0] = date;
newTransaction[1] = checkNumber;
newTransaction[2] = transactionType;
newTransaction[3] = description;
newTransaction[4] = amount.ToString("0,0.00");
newTransaction[5] = newBalance.ToString("0,0.00");

ListViewItem item;
item = new ListViewItem();

//how do i get my string array into that item.
//i tried by using item = new ListViewItem(newTransaction[]);
//but it said that it didnt take 1 argument so im not sure what to put in this area to make the next line work.
				

ledgerView.Items.Add(item);

// i am guessing the above code would work if i knew how to get my strings data into that item.



thanks again for helping me with this!


edit*****************************************************************************************

after much frustration i started a new application only this time i used a windows form application instead of a WindowsPresentationForm and this is what i found

this worked fine in the WFA
string one = textBox1.Text;
			string two = textBox2.Text;
			string three = textBox3.Text;

			string[] newTrans;
			newTrans = new string[3];

			newTrans[0] = one;
			newTrans[1] = two;
			newTrans[2] = three;



			ListViewItem newItem = new ListViewItem(newTrans[0], 0);
			newItem.SubItems.Add(newTrans[1]);
			newItem.SubItems.Add(newTrans[2]);

			listView1.Items.AddRange(new ListViewItem[] { newItem });



however this same text copy and pasted and modified to match items and variables does not compile in my program (the WPF)
string[] newTransaction;
				newTransaction = new string[6];
				newTransaction[0] = date;
				newTransaction[1] = checkNumber;
				newTransaction[2] = transactionType;
				newTransaction[3] = description;
				newTransaction[4] = amount.ToString("0,0.00");
				newTransaction[5] = newBalance.ToString("0,0.00");

				//ListViewItem item;
				//item = new ListViewItem();

				ListViewItem newItem = new ListViewItem(newTransaction[0], 0);  //Error	1	'System.Windows.Controls.ListViewItem' does not contain a constructor that takes '2' arguments
				newItem.SubItems.Add(newTransaction[1]); // errors here also saying System.WIndows.Controls.ListviewItem does not contain a definition for sub items.
				newItem.SubItems.Add(newTransaction[2]);
				newItem.SubItems.Add(newTransaction[3]);
				newItem.SubItems.Add(newTransaction[4]);
				newItem.SubItems.Add(newTransaction[5]);

				ledgerView.Items.AddRange(new ListViewItem[] { newItem });  //Error you sorry peice of trash you cant use AddRange their is no definition for it!!!!



that being said i think the help you guys have been trying to give me is for a Windows Form Application.
I think im just gonna scrap my WPF app and start over with WFA, simply because i havent been able to find any information on ListView in WPF that i can use.

thanks for the help guys and i'll try your suggestions on my new program once i get back up to that point. i'm sure i'll be posting again in the future :)

This post has been edited by Extas: 15 April 2008 - 07:29 PM

Was This Post Helpful? 0
  • +
  • -

#11 Extas  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-April 08

Re: how to get data from a listview?

Posted 15 April 2008 - 10:49 PM

thank you both for helping me figure this out.

after seeing your suggestions i realized that something wasnt right, i decided to just make the app in WFA instead of WPF and now i can successfully add transactions, as well as delete transactions, and also update the listview appropriatly so that each transaction shows the correct balance after the deletion.

for anyone else that stumbles on this thread looking for answers here is the code i used.
(i know i could declare and assign my variables in one line i just dont :D)

setting up the listview
public Form1()
		{
			InitializeComponent();
			
			currentBalanceBox.Text = "0.00"; // if i dont set this to a value here its going to cause an error later when it tries to parse it for the first time and its blank
			
			ledgerView.View = View.Details;
			ledgerView.FullRowSelect = true;

			ledgerView.Columns.Add("Date", 120, HorizontalAlignment.Left);
			ledgerView.Columns.Add("Check Number", 180, HorizontalAlignment.Left);
			ledgerView.Columns.Add("Transaction Type", 120, HorizontalAlignment.Left);
			ledgerView.Columns.Add("Description", 312, HorizontalAlignment.Left);
			ledgerView.Columns.Add("Amount", 120, HorizontalAlignment.Left);
			ledgerView.Columns.Add("Balance", 120, HorizontalAlignment.Left);
			
		}



adding a transaction
try
			{
				string date = dateTextBox.Text;
				string checkNumber = checkNumberBox.Text;
				string description = descriptionTextBox.Text;
				double amount = double.Parse(amountTextBox.Text);
				string transactionType;
				double currentBalance = double.Parse(currentBalanceBox.Text);
				
				if (writeCheckRadio.Checked)
				{
					transactionType = "Withdrawal";
					amount = 0 - amount;
				}
				else
				{
					transactionType = "Deposit";
					amount = 0 + amount;
				}

				double newBalance = currentBalance + amount;
				currentBalanceBox.Text = newBalance.ToString("0,0.00");

				string[] newTransaction;
				newTransaction = new string[6];
				newTransaction[0] = date;
				newTransaction[1] = checkNumber;
				newTransaction[2] = transactionType;
				newTransaction[3] = description;
				newTransaction[4] = amount.ToString("0,0.00");
				newTransaction[5] = newBalance.ToString("0,0.00");

				ListViewItem newItem = new ListViewItem(newTransaction[0], 0);
				newItem.SubItems.Add(newTransaction[1]);
				newItem.SubItems.Add(newTransaction[2]);
				newItem.SubItems.Add(newTransaction[3]);
				newItem.SubItems.Add(newTransaction[4]);
				newItem.SubItems.Add(newTransaction[5]);

				ledgerView.Items.AddRange(new ListViewItem[] { newItem });

				dateTextBox.Text = "";
				checkNumberBox.Text = "";
				descriptionTextBox.Text = "";
				amountTextBox.Text = "";
			}
			catch (FormatException)
			{
				MessageBox.Show("Amount value must be numbers only " + amountTextBox.Text + " will not work");
			}



deleting a transaction then recalculating all the balances in the list view correctly as well as the textbox under it that displaces the current balance (incase the user is scrolling up or down they can always see the current balance)
try
			{
				//gets index of selected item.
				int sel;
				sel = ledgerView.SelectedIndices[0];

				double ballance = double.Parse(currentBalanceBox.Text);
				double removingAmount = double.Parse(ledgerView.Items[sel].SubItems[4].Text);
				double newBalance = ballance - removingAmount;
				currentBalanceBox.Text = newBalance.ToString("0,0.00");

				//removes selection
				ledgerView.Items.RemoveAt(sel);

				//fixes balances in ledgerView
				double newLedgerBalance = 0;
				double amount = 0;
				int currentEntry = 0;
				int totalEntries = ledgerView.Items.Count;

				while (currentEntry < totalEntries)
				{
					amount = double.Parse(ledgerView.Items[currentEntry].SubItems[4].Text);
					newLedgerBalance = newLedgerBalance + amount;
					ledgerView.Items[currentEntry].SubItems[5].Text = newLedgerBalance.ToString("0,0.00");
					currentEntry++;
				}

			}
			catch
			{
				MessageBox.Show("Please select a transaction to delete, then click the Delete Transaction Button");
			}



there it is for anyone thats having the problem i was having.

thanks again for you guys help, is there anyway i need to rate you guys or anything (this is my first thread on these forums)
anyway time for bed i'll probably be back tommoro looking for help with something lol.

This post has been edited by Extas: 15 April 2008 - 10:51 PM

Was This Post Helpful? 0
  • +
  • -

#12 ggibellato  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 01-May 08

Re: how to get data from a listview?

Posted 01 May 2008 - 02:42 AM

I now you give up from WPF but if you want give another try maybe this code help you


That is the place where I found

http://forums.micros.......41&SiteID=1

That is my adaptation


DataTable table = new DataTable();
		   
			DataColumn column = new DataColumn("OldMatId");
			column.DataType = typeof(string);
			table.Columns.Add(column);

			column = new DataColumn("NewMatId");
			column.DataType = typeof(string);
			table.Columns.Add(column);

			column = new DataColumn("Posted");
			column.DataType = typeof(string);
			table.Columns.Add(column);

			for(int i = 0; i<2; i++)
			{
				column = new DataColumn("POD"+i);
				column.DataType = typeof(string);
				table.Columns.Add(column);
			}

			for(int lines=1; lines<10; lines++)
			{
				DataRow row = table.NewRow();
				row["OldMatId"] = "OldID" + lines;
				row["NewMatId"] = "NewID" + lines;
				row["Posted"] = DateTime.Now;

				for(int i = 0; i<2; i++)
				{
					row["POD"+i] = "Status POD " + i;
				}
				table.Rows.Add(row);
			}

			//Create the GridView and create GridViewColumns
			GridView gridview = new GridView();

			GridViewColumn gvcolumn = new GridViewColumn();
			gvcolumn.Header = "Old Material ID";
			gvcolumn.DisplayMemberBinding = new Binding("OldMatId");
			gridview.Columns.Add(gvcolumn);

			gvcolumn = new GridViewColumn();
			gvcolumn.Header = "New Material ID";
			gvcolumn.DisplayMemberBinding = new Binding("NewMatId");
			gridview.Columns.Add(gvcolumn);

			gvcolumn = new GridViewColumn();
			gvcolumn.Header = "Posted";
			gvcolumn.DisplayMemberBinding = new Binding("Posted");
			gridview.Columns.Add(gvcolumn);

			for (int i = 0; i < 2; i++)
			{
				gvcolumn = new GridViewColumn();
				gvcolumn.Header = "POD" + i;
				gvcolumn.DisplayMemberBinding = new Binding("POD"+i);
				gridview.Columns.Add(gvcolumn);
			}
			//Set the ListView's View to GridView
			lv.View = gridview;

			//Set the DataContext property of the ListView to the DataTable and bind the ItemsSourceProperty to {Binding}
			Binding bind = new Binding();
			lv.DataContext = table;
			lv.SetBinding(ListView.ItemsSourceProperty, bind);




Was This Post Helpful? 0
  • +
  • -

#13 lokesh_03  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-June 11

Re: how to get data from a listview?

Posted 19 June 2011 - 04:59 AM

----Example to get listview box values when button clicked--------------
-----xaml----
<Button x:Name="BtnCheckUpload" Content="CheckUpload" Click="BtnCheckUpload_Click" Margin="71,90,133,0" Height="20" VerticalAlignment="Top" />
       
<ListView ItemsSource="{Binding}" Name="lstvw_filestatus" Margin="78,127,65,69" Selectionchanged="lstvw_filestatus_Selectionchanged" SelectionMode="Multiple">
        <ListView.View>    
          
            <GridView > 
                <GridViewColumn Header="FileNotuploaded" DisplayMemberBinding="{Binding Path=Name}"/>    
                <GridViewColumn Header="Check"> 
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <CheckBox IsChecked="{Binding Checked}" Width="Auto"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                 </GridViewColumn> 
                   </GridView>           
        </ListView.View> 
            </ListView>


----add class ListProp----

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace filedailog
{
   public  class ListProp
    {
        public string Name { get; set; }
        public Boolean Checked { get; set; }
    }
}
--------button  --------
     private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
                try
                 {
                    int ncount = lstvw_filestatus.Items.Count;
                    for (int lp = 0; lp < ncount; lp++)
                    {
                        ListProp mypr = (ListProp)lstvw_filestatus.Items[lp];

                        string lstcon1 = (String)mypr.Name;
                        System.Windows.MessageBox.Show(lstcon1.ToString());

                    }
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.Message);

                }
            }


-----my contact:***REMOVED EMAIL ADDRESS***----

This post has been edited by JackOfAllTrades: 19 June 2011 - 06:37 AM

Was This Post Helpful? 0
  • +
  • -

#14 DivideByZero  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 238
  • View blog
  • Posts: 551
  • Joined: 02-December 10

Re: how to get data from a listview?

Posted 19 June 2011 - 06:28 AM

You've only been programming for a few weeks and you're already working with WPF?
Very impressive dude :)

I still struggling with it and I've been programming for over a year now :/
Was This Post Helpful? 0
  • +
  • -

#15 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6035
  • View blog
  • Posts: 23,418
  • Joined: 23-August 08

Re: how to get data from a listview?

Posted 19 June 2011 - 06:38 AM

NOTE: This topic is a NECRO!

Moved to WPF.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1