Windows Forms: How to pass ListView row data into another Form in C#
By FoxLearn 7/26/2017 9:46:05 PM 7.74K
How to pass ListView row data into another Form in C#
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "LinkListViewToDatabase" and then click OK
Step 2: Design your form as below
Form1
frmDetail
Step 3: Create an Entity Framework Model, then add a Product table from Northwind database to your model
Step 4: Add code to handle your form as below
frmDetail
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LinkListViewToDatabase { public partial class frmDetail : Form { public frmDetail(Product p) { InitializeComponent(); productBindingSource.DataSource = p; } } }
Form1
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LinkListViewToDatabase { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnLoad_Click(object sender, EventArgs e) { //Init data Cursor.Current = Cursors.WaitCursor; using (NorthwindEntities db = new NorthwindEntities()) { List<Product> list = db.Products.ToList(); foreach(Product p in list) { ListViewItem item = new ListViewItem(p.ProductID.ToString()); item.SubItems.Add(p.ProductName); item.SubItems.Add(p.UnitPrice.ToString()); item.SubItems.Add(p.UnitsInStock.ToString()); listView.Items.Add(item); } } Cursor.Current = Cursors.Default; } private async void listView_ItemActivate(object sender, EventArgs e) { if (listView.SelectedItems.Count > 0) { ListViewItem item = listView.SelectedItems[0]; using (NorthwindEntities db = new NorthwindEntities()) { string productId = item.SubItems[0].Text; Product p = await db.Products.FindAsync(Convert.ToInt32(productId)); if (p != null) { using (frmDetail frm = new frmDetail(p)) { if (frm.ShowDialog() == DialogResult.OK) { //Process } } } } } } } }
VIDEO TUTORIALS
- Windows Forms: Text to speech in C#
- Windows Forms: Print Picture Box in C#
- Windows Forms: Advanced Filter DataGridView in C#
- Windows Forms: Progress Bar in C#
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024
What Are RESTful Web Services?
02/19/2024