webForumDet fria alternativet

listView - Skapa Event vid radval eller liknande... Hur?

.NETur .NET

7 svar · 251 visningar · startad av T_Codez

Medlem sedan juli 2001458 inlägg
Frågan#1

Hej

Nu är jag fast i listView smeten igen.

Den här gången har jag en listview som populerats via Active Directoriet
i ett antal "items"(rader) som lästs ut från en arraylist under columnerna.

Nu vill jag i samband med att jag väljer (OnFocus, OnClick eller dylikt) en rad (item) att då ska
jag trigga en funktion/metod som lägger ut innehållet i den raden i ett par textboxar istället.

Jag slänger med kod för en betydligt enklare variant av listviewer för lättare överblick på koden.
Samt att det är bara att Copy/Pasta allt till ett nytt projekt för er så spar ni lite tid...

Tacksam för allehanda uppslag och ideer om hur man ska kunna fixa detta. Jag är tyvärr fortfarande
slav under det gamla funktionsorienterade tänket vilket gör att objekt tänket är grymt klurigt för
en annan än så länge...

Så jag hoppas ni kan ha överseende med mina ibland kanske naiva frågor...

namespace ListViewSort
{
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
	private System.Windows.Forms.ListView listView1;
	private System.Windows.Forms.TextBox textBox1;
	private System.Windows.Forms.TextBox textBox2;
	private System.Windows.Forms.TextBox textBox3;
	private System.Windows.Forms.TextBox textBox4;
	private System.Windows.Forms.Button button1;
	/// <summary>
	/// Required designer variable.
	/// </summary>
	private System.ComponentModel.Container components = null;

	public Form1()
	{
		//
		// Required for Windows Form Designer support
		//
		InitializeComponent();

		// Create a new ListView control.
		//	ListView listView1 = new ListView();
		listView1.Bounds = new Rectangle(new Point(10,10), new Size(344,200));
		// Set the view to show details.
		listView1.View = View.Details;
		// Allow the user to edit item text.
		listView1.LabelEdit = true;
		// Allow the user to rearrange columns.
		listView1.AllowColumnReorder = true;
		// Display check boxes.
		listView1.CheckBoxes = true;
		// Select the item and subitems when selection is made.
		listView1.FullRowSelect = true;
		// Display grid lines.
		listView1.GridLines = true;
		// Sort the items in the list in ascending order.
		listView1.Sorting = SortOrder.Ascending;
                     
		// Create three items and three sets of subitems for each item.
		ListViewItem item1 = new ListViewItem("item1",0);
		// Place a check mark next to the item.
		item1.Checked = true;
		item1.SubItems.Add("1");
		item1.SubItems.Add("44");
		item1.SubItems.Add("3");
		ListViewItem item2 = new ListViewItem("item2",1);
		item2.SubItems.Add("22");
		item2.SubItems.Add("5");
		item2.SubItems.Add("3");
		ListViewItem item3 = new ListViewItem("item3",0);
		// Place a check mark next to the item.
		item3.Checked = false;
		item3.SubItems.Add("66");
		item3.SubItems.Add("23");
		item3.SubItems.Add("43");
		ListViewItem item4 = new ListViewItem("item4",0);
		// Place a check mark next to the item.
		item4.Checked = false;
		item4.SubItems.Add("11");
		item4.SubItems.Add("8");
		item4.SubItems.Add("1");
		ListViewItem item5 = new ListViewItem("item5",2);
		// Place a check mark next to the item.
		item5.Checked = false;
		item5.SubItems.Add("5");
		item5.SubItems.Add("44");
		item5.SubItems.Add("13");
		ListViewItem item6 = new ListViewItem("item6",0);
		// Place a check mark next to the item.
		item6.Checked = false;
		item6.SubItems.Add("0");
		item6.SubItems.Add("-1");
		item6.SubItems.Add("48");

		// Create columns for the items and subitems.
		listView1.Columns.Add("Item Column", -2, HorizontalAlignment.Left);
		listView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left);
		listView1.Columns.Add("Column 3", -2, HorizontalAlignment.Left);
		listView1.Columns.Add("Column 4", -2, HorizontalAlignment.Center);

