user1093651
user1093651

Reputation: 2021

How to create a DataTable and filling it with a data from the database using the DataView?

I am a new ASP.NET developer and I want to create a table programmatically using HtmlTable or DataTable and then filling this table with the data from the database using DataView.

I could be able to create a table using HtmlTable but when I did a search regarding "how to fill HtmlTable with a data using DataView", I found that DataView will not work with HtmlTable. So I repeated creating the table using the DataTable, but now I need to fill it with the data using DataView, so how can I do that?

My code:

    DataTable table = new DataTable();

    DataColumn col1 = new DataColumn("Name");
    DataColumn col2 = new DataColumn("Username");

    col1.DataType = System.Type.GetType("System.String");
    col2.DataType = System.Type.GetType("System.String");

    table.Columns.Add(col1);
    table.Columns.Add(col2);

    DataRow row = table.NewRow();
    row[col1] = "John";
    row[col2] = "John123";
    table.Rows.Add(row);


    GridView gv = new GridView();
    gv.DataSource = table;
    gv.DataBind();

Regarding the table in the database, the schema of the User Table is:

Username, FirstName, LastName, Age, Job

Upvotes: 4

Views: 16668

Answers (2)

Rui Mendes
Rui Mendes

Reputation: 21

I guess you could so something like:

var MyTable = new DataAccess.MyTable();
MyTable.LoadAll();
row[col1] = MyTable.Username;
row[col2] = MyTable.FirstName + MyTable.LastName;
row[col3] = MyTable.Age;
row[col4] = MyTable.Job;

Hope this helps.

Upvotes: 1

Icarus
Icarus

Reputation: 63956

You can easily set the DataSource property of a GridView to be the DataView.

GridView gv = new GridView();
gv.DataSource = yourDataView;
gv.DataBind();

By the way, I don't see the need to instantiate the GridView programmatically; you probably can define it on your markup directly. But that's for you to decide what suits you better.

Upvotes: 2

Related Questions