pit
pit

Reputation: 21

How to read ListView data into generic List

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"

Upvotes: 1

Views: 3721

Answers (2)

TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

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.

Upvotes: 0

James Curran
James Curran

Reputation: 103545

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

Upvotes: 1

Related Questions