将 GridView 与 DataSource 绑定,例如 DataTable

第 1 步:设计 GridView 以显示你的数据( HTML 代码 ):

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label ID="lblId" runat="server" Text='<% #Bind("id") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="NAME">
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server" Text='<% #Bind("name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="COUNTRY">
            <ItemTemplate>
                <asp:Label ID="lblCountry" runat="server" Text='<% #Bind("country") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

第 2 步:使用 DataTable( .CS 代码 ) 绑定 GridView :

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Create a datatable as a DataSource of your GridView
            DataTable dt = new DataTable();

            // Add three columns in datatable and their names and data types
            dt.Columns.Add(new DataColumn("id", typeof(int)));
            dt.Columns.Add(new DataColumn("name", typeof(string)));
            dt.Columns.Add(new DataColumn("country", typeof(string)));

            // Add five records in datatable
            for (int i = 0; i < 5; i++)
            {
                dt.Rows.Add(i, "Name" + i, "Country" + i);
            }

            GridView1.DataSource = dt; // set your datatable to your gridview as datasource
            GridView1.DataBind(); // bind the gridview with datasource
        }
}

绑定后,GridView 看起来像这样:

StackOverflow 文档

注意: 你还可以从数据库绑定 GridView。