Asp.Net 开发之(1) ---如何自动加载数据到页面或更新数据到数据容器中(基础控件)

来源:互联网 发布:淘宝代码转换器 编辑:程序博客网 时间:2024/05/16 12:23

此文章只代表作者在某一段时间内的看法与观点。

    对于一个程序员来说,他们最希望看到了就是如何可以减少他们的工作,也就是说使用最少的code,实现最多的function。在Asp.Net开发的过程中,对data controls的操作是不必不可少,最基本的功能就是对Controls data的加载及Controls选择或输入的值存储起来,也就是所谓的Load 和Update方法。而我们在平时的软件开发的过程中又是怎样来实现这些功能的呢?一般情况下我相信大家都和我之前一样,通过对页面中的每一个Controls做更新或加载,如下代码所示。

一.传统的操作模式

HTML 代码:

 
 1<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ControlsOpr.aspx.cs" Inherits="Adrienne.WCF.WebUI.ControlsOpr" %> 
 2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 3<html xmlns="http://www.w3.org/1999/xhtml"> 
 4<head runat="server"> 
 5<title>Untitled Page</title> 
 6</head> 
 7<body> 
 8<form id="form1" runat="server"> 
 9<div> 
10<dir> 
11用户名:<asp:TextBox ID="UserName" runat="server"></asp:TextBox> 
12</dir> 
13<dir> 
14性别:<asp:RadioButtonList ID="Sex" runat="server" RepeatColumns="2"> 
15<asp:ListItem></asp:ListItem> 
16<asp:ListItem></asp:ListItem> 
17</asp:RadioButtonList> 
18<asp:Button ID="Upload" runat="server" Text="加载" onclick="Upload_Click" /> 
19<asp:Button ID="Update" runat="server" Text="更新" onclick="Update_Click" /> 
20</dir> 
21</div> 
22<asp:GridView ID="GridView1" runat="server"> 
23</asp:GridView> 
24</form> 
25</body> 
26</html> 

CS代码:


 1using System;
 2using System.Collections;
 3using System.Configuration;
 4using System.Data;
 5using System.Linq;
 6using System.Web;
 7using System.Web.Security;
 8using System.Web.UI;
 9using System.Web.UI.HtmlControls;
