简体   繁体   中英

Bind data to grid view using LINQ with out adding DataClasses

I have seen many articles using LINQ to bind gridview , but in all are using DataClasses . Is it possible to bind data to grid view using LINQ with out adding DataClasses .. Can any one give me any sample code or working example on this

在此处输入图片说明

I think I may be missing the point, but whatever the source of your data, as long as it's some form of collection, you can use Linq to objects to query the data. So for example:

public partial class WebUserControl1 : System.Web.UI.UserControl
{
    private readonly List<DataItem> _items;

    public WebUserControl1()
    {
        _items = new List<DataItem>
                     {
                         new DataItem {Name = "Fred"},
                         new DataItem {Name = "Dave"},
                         new DataItem {Name = "John"},
                     };
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Get data and use Linq to objects
        var filteredData = GetData().Where(i => i.Name.StartsWith("F")).ToList();

        // Bind to data 
        GridView1.DataSource = filteredData;
        GridView1.DataBind();
    }

    private IEnumerable<DataItem> GetData()
    {
        // Get data from your data source
        return _items;
    }
}

public class DataItem
{
    public string Name { get; set; }
}

If your data is an a database, then a good option is to use Linq to SQL (SQL Server only) or Linq to Entities (not just SQL Server), or Linq to Datasets (if you really have to).

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