這篇文章主要介紹了ASP.NET―GridView綁定List、頁面返回值具體實現,需要的朋友可以參考下
用慣了WPF的綁定,ASP.NET的綁定貌似不是很好用。下面看看ASP.NET綁定的用法。一般來說可以直接綁定DataTable的,不過我覺得綁定List比較符合面向對象編程。
綁定的方法是兩句代碼:
代碼如下:
GridView名.DataSource = List<自定義類>;
GridView名.DataBind();
直接看例子吧,以下是一個綁定一個PersonModel類的例子。其中用到了頁面返回參數,使用js傳遞,js可寫在前端也可直接寫在後台代碼裡。
項目結構:
效果:
實體類
代碼如下:
public class PersonModel
{
private int personIndex;
public int PersonIndex
{
get { return personIndex; }
set { personIndex = value; }
}
private string personID;
public string PersonID
{
get { return personID; }
set { personID = value; }
}
private string personName;
public string PersonName
{
get { return personName; }
set { personName = value; }
}
private string personSex;
public string PersonSex
{
get { return personSex; }
set { personSex = value; }
}
private int personAge;
public int PersonAge
{
get { return personAge; }
set { personAge = value; }
}
private bool personSelected = false;
public bool PersonSelected
{
get { return personSelected; }
set { personSelected = value; }
}
}
針對綁定的aspx頁面寫一個管理類,用於操作數據
代碼如下:
public class ChildFrmManager
{
private List<PersonModel> personCollect = new List<PersonModel>();
private static ChildFrmManager instance = null;
public List<PersonModel> PersonCollect
{
get { return personCollect; }
set { personCollect = value; }
}
public static ChildFrmManager DoGetInstance()
{
if (instance == null)
{
instance = new ChildFrmManager();
}
return instance;
}
public void DoAddPersons()
{
for (int i = 0; i < 20; i++)
{
PersonModel model = new PersonModel();
model.PersonIndex = i + 1;
model.PersonID = System.Guid.NewGuid().ToString();
model.PersonName = "測試" + i;
model.PersonAge = 27 + i;
model.PersonSex = i % 2 == 0 ? "男" : "女";
model.PersonSelected = false;
this.PersonCollect.Add(model);
}
}
}
綁定的頁面前端
代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChildFrm.aspx.cs" Inherits="ASPNetGridView.Pages.ChildFrm" %>
<!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 id="MyBody" runat="server" ms_positioning="GridLayout">
<form id="Form1" runat="server" method="post">
<div>
<asp:GridView ID="dgPersons" runat="server" AutoGenerateColumns="False"
EnableViewState="false"
CellPadding="4" ForeColor="#333333" DataKeyNames="PersonID"
OnSelectedIndexChanged="Selcted_Click">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="PersonInd