ASP.NET―001: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="PersonIndex" HeaderText="序号"/>
       <asp:TemplateField>
       <ItemTemplate>
       <input id="radiobutton1" name="pselect" type="radio" />
       </ItemTemplate>
       </asp:TemplateField>
       <asp:BoundField DataField="PersonName" HeaderText="姓名" />
       <asp:BoundField DataField="PersonAge" HeaderText="年龄" />
       <asp:BoundField DataField="PersonSex" HeaderText="性别" />
     </Columns>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

    </asp:GridView>
    </div>
    </form>
</body>
</html>

绑定页面后台

复制代码 代码如下:

 public partial class ChildFrm : System.Web.UI.Page
    {
        private ChildFrmManager dManager = null;

        protected PersonModel selectItem = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            dManager = ChildFrmManager.DoGetInstance();

            if (!IsPostBack)
            {
                dManager.DoAddPersons();

                this.dgPersons.DataSource = dManager.PersonCollect;

                this.dgPersons.DataBind();
            }
        }

        protected void Selcted_Click(object sender, EventArgs e)
        {
            int selectIndex = this.dgPersons.SelectedIndex;

            foreach (PersonModel mitem in dManager.PersonCollect)
            {
                if (mitem.PersonIndex - 1 == selectIndex)
                {
                    mitem.PersonSelected = true;
                }
                else
                {
                    mitem.PersonSelected = false;
                }
            }

            selectItem = dManager.PersonCollect[selectIndex];

            string vbCrLf = " ";

            string strScript = "<script>" + vbCrLf;

            strScript += "window.parent.returnValue='" + selectItem.PersonName + "';" + vbCrLf;

            strScript += "window.parent.close();" + vbCrLf;

            strScript += "</script>" + vbCrLf;

            if (!IsClientScriptBlockRegistered("clientScript"))
            {
                RegisterClientScriptBlock("clientScript", strScript);
            }
        }
    }

承载绑定页面的页面

复制代码 代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FrameFrm.aspx.cs" Inherits="ASPNetGridView.Pages.FrameFrm" %>

<!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>
<frameset rows="0,*">
    <frame src="about:blank">
    <frame src="ChildFrm.aspx">
  </frameset>
</html>

主页面,获取返回值的js在前端

复制代码 代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ASPNetGridView._Default" %>

<!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>
    <div align="center">
        <form id="Form1" runat="server" method="post">
            <table runat="server">
              <tr>
                  <td>
                  <asp:Label ID="Label1" runat="server" Font-Bold="true">选择结果</asp:Label>
                  </td>

                  <td>
                  <asp:TextBox ID="txtShowReturnValue" runat="server" Width="100px" />
                  </td>
                  <td>
                  <asp:Button ID="btnOpenNewFrm" runat="server" Text="选择" Width="60px" OnClientClick="OpenNewWindow()"/>
                  </td>
              </tr>
            </table>
        </form>
    </div>
</body>
<script type ='text/javascript'>
    function OpenNewWindow() {

        var str = window.showModalDialog('Pages/FrameFrm.aspx', document.Form1.txtShowReturnValue.value, 'dialogWidth=1000px;dialogHeight=900px', 'scroll:yes');

        if (str != null)
        { document.Form1.txtShowReturnValue.value = str; }
    }
</script>
</html>

代码下载

时间: 2024-11-03 09:34:17

ASP.NET―001:GridView绑定List、页面返回值具体实现_实用技巧的相关文章

asp.net实现调用存储过程并带返回值的方法_实用技巧

本文实例讲述了asp.net实现调用存储过程并带返回值的方法.分享给大家供大家参考,具体如下: /// <summary> /// DataBase 的摘要说明 /// </summary> public class DataBase { /// <summary> ///DataBase 的摘要说明 /// </summary> protected static SqlConnection BaseSqlConnection = new SqlConnec

使用ASP.NET模板生成HTML静态页面的五种方案_实用技巧

ASP.NET模版生成HTML静态页面方案1: 复制代码 代码如下: /// < summary> /// 传入URL返回网页的html代码 /// < /summary> /// < param name="Url">URL< /param> /// < returns>< /returns> public static string getUrltoHtml(string Url) { errorMsg = &

ASP.NET中GridView 重复表格列合并的实现方法_实用技巧

这几天做一个项目有用到表格显示数据的地方,客户要求重复的数据列需要合并,就总结了一下GridView 和 Repeater 关于重复数据合并的方法. 效果图如下: GridView : 前台代码 : <div> <asp:GridView ID="gvIncome" runat="server" AutoGenerateColumns="False"> <Columns> <asp:TemplateFie

ASP.NET实现个人信息注册页面并跳转显示_实用技巧

题目 新建一个MVC项目,利用HTML.CSS.JS.jQuery.Ajax.jQuery UI等技术设计一个个人信息注册页面.当点击"提交"按钮时,跳转到新的页面显示录入信息. 基本要求: 用户名为6-10个小写字母(小写使用正则式验证,且用户名不能为"wustzz" –用Ajax技术来检测):密码为6位数字,确认密码不一致时有提示:籍贯使用级联(jquery实现):Email必须符合Email格式:手机是11位(假设规定以1569开头):出生年月使用jQuery

VB.NET调用MySQL存储过程并获得返回值的方法_实用技巧

本文实例讲述了VB.NET调用MySQL存储过程并获得返回值的方法.分享给大家供大家参考.具体实现方法如下: Dim myConnectionString As String = "Database=" & myDatabase & _ " ;Data Source=" & myHost & _ ";User Id=" & myUserId & ";Password=" &

ASP.NET中RadioButtonList绑定后台数据后触发点击事件_实用技巧

本文实例为大家分享了RadioButtonList绑定后台数据,触发点击事件的方法 首先前台页面放置一个RadioButtonList 控件 <asp:RadioButtonList runat="server" ID="RadioButtonList1" BorderStyle="None" RepeatColumns="3" CssClass="" RepeatLayout="Flow&

asp.net 不用GridView自带删除功能,删除一行数据_实用技巧

前台代码: 复制代码 代码如下: <asp:GridView ID="GridLog" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ID" BorderColor="#333" BorderStyle="solid" BorderWidth="1&qu

解决ASP.NET中Type.GetType方法总返回空的问题_实用技巧

 Type.GetType总是返回NULL;    后来查看,web项目中的引用,发现么有引用对应的项目.. 所以,应用程序无法在web项目中找到对应的dll.. 添加一个引用就解决了.... 额...不知道怎么说通顺些 举个例子 如:Type.GetType("System.String") //这个是没问题的,因为System.String在mscorlib.dll中 下边我要获取MyProject.Data.SqlServerDAL Type.GetType("MyPr

ASP.NET MVC 从IHttp到页面输出的实例代码_实用技巧

复制代码 代码如下: MVCHandler : IHttpHandlervoid IHttpHandler.ProcessRequest(HttpContext httpContext){    this.ProcessRequest(httpContext);} protected virtual void ProcessRequest(HttpContext httpContext){    HttpContextBase base2 = new HttpContextWrapper(htt