		//Add the items to the ListView.
		listView1.Items.AddRange(new ListViewItem[]{item1,item2,item3, item4, item5, item6});

		// Create two ImageList objects.
		ImageList imageListSmall = new ImageList();
		ImageList imageListLarge = new ImageList();

		// Initialize the ImageList objects with bitmaps.
		imageListSmall.Images.Add(SystemIcons.Asterisk.ToBitmap());
		imageListSmall.Images.Add(SystemIcons.Application.ToBitmap());
		imageListLarge.Images.Add(SystemIcons.Exclamation.ToBitmap());
		imageListLarge.Images.Add(SystemIcons.Hand.ToBitmap());

		//Assign the ImageList objects to the ListView.
		listView1.LargeImageList = imageListLarge;
		listView1.SmallImageList = imageListSmall;

		// Add the ListView to the control collection.
	
	}

	/// <summary>
	/// Clean up any resources being used.
	/// </summary>
	protected override void Dispose( bool disposing )

	{
		if( disposing )
		{
			if (components != null) 
			{
				components.Dispose();
			}
		}
		base.Dispose( disposing );
	}
		#region Windows Form Designer generated code
	/// <summary>
	/// Required method for Designer support - do not modify
	/// the contents of this method with the code editor.
	/// </summary>
	private void InitializeComponent()
	{
		this.listView1 = new System.Windows.Forms.ListView();
		this.textBox1 = new System.Windows.Forms.TextBox();
		this.textBox2 = new System.Windows.Forms.TextBox();
		this.textBox3 = new System.Windows.Forms.TextBox();
		this.textBox4 = new System.Windows.Forms.TextBox();
		this.button1 = new System.Windows.Forms.Button();
		this.SuspendLayout();
		// 
		// listView1
		// 
		this.listView1.Location = new System.Drawing.Point(8, 16);
		this.listView1.Name = "listView1";
		this.listView1.Size = new System.Drawing.Size(344, 208);
		this.listView1.TabIndex = 0;
		this.listView1.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.listView1_ColumnClick);
		// 
		// textBox1
		// 
		this.textBox1.Location = new System.Drawing.Point(8, 240);
		this.textBox1.Name = "textBox1";
		this.textBox1.TabIndex = 1;
		this.textBox1.Text = "";
		// 
		// textBox2
		// 
		this.textBox2.Location = new System.Drawing.Point(8, 264);
		this.textBox2.Name = "textBox2";
		this.textBox2.TabIndex = 2;
		this.textBox2.Text = "";
		// 
		// textBox3
		// 
		this.textBox3.Location = new System.Drawing.Point(120, 240);
		this.textBox3.Name = "textBox3";
		this.textBox3.TabIndex = 3;
		this.textBox3.Text = "";
		// 
		// textBox4
		// 
		this.textBox4.Location = new System.Drawing.Point(120, 264);
		this.textBox4.Name = "textBox4";
		this.textBox4.TabIndex = 4;
		this.textBox4.Text = "";
		// 
		// button1
		// 
		this.button1.Location = new System.Drawing.Point(232, 240);
		this.button1.Name = "button1";
		this.button1.Size = new System.Drawing.Size(120, 48);
		this.button1.TabIndex = 5;
		this.button1.Text = "Hämta Innehåll från rad till textbox";
		// 
		// Form1
		// 
		this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
		this.ClientSize = new System.Drawing.Size(376, 302);
		this.Controls.Add(this.button1);
		this.Controls.Add(this.textBox4);
		this.Controls.Add(this.textBox3);
		this.Controls.Add(this.textBox2);
		this.Controls.Add(this.textBox1);
		this.Controls.Add(this.listView1);
		this.Name = "Form1";
		this.Text = "Form1";
		this.ResumeLayout(false);

	}
	#endregion

	/// <summary>
	/// The main entry point for the application.
	/// </summary>
	[STAThread]
	public static void Main() 
	{
		Application.Run(new Form1());
	}

	private void listView1_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
	{
		//don't sort col 0
		if(e.Column > 0)
		{
			SorterClass sc = new SorterClass(e.Column, listView1.Sorting);
			listView1.ListViewItemSorter = sc;
			if(listView1.Sorting == SortOrder.Ascending)
				listView1.Sorting = SortOrder.Descending;
			else
				listView1.Sorting = SortOrder.Ascending	;
		}
	}
}

