0

How can I populate data into GridView using LINQ data source. Currently Im doing this manual with code bellow. alt text

Here is my code:

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

code behind

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

1 Answer 1

1

The following Scott Guthrie's blog post should help you:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.