简体   繁体   中英

Populating a GridView from a DataTable

I am new ASP.NET and I have never used a GridView or DataGrid, but I cannot find helpful examples online on how to do what I need. I need some data to be displayed on a page and I know that I should use a GridView, but I cannot seem to get anything to display.

I have the following DataSet:

DataSet ds = new DataSet("MyTables");
ds.Tables.Add("Users");
ds.Tables["Users"].Columns.Add("ID");
ds.Tables["Users"].Columns.Add("Name");
ds.Tables["Users"].Columns.Add("Email");
ds.Tables["Users"].Rows.Add(0,"Ace","ace@example.com");
ds.Tables["Users"].Rows.Add(1,"Biff","biff@example.com");
ds.Tables["Users"].Rows.Add(2,"Chuck","chuck@example.com");
ds.Tables["Users"].Rows.Add(3,"Dick","dick@example.com");
myGrid.DataSource = ds.Tables["Users"].DefaultView;
myGrid.DataBind();

Heres is my ASP.NET:

<asp:GridView ID="myGrid" runat="server">
</asp:GridView>

I think you're adding columns to the wrong table. Try something like this:

DataSet ds = new DataSet("MyTables");
ds.Tables.Add("Users");
DataTable userTable = ds.Tables["Users"];
userTable.Columns.Add("ID");
userTable.Columns.Add("Name");
userTable.Columns.Add("Email");
userTable.Rows.Add(0,"Ace","ace@example.com)";
userTable.Rows.Add(1,"Biff","biff@example.com)";
userTable.Rows.Add(2,"Chuck","chuck@example.com)";
userTable.Rows.Add(2,"Dick","dick@example.com)";
myGrid.DataSource = userTable;
myGrid.DataBind();

You are referencing two completely different tables. You create the Table USERS then add columns to a table called ADD USERS then add rows to the Users table. Nothing will show up when you bind this.

Change this code

ds.Tables["Add Users"].Columns.Add("ID");
ds.Tables["Add Users"].Columns.Add("Name");
ds.Tables["Add Users"].Columns.Add("Email");

to this

ds.Tables["Users"].Columns.Add("ID");
ds.Tables["Users"].Columns.Add("Name");
ds.Tables["Users"].Columns.Add("Email");

I'm thinking that you're getting a object null reference error. What's happening is that you're creating columns in a table called 'add users' where there is no table called 'add users'. If you just change the three lines that you have ds.Tables["Add Users"] and change that to just ds.Tables["Users"] everything should work out just fine.

Hope this works for you.

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