Listview c # passing value to the next form

0

I've set form to c# and this form is responsible for showing all data in my table in Bd and putting that data in listview , so I can select an item from listview e I mounted another form where it will receive the ID of the field that was selected in listview .

That's where it started to complicate how I can pass this value to my other form , because it does not recognize the Listview.selectedvalue command, so I store the id of the selected line and pass it as a search parameter in other form

    
asked by anonymous 04.10.2016 / 07:11

1 answer

0

Via construtor of classe that receives the ID of ListView . In the code below the evento ListView1_MouseDoubleClick would be a clear example of sending ID via construtor .

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listView1.Columns.Add("Codigo", "Código");
            listView1.Columns.Add("Nome", "Nome");

            ListViewItem item0001 = listView1.Items.Add("0001");
            item0001.SubItems.Add("Teste 1");

            ListViewItem item0002 = listView1.Items.Add("0002");
            item0002.SubItems.Add("Teste 2");

            listView1.FullRowSelect = true;

            listView1.MouseDoubleClick += ListView1_MouseDoubleClick;

        }

        private void ListView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListView listView = ((ListView)sender);
            if (listView != null)
            {
                if (e.X >= 0 && e.Y >= 0)
                {
                    ListViewItem listViewItem = listView.GetItemAt(e.X, e.Y);
                    if (listViewItem != null)
                    {
                        int id;
                        if (int.TryParse(listViewItem.Text, out id))
                        {
                            Form2 frm = new Form2(id);
                            frm.ShowDialog();
                        }
                    }
                }
            }            
        }
    }
}

No form2 create a paramento in construtor that will receive the value sent form1 :

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        private int _id;
        public Form2(int Id)
        {
            InitializeComponent();
            _id = Id;
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            //code
            //_id enviado do form1
            label1.Text = $"{_id}";
        }
    }
}

With _id you have the option to load data, manipulate, etc.

    
04.10.2016 / 15:46