public class SorterClass : IComparer
{
	private int _colNum = 0;
	private SortOrder _sortOrder = SortOrder.Ascending;
	public SorterClass(int colNum, SortOrder sortOrder)
	{
		_colNum = colNum;
		_sortOrder = sortOrder;
	}

	//this routine should return -1 if x<y, 1 if x>y and 0 if x==y.
	// for our sample we'll just use string comparison
	public int Compare(object x, object y)
	{
		System.Windows.Forms.ListViewItem item1 = (System.Windows.Forms.ListViewItem) x;
		System.Windows.Forms.ListViewItem item2 = (System.Windows.Forms.ListViewItem) y;
		if(_sortOrder == SortOrder.Descending)
		{
			if(int.Parse(item1.SubItems[_colNum].Text) < int.Parse(item2.SubItems[_colNum].Text))
				return -1;
			else if(int.Parse(item1.SubItems[_colNum].Text) > int.Parse(item2.SubItems[_colNum].Text))
				return 1;
			else
				return 0;
		}
		else
		{
			if(int.Parse(item1.SubItems[_colNum].Text) > int.Parse(item2.SubItems[_colNum].Text))
				return -1;
			else if(int.Parse(item1.SubItems[_colNum].Text) < int.Parse(item2.SubItems[_colNum].Text))
				return 1;
			else
				return 0;
		}
	}
}																								  
}

Tack för uppmärksamheten :e

/T

Medlem sedan nov. 20022 355 inlägg
#2

Du kan väl använda dig av SelectedIndexChanged som du sätter till en vald metod.

Medlem sedan juli 2001458 inlägg
#3

Okay...
Det förslaget verkar helt okay. Men då måste jag börja med att indexera vid alla "inläsningstillfällen" en för var column/rad va?

Jag började pula lite åt detta hållet under tiden (vet dock inte om det är riktigt...)