10using System.Web.UI.WebControls;
11using System.Web.UI.WebControls.WebParts;
12using System.Xml.Linq;
13
14namespace Adrienne.WCF.WebUI
15{
16    public partial class ControlsOpr : System.Web.UI.Page
17    {
18        protected void Page_Load(object sender, EventArgs e)
19        {
20            if (!IsPostBack)
21            {
22                //Create the Date
23                DataTable dt = new DataTable();
24                dt.Columns.Add("USER_NAME");
25                dt.Columns.Add("SEX");
26                DataRow row = dt.NewRow();
27                row["USER_NAME"= "Xiong Wei";
28                row["SEX"= "";
29                dt.Rows.Add(row);
30                ViewState["dt"= dt;
31            }

32        }

33
34        protected void Upload_Click(object sender, EventArgs e)
35        {
36            //Original method
37            if (ViewState["dt"!= null)
38            {
39                DataTable dt = ViewState["dt"as DataTable;
40                ////Should be check each column before
41                this.UserName.Text = dt.Rows[0]["USER_NAME"as string;
42                this.Sex.SelectedValue = dt.Rows[0]["SEX"as string;
43
44                this.GridView1.DataSource = dt;
45                this.DataBind();
46            }

47        }

48
49        protected void Update_Click(object sender, EventArgs e)
50        {
51            if (ViewState["dt"!= null)
52            {
53                DataTable dt = ViewState["dt"as DataTable;
54                //Should be check each column before
55                dt.Rows[0]["USER_NAME"]=this.UserName.Text;
56                dt.Rows[0]["SEX"]=this.Sex.SelectedValue;
57
58                this.GridView1.DataSource = dt;
59                this.DataBind();
60            }

61        }

62    }

63}

 

界面如下:

点击Upload_Click

 

 

点击Update_Click

 

 

传统模式就是这样对页面中的数据进行操作的。

Upload_Click事件完成了对面页中控件值的加载;

Update_Click事件完成了把页面中控件的值更新到相应的数据控件中去。

    我们可以来假设一下,如果存在这样一个项目,项目中存在大概有50个Page,每个Page当中大概有50个Control,这时就存在一个问题,我们如何对这些控件进行加载和保存数据呢,可想而知,上面的方法将存在巨大的工作量,针对上面方法的一个缺点,我们就可以考虑写一些Common的方法来实现上面的操作,从而优化操作模式,下面本人就自己的观点写了一段代码来优化上面的不足。

二.优化的操作模式

在本例中Controls比较少,假设每一个Page中有50个Controls,一个Project中有几十个Pages,那么请问,这个时候我们怎么做,难道还是每一个写一次吧,毋庸置疑,答案是否定的,那么我们又应该怎么了做呢?为此本人写了一个简单的类,这个类主要用来完成对控件值的加载以及对数据容器的更新。

操作类代码:

 


  1using System;
  2using System.Data;
  3using System.Configuration;
  4using System.Linq;
  5using System.Web;
  6using System.Web.Security;
  7using System.Web.UI;
  8using System.Web.UI.HtmlControls;
  9using System.Web.UI.WebControls;
 10using System.Web.UI.WebControls.WebParts;
 11using System.Xml.Linq;
 12using Microsoft.Practices.EnterpriseLibrary.Logging;
 13
 14namespace Adrienne.WCF.WebUI
 15{
 16    /// <summary>
 17    /// Provide the operation for the controls of the pages
 18    /// </summary>

 19    public class PageHelper : PageBase
 20    {
 21        /// <summary>
 22        /// Fill the data information to the controls of the web page
 23        /// </summary>
 24        /// <param name="row"></param>
 25        /// <param name="control"></param>

 26        public static void FillPage(DataRow row, Control control)
 27        {
 28            foreach (DataColumn col in row.Table.Columns)
 29            {
 30                string colName = col.ColumnName.Replace("_""");
 31                Control findControl;
 32                findControl = control.FindControl(colName);
 33                if (findControl != null)
 34                {
 35                    if (row[col.ColumnName] == null)
 36                    {
 37                        continue;
 38                    }

 39                    if (findControl is TextBox)
 40                    {
 41                        TextBox textbox = (TextBox)findControl;
 42                        textbox.Text = row[col.ColumnName].ToString();
 43                    }

 44                    else if (findControl is RadioButton)
 45                    {
 46                        RadioButton radiobutton = (RadioButton)findControl;
 47                        radiobutton.Checked = bool.Parse(row[col.ColumnName].ToString());
 48                    }

 49                    else if (findControl is RadioButtonList)
 50                    {
 51                        RadioButtonList radiobuttonlist = (RadioButtonList)findControl;
 52                        radiobuttonlist.SelectedValue = row[col.ColumnName].ToString();
 53                    }

 54                    else if (findControl is CheckBox)
 55                    {
 56                        CheckBox checkbox = (CheckBox)findControl;
 57                        checkbox.Checked = bool.Parse(row[col.ColumnName].ToString());
 58                    }

 59                    else if (findControl is CheckBoxList)
 60                    {
 61                        CheckBoxList checkboxlist = (CheckBoxList)findControl;
 62                        checkboxlist.SelectedValue = row[col.ColumnName].ToString();
 63                    }

 64                    else if (findControl is DropDownList)
 65                    {
 66                        DropDownList dropdownlist = (DropDownList)findControl;
 67                        dropdownlist.SelectedValue = row[col.ColumnName].ToString();
 68                    }

 69                    else if (findControl is Label)
 70                    {
 71                        Label label = (Label)findControl;
 72                        label.Text = row[col.ColumnName].ToString();
 73                    }

 74
 75                }

 76            }

 77        }

 78
 79        /// <summary>
 80        /// Upload the value of the control to a datarow
 81        /// </summary>
 82        /// <param name="row"></param>
 83        /// <param name="control"></param>

 84        public static void UpdateData(DataRow row, Control control)
 85        {
 86            foreach (DataColumn col in row.Table.Columns)
 87            {
 88                string colName = col.ColumnName.Replace("_""");
 89                Control findControl;
 90                findControl = control.FindControl(colName);
 91                if (findControl != null)
 92                {
 93                    if (findControl is TextBox)
 94                    {
 95                        TextBox textbox = (TextBox)findControl;
 96                        row[col.ColumnName] = textbox.Text;
 97                    }

 98                    else if (findControl is RadioButton)
 99                    {
100                        RadioButton radiobutton = (RadioButton)findControl;
101                        row[col.ColumnName] = radiobutton.Checked;
102                    }

103                    else if (findControl is RadioButtonList)
104                    {
105                        RadioButtonList radiobuttonlist = (RadioButtonList)findControl;
106                        row[col.ColumnName] = radiobuttonlist.SelectedValue;
107                    }

108                    else if (findControl is CheckBox)
109                    {
110                        CheckBox checkbox = (CheckBox)findControl;
111                        row[col.ColumnName] = checkbox.Checked;
112                    }

113                    else if (findControl is CheckBoxList)
114                    {
115                        CheckBoxList checkboxlist = (CheckBoxList)findControl;
116                        row[col.ColumnName] = checkboxlist.SelectedValue;
117                    }

118                    else if (findControl is DropDownList)
119                    {
120                        DropDownList dropdownlist = (DropDownList)findControl;
121                        row[col.ColumnName] = dropdownlist.SelectedValue;
122                    }

123                    else if (findControl is Label)
124                    {
125                        Label label = (Label)findControl;
126                        row[col.ColumnName] = label.Text;
127                    }

128
129                }

130            }

131        }

132    }

133}

134

 

调用此方法:


 1using System;
 2using System.Collections;
 3using System.Configuration;
 4using System.Data;
 5using System.Linq;
 6using System.Web;
 7using System.Web.Security;
 8using System.Web.UI;
 9using System.Web.UI.HtmlControls;
10using System.Web.UI.WebControls;
11using System.Web.UI.WebControls.WebParts;
12using System.Xml.Linq;
13
14namespace Adrienne.WCF.WebUI
15{
16    public partial class ControlsOpr : System.Web.UI.Page
17    {
18        protected void Page_Load(object sender, EventArgs e)
19        {
20            if (!IsPostBack)
21            {
22                //Create the Date
23                DataTable dt = new DataTable();
24                dt.Columns.Add("USER_NAME");
25                dt.Columns.Add("SEX");
26                DataRow row = dt.NewRow();
27                row["USER_NAME"= "Xiong Wei";
28                row["SEX"= "";
29                dt.Rows.Add(row);
30                ViewState["dt"= dt;
31            }

32        }

33
34        protected void Upload_Click(object sender, EventArgs e)
35        {
36            //Original method
37            if (ViewState["dt"!= null)
38            {
39                DataTable dt = ViewState["dt"as DataTable;
40                ////Should be check each column before
41                //this.UserName.Text = dt.Rows[0]["USER_NAME"] as string;
42                //this.Sex.SelectedValue = dt.Rows[0]["SEX"] as string;
43                PageHelper.FillPage(dt.Rows[0],this);
44
45                this.GridView1.DataSource = dt;
46                this.DataBind();
47            }

48        }

49
50        protected void Update_Click(object sender, EventArgs e)
51        {
52            if (ViewState["dt"!= null)
53            {
54                DataTable dt = ViewState["dt"as DataTable;
55                //Should be check each column before
56                //dt.Rows[0]["USER_NAME"]=this.UserName.Text;
57                //dt.Rows[0]["SEX"]=this.Sex.SelectedValue;
58                PageHelper.UpdateData(dt.Rows[0], this);
59
60                this.GridView1.DataSource = dt;
61                this.DataBind();
62            }

63        }

64    }

65}

66

     通过上面的例子,我们知道,如果页面上有50个Control来做加载或更新数据的操作,只要用上面的两句话搞定。

     其实我们在软件开发的过程中,如果发现一直在重复的写一定的代码,一样模式的代码,那么说明我的开发方式或都思想上有问题,或者说需要更新。就本例而言,其实这一个基础的操作,只是对一些基础控件的操作,并且操作的方式比较简单,在以后的时间里,我将写一些关于其它控件的操作。