Test.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="WebApplication1.Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
<FooterStyle BackColor="Blue" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="Red" />
<Columns>
<asp:BoundField DataField="id" HeaderText="学号"/>
<asp:BoundField DataField="name" HeaderText="姓名"/>
<asp:BoundField DataField="age" HeaderText="年龄"/>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Test.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.BindGridView();
}
private void BindGridView()
{
DataTable dtBind = this.getDB();
this.GridView1.DataSource = dtBind;
this.GridView1.DataBind();
}
/// <summary>
/// 获取数据源的方法
/// </summary>
/// <returns>数据源</returns>
private DataTable getDB()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("age");
dt.Rows.Add(new object[] { "000001", "hekui", "26" });
dt.Rows.Add(new object[] { "000002", "zhangyu", "26" });
dt.Rows.Add(new object[] { "000003", "zhukundian", "27" });
dt.Rows.Add(new object[] { "000004", "liyang", "25" });
dt.Rows.Add(new object[] { "000005", "caili", "27" });
return dt;
}
}
}
AutoGenerateColumns属性:运行时是否基于关联的数据源自动生成列。怎么理解?
实验:将AutoGenerateColumns设为true时
再把AutoGenerateColumns设为false时
相信你已经看到区别了。O(∩_∩)O~