Prasad MV
Prasad MV

Reputation: 107

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     [email protected]
james    [email protected]
kris     [email protected]

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

textbox1 = james
textbox2 = [email protected]

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.

Upvotes: 1

Views: 16792

Answers (3)

Rafal
Rafal

Reputation: 1091

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(...)

Upvotes: 3

spajce
spajce

Reputation: 7082

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;
}

Upvotes: 0

shahkalpesh
shahkalpesh

Reputation: 33476

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

Upvotes: 3

Related Questions