views:

75

answers:

2

I have a ListView which is filled by generic list of type MyClass. I can easily bind data from this list into ListView. But I have problems with reading data in opposite direction. This is my class:

public class MyClass
{
    public int id { get; set; }
    public string name { get; set; }
}

I have also generic list of type MyClass:

List<MyTest> list = new List<MyTest>();

Finally I bind data to ListView this way:

ListView1.DataSource = list;
ListView1.DataBind();

My ListView template:

  <asp:ListView runat="server" ID="ListView1">
  <LayoutTemplate>
    <table runat="server" id="table1" >
      <tr runat="server" id="itemPlaceholder" ></tr>
    </table>
  </LayoutTemplate>
  <ItemTemplate>
    <tr id="tr" runat="server">
        <td id="td1" runat="server">
            <asp:TextBox ID="tb1" runat="server" Text='<%#Eval("id") %>' />
        </td>
        <td id="td2" runat="server">
            <asp:TextBox ID="tb2" runat="server" Text='<%#Eval("name") %>' />
        </td>
    </tr>
  </ItemTemplate>

How can I read data from ListView into my List list?

The operation of reading ListView data into List generic list should begin after clicking the button "GetData"

+1  A: 

I can't test this, but I believe this will work:

using System.Linq;

List<MyClass> list = ListView1.DataSource.Cast<MyClass>().ToList();

UPDATE: As noted in the comments, that only works right after you set the DataSource. If you want to get the list on a post-back, try:

List<MyClass> list = ListView1.Items
                              .Select(lvi=>lvi.DataItem as MyClass)
                              .ToList();
James Curran
However, that will only work before a post back. The poster might want to get the list out of the ListView in a post back situation.
Jason Berkan
Unfortunatelly your solution does not work in my project. The data is binding to my ListView correctly, but when I try to get data form ListView (after postback) i got nothing. I see that DataItem property for each row has null value so my list gets all rows from ListView, but they all are with null values.
pit
A: 

You can get at the ListViewItem in an updating event like this:

<asp:ListView ID="ListView1" runat="server" OnItemUpdating="ListView1_ItemUpdating"></asp:ListView>

void ListView1_ItemUpdating(Object sender, ListViewUpdateEventArgs e)
{
     ListViewItem item = ListView1.Items[e.ItemIndex];

     // I think you should also be able to do if you are indeed binding with the type List<MyTest>
     List<MyTest> item = (List<MyTest>)ListView1.Items[e.ItemIndex];
}

I can show you other ways if you describe more of what the scenario is that you need to get the data.

TheGeekYouNeed