简体   繁体   中英

Get the data from a column in a selected row

I have listView with following columns Name & Email with following data like

NAME     EMAIL
adam     adam@gmail.com
james    james@gmail.com
kris     kris@gmail.com

I select james row, now on two textboxes I want their name & email to be there like

textbox1 = james
textbox2 = james@gmail.com

What I'm doing actually is on form1 I've contextmenu with item update. on the click of updatecontextmenu ill load form2 with textbox name and email. listview contains name and email as shown above.

I want to place the name from the selected row from the list view to name textbox and email respectively.

I tried this.

updateToolStripMenuItem_Click(...)
{

    Form3 update = new Form3();
    update.ShowDialog();            
}

Form3_Load(...)
{
    Form1 f1 = new Form1();
    string oldName = f1.listView1.SelectedItems[0].SubItems[0].Text;
    string oldEmail = f1.listView1.SelectedItems[0].SubItems[0].Text;
    textBox1.Text = oldName.ToString();
    textBox2.Text = oldEmail.ToString();
}

but getting error.

ListViewItem selItem = ListView1.SelectedItems[0];
Console.WriteLine(selItem.SubItems[0].Text);
Console.WriteLine(selItem.SubItems[1].Text);

Update. Try add to your Form3 window method:

public void SetData(string name, string email)
{
    textBox1.Text = name;
    textBox2.Text = email;
}

next, update your updateToolStripMenuItem_Click event handler to:

updateToolStripMenuItem_Click(...)
{
    Form3 update = new Form3();
    ListViewItem selectedItem = listView1.SelectedItems[0];
    update.SetData(selectedItem.SubItems[0].Text, selectedItem.SubItems[1].Text);
    update.ShowDialog();            
}

finally, clear content of Form3_Load(...)

Try to create a properties from your Form3

public string OldName {get;set;}
public string OldEmail {get;set;}

Then, from your From1

updateToolStripMenuItem_Click(...)
{
    using(var update = new Form3())
    {
        var firstCol = listView.SelectedItems[0].Text;
        update.OldName = listView.SelectedItems[0].SubItems[1].Text;
        update.OldEmail = listView.SelectedItems[0].SubItems[2].Text;
        update.ShowDialog();     
    } 
}

Then, in Form3 looks like this

Form3_Load(...)
{
    textBox1.Text = OldName;
    textBox2.Text = OldEmail;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM