Asp.net GridView使用LINQ DataSource填充数据

时间:2010-11-06 15:14:32

标签: asp.net linq gridview datasource

如何使用LINQ数据源将数据填充到GridView中。 目前我正在使用下面的代码执行此手册。 alt text

这是我的代码:

<asp:GridView ID="gridProcesses" runat="server" AutoGenerateColumns="False" 
EnableModelValidation="True" Width="400px" DataKeyNames="ID">
    <Columns>
        <asp:BoundField HeaderText="Name" />
        <asp:BoundField HeaderText="CPU" />
        <asp:BoundField HeaderText="RAM" />
        <asp:CommandField ButtonType="Button" SelectText="Kill" ShowSelectButton="True">
        <ItemStyle HorizontalAlign="Center" Width="30px" />
        </asp:CommandField>
    </Columns>
</asp:GridView> 

背后的代码

public partial class OsControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private List<string> getTestData()
    {
        List<string> tData = new List<string>();
        Random rand = new Random();
        for (int i = 0; i < 10; i++)
        {
            tData.Add("proc" + i + "_" + rand.Next(100) + "_" + rand.Next(100));
        }

        return tData;
    }

    protected void btnLoad_Click(object sender, EventArgs e)
    {
        DataTable dtProcesses = new DataTable();
        dtProcesses.Columns.Add("Name", System.Type.GetType("System.String"));
        dtProcesses.Columns.Add("CPU", System.Type.GetType("System.Int32"));
        dtProcesses.Columns.Add("RAM", System.Type.GetType("System.Int32"));
        dtProcesses.Columns.Add("ID", System.Type.GetType("System.Int32"));

        int id = 0;
        foreach (string line in getTestData())
        {
            string[] items = line.Split('_');
            DataRow row = dtProcesses.NewRow();
            row["Name"] = items[0];
            row["CPU"] = int.Parse(items[1]);
            row["RAM"] = int.Parse(items[1]);
            row["ID"] = id++;
            dtProcesses.Rows.Add(row);
        }

        gridProcesses.DataSource = dtProcesses;
        gridProcesses.DataBind();
    }
}-

1 个答案:

答案 0 :(得分:1)

以下Scott Guthrie的博客文章可以帮助您:

LINQ to SQL (Part 5 - Binding UI using the ASP:LinqDataSource Control)