private void button4_Click(object sender, System.EventArgs e)
{
string test = "";

if (listView1.CheckBoxes = true)
{
test = listView1.CheckedItems.ToString();
label7.Text = listView1.SelectedItems.ToString();
}

Det ger följande: System.Windows.For...

Jag vet inte riktigt hur jag ska få ut själva "strängvärdet/na" från raden. *suck*.

Hjälp för detta mottages tacksamt också. Men funkar det inte riktigt så här så kommer jag grotta vidare på förslaget som du lämnade Mc Fetto.

Medlem sedan apr. 2004778 inlägg
#4

Om man tittar här, http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwindowsformslistviewclassselecteditemstopic.asp så kan man se att SelectedItems returnerar en Collection. Det innebär att du måste loopa den för att få ut alla valda Items. Se kodexemplet.

Medlem sedan juli 2001458 inlägg
#5

Avgrundsdjup *SUCK*... :|

Du fann det jag sökte. Har modifierat min kod efter det exemplet. Men får nu samma "Fel"´som Microsofts Exempelkod ger... (NoNada händer)

Jag får inte ens det exemplet från den sidan (PDahlen's inlägg) att funka...

Fösökte slänga in "System.Windows.Forms.SelectedListViewItemCollection " eller snarare "System.Windows.Forms.ListView.SelectedListViewItemCollection " under form classen. Men det bidde fel där med. Någon som har tid/lust och ork att hjälpa min Newbieskalle med detta?

Siten nämner även detta:
This example assumes the event-handling method is correctly associated with the SelectedIndexChanged event. (och det är förmodligen detta som spökar också...)

Tog bort koden för att den finns ju även på Pdahlens länk (Se inlägget). Samt att det sparar lite Spejs...
Medlem sedan nov. 20022 355 inlägg
#6

prova detta då:

	using System;
	using System.Drawing;
	using System.Collections;
	using System.ComponentModel;
	using System.Windows.Forms;
	using System.Data;

	namespace MS_ListViewSelectedItem
	{
		/// <summary>
		/// Summary description for Form1.
		/// </summary>
		public class Form1 : System.Windows.Forms.Form
		{
			private System.Windows.Forms.ListView ListView1;
			private System.Windows.Forms.TextBox TextBox1;

			/// <summary>
			/// Required designer variable.
			/// </summary>
			private System.ComponentModel.Container components = null;

			// Uses the SelectedItems property to retrieve and tally the price 
			// of the selected menu items.
			private void ListView1_SelectedIndexChanged_UsingItems(
				object sender, System.EventArgs e)
			{
				ListView.SelectedListViewItemCollection breakfast = 
					this.ListView1.SelectedItems;
    
				double price = 0.0;
				foreach ( ListViewItem item in breakfast )
				{
					price += Double.Parse(item.SubItems[1].Text);
				}

				// Output the price to TextBox1.
				TextBox1.Text = price.ToString();
			}

			public Form1()
			{
				// Required for Windows Form Designer support
				//
				InitializeComponent();
				//
				// TODO: Add any constructor code after InitializeComponent call
				//
				InitializeListView();
			}

			// This method adds two columns to the ListView, setting the Text 
			// and TextAlign, and Width properties of each ColumnHeader.  The 
			// HeaderStyle property is set to NonClickable since the ColumnClick 
			// event is not handled.  Finally the method adds ListViewItems and 
			// SubItems to each column.
			private void InitializeListView()
			{
	

				// Create a new ListView control.
				//ListView listView1 = new ListView();
				ListView1.Bounds = new Rectangle(new Point(10,10), new Size(344,200));
				// Set the view to show details.
				ListView1.View = View.Details;
				// Allow the user to edit item text.
				ListView1.LabelEdit = true;
				// Allow the user to rearrange columns.
				ListView1.AllowColumnReorder = true;
				// Display check boxes.
				ListView1.CheckBoxes = true;
				// Select the item and subitems when selection is made.
				ListView1.FullRowSelect = true;
				// Display grid lines.
				ListView1.GridLines = true;
				// Sort the items in the list in ascending order.
				ListView1.Sorting = SortOrder.Ascending;
                     
				// Create three items and three sets of subitems for each item.
				ListViewItem item1 = new ListViewItem("item1",0);
				// Place a check mark next to the item.
				item1.Checked = true;
				item1.SubItems.Add("1");
				item1.SubItems.Add("44");
				item1.SubItems.Add("3");
				ListViewItem item2 = new ListViewItem("item2",1);
				item2.SubItems.Add("22");
				item2.SubItems.Add("5");
				item2.SubItems.Add("3");
				ListViewItem item3 = new ListViewItem("item3",0);
				// Place a check mark next to the item.
				item3.Checked = false;
				item3.SubItems.Add("66");
				item3.SubItems.Add("23");
				item3.SubItems.Add("43");
				ListViewItem item4 = new ListViewItem("item4",0);
				// Place a check mark next to the item.
				item4.Checked = false;
				item4.SubItems.Add("11");
				item4.SubItems.Add("8");
				item4.SubItems.Add("1");
				ListViewItem item5 = new ListViewItem("item5",2);
				// Place a check mark next to the item.
				item5.Checked = false;
				item5.SubItems.Add("5");
				item5.SubItems.Add("44");
				item5.SubItems.Add("13");
				ListViewItem item6 = new ListViewItem("item6",0);
				// Place a check mark next to the item.
				item6.Checked = false;
				item6.SubItems.Add("0");
				item6.SubItems.Add("-1");
				item6.SubItems.Add("48");

				// Create columns for the items and subitems.
				ListView1.Columns.Add("Item Column", -2, HorizontalAlignment.Left);
				ListView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left);
				ListView1.Columns.Add("Column 3", -2, HorizontalAlignment.Left);
				ListView1.Columns.Add("Column 4", -2, HorizontalAlignment.Center);

				//Add the items to the ListView.
				ListView1.Items.AddRange(new ListViewItem[]{item1,item2,item3, item4, item5, item6});

				// Create two ImageList objects.
				ImageList imageListSmall = new ImageList();
				ImageList imageListLarge = new ImageList();

				// Initialize the ImageList objects with bitmaps.
				imageListSmall.Images.Add(SystemIcons.Asterisk.ToBitmap());
				imageListSmall.Images.Add(SystemIcons.Application.ToBitmap());
				imageListLarge.Images.Add(SystemIcons.Exclamation.ToBitmap());
				imageListLarge.Images.Add(SystemIcons.Hand.ToBitmap());

				//Assign the ImageList objects to the ListView.
				ListView1.LargeImageList = imageListLarge;
				ListView1.SmallImageList = imageListSmall;

				// Add the ListView to the control collection.
			}

			/// <summary>
			/// Clean up any resources being used.
			/// </summary>
			protected override void Dispose( bool disposing )
			{
				if( disposing )
				{
					if (components != null) 
					{
						components.Dispose();
					}
				}
				base.Dispose( disposing );
			}
			#region Windows Form Designer generated code
			/// <summary>
			/// Required method for Designer support - do not modify
			/// the contents of this method with the code editor.
			/// </summary>
			private void InitializeComponent()
			{
				this.ListView1 = new System.Windows.Forms.ListView();
				this.TextBox1 = new System.Windows.Forms.TextBox();
				this.SuspendLayout();
				// 
				// ListView1
				// 
				this.ListView1.Location = new System.Drawing.Point(8, 160);
				this.ListView1.Name = "ListView1";
				this.ListView1.TabIndex = 0;
				this.ListView1.SelectedIndexChanged += new System.EventHandler(this.ListView1_SelectedIndexChanged_UsingItems);
				// 
				// TextBox1
				// 
				this.TextBox1.Location = new System.Drawing.Point(144, 240);
				this.TextBox1.Name = "TextBox1";
				this.TextBox1.TabIndex = 1;
				this.TextBox1.Text = "";
				// 
				// Form1
				// 
				this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
				this.ClientSize = new System.Drawing.Size(312, 318);
				this.Controls.Add(this.TextBox1);
				this.Controls.Add(this.ListView1);
				this.Name = "Form1";
				this.Text = "Form1";
				this.ResumeLayout(false);

			}
			#endregion

			/// <summary>
			/// The main entry point for the application.
			/// </summary>
			[STAThread]
			static void Main() 
			{
				Application.Run(new Form1());
			}

		}
	}
Medlem sedan juli 2001458 inlägg
#7

:L Tjoflöjt :birp

Ett tips är att lägga ner Microsofts exempel och skapa
en egen variant som är snarlik. Då funkar det utmärkt!

Första missen som jag gjorde var en V.Studio grej. Typ hallå... det finns en knapp som har en blixt som håller i alla Events.

(Man lär sig nya prylar hela tiden...)

Där hittade jag iaf "SelectIndexChanged". Klickade sen på (nedpilen). Och skrev in "ListView1_SelectedIndexChanged_UsingItems" (Gick att välja också...).

Sen gick det bra att bygga. Kompilera & Köra... Och banne mig om det inte funkade som jag/vi ville till slut.

private void ListView1_SelectedIndexChanged_UsingItems(object sender, System.EventArgs e)
{
	ListView.SelectedListViewItemCollection anvandare = this.listView1.SelectedItems;
   
	string test = "";
		foreach ( ListViewItem item in anvandare )
	{
		test += item.SubItems[3].Text;
	}

	this.label7.Text = test.ToString();
}		}

Glöm all tjafskod som jag lagt till inann i den här tråden, för de hjälper ändå ingen...

Thankz! :e McFetto och Pdahlen för uppslag och ideer.

Medlem sedan juli 2001458 inlägg
#8

Ojdå...

Hade inte noterat att du svarat en gång till McFetto.

Jepp ditt förlag funkade finfint de med.

Thankz for the effort. :birp

147 ms totalt · 3 externa anrop · v20260731065814-full.b746b907
0 ms — hämta forumlista (cache)
0 ms — hämta statistik (cache)
144 ms — hämta tråd, inlägg och bilagor (db)