现在的位置: 首页 > 综合 > 正文

【ASP.NET2.0学习笔记】开发投票系统

2013年12月23日 ⁄ 综合 ⁄ 共 12843字 ⁄ 字号 评论关闭

//文章作者:叶茂(猫猫)(本学习笔记系列文章拒绝任何形式的修改、加工或转载)

 

这个投票系统的大部分源码来自马军主编的《精通ASP.NET 2.0 网络应用系统开发》,但是按照原文提供的代码,系统是无法在VS2005下编译通过的。鉴于此,猫重写了部分代码使其能正常运行于VS2005,现贴出来给大家分享。

 

1、系统功能设计

  • 投票选项管理
  • 对选项投票
  • 投票情况查看

2、数据库设计

  • VoteDB

 

3、存储过程设计

  • 添加投票选项
    1. CREATE PROCEDURE Proc_AddVote
    2. @Item varchar(100)
    3. AS
    4. INSERT INTO
    5. Votes(Item,VoteCount)
    6. VALUES(@Item,0)
    7. RETURN @@Identity
    8. GO
  • 删除投票选项
    1. CREATE PROCEDURE Proc_DeleteVote
    2. @VoteID int
    3. AS
    4. DELETE Votes
    5. WHERE VoteID = @VoteID
    6. GO
  • 更新投票选项
    1. CREATE PROCEDURE Proc_UpdateVote
    2. @VoteID int
    3. AS
    4. UPDATE Votes
    5. SET VoteCount = VoteCount + 1
    6. WHERE VoteID = @VoteID
    7. GO
  • 显示所有投票项目
  1. CREATE PROCEDURE Pr_GetVotes
  2. AS
  3. SELECT *
  4. FROM Votes
  5. Order By VoteID
  6. GO

4、数据库访问层设计

      在App_Code文件夹下添加一个.cs类文件用来封装对以上存储过程的调用方法。

  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;
  10. using SQLHelper;
  11. using System.Data.SqlClient;
  12. namespace WebVote
  13. {
  14.     /// <summary>
  15.     /// Summary description for Vote
  16.     /// </summary>
  17.     public class Vote
  18.     {
  19.         public SqlDataReader GetVotes()
  20.         {
  21.             ///定义类SQLHelper
  22.             SQLHelper.SQLHelper sqlHelper = new SQLHelper.SQLHelper();
  23.             ///定义保存从数据库获取的结果的DataReader
  24.             SqlDataReader dr = null;
  25.             try
  26.             {
  27.                 ///执行存储过程
  28.                 sqlHelper.RunProc("Proc_GetVotes"out dr);
  29.             }
  30.             catch (Exception ex)
  31.             {
  32.                 ///抛出执行数据库异常
  33.                 SystemError.CreateErrorLog(ex.Message);
  34.                 throw new Exception(ex.Message, ex);
  35.             }
  36.             ///返回从数据库获取的结果
  37.             return (dr);
  38.         }
  39.         public int AddVote(String sItem)
  40.         {
  41.             ///定义类SQLHelper
  42.             SQLHelper.SQLHelper sqlHelper = new SQLHelper.SQLHelper();
  43.             ///创建访问数据库的参数       
  44.             SqlParameter[] paramList = {
  45.                 sqlHelper.CreateInParam("@Item", SqlDbType.VarChar,100,sItem)
  46.             };
  47.             try
  48.             {
  49.                 ///执行存储过程
  50.                 return (sqlHelper.RunProc("Proc_AddVote", paramList));
  51.             }
  52.             catch (Exception ex)
  53.             {
  54.                 ///抛出执行数据库异常
  55.                 SystemError.CreateErrorLog(ex.Message);
  56.                 throw new Exception(ex.Message, ex);
  57.             }
  58.         }
  59.         public void UpdateVote(int nVoteID)
  60.         {
  61.             ///定义类SQLHelper
  62.             SQLHelper.SQLHelper sqlHelper = new SQLHelper.SQLHelper();
  63.             ///创建访问数据库的参数
  64.             SqlParameter[] paramList = {
  65.                 sqlHelper.CreateInParam("@VoteID", SqlDbType.Int, 4,nVoteID)
  66.             };
  67.             try
  68.             {
  69.                 ///执行存储过程
  70.                 sqlHelper.RunProc("Proc_UpdateVote", paramList);
  71.             }
  72.             catch (Exception ex)
  73.             {
  74.                 ///抛出执行数据库异常
  75.                 SystemError.CreateErrorLog(ex.Message);
  76.                 throw new Exception(ex.Message, ex);
  77.             }
  78.         }
  79.         public void DeleteVote(int nVoteID)
  80.         {
  81.             ///定义类SQLHelper
  82.             SQLHelper.SQLHelper sqlHelper = new SQLHelper.SQLHelper();
  83.             ///创建访问数据库的参数   
  84.             SqlParameter[] paramList = {
  85.                 sqlHelper.CreateInParam("@VoteID", SqlDbType.Int, 4,nVoteID)
  86.             };
  87.             try
  88.             {
  89.                 ///执行存储过程
  90.                 sqlHelper.RunProc("Proc_DeleteVote", paramList);
  91.             }
  92.             catch (Exception ex)
  93.             {
  94.                 ///抛出执行数据库异常
  95.                 SystemError.CreateErrorLog(ex.Message);
  96.                 throw new Exception(ex.Message, ex);
  97.             }
  98.         }
  99.     }
  100. }

对于数据访问层,需要使用一个SQLHelper的DLL文件(下载地址:http://d.download.csdn.net/down/661742/zhaobisha 将其粘贴到Bin文件夹中。

 

5、程序页面设计

  • 主页面(Default.aspx)
    1. ...    
    2. <form id="form1" runat="server">
    3.     <div>
    4.         <asp:LinkButton ID="ItemManageLink" runat="server" BackColor="Black" ForeColor="White"
    5.             Height="24px" Width="149px" PostBackUrl="VoteItemManage.aspx">投票选项管理</asp:LinkButton><br />
    6.         <br />
    7.         <asp:LinkButton ID="OnlineVoteLink" runat="server" BackColor="Black" ForeColor="White"
    8.             Height="24px" Width="149px" PostBackUrl="~/OnlineVote.aspx">在线投票</asp:LinkButton> <br />
    9.         <br />
    10.         <asp:LinkButton ID="ViewVoteLink" runat="server" BackColor="Black" ForeColor="White"
    11.             Height="24px" Width="149px" PostBackUrl="~/ShowVoteResult.aspx">查看投票结果</asp:LinkButton></div>
    12. </form>
    13. ...
  • 投票选项管理页面(VoteItemManage.aspx)

 

    1. ...
    2. <form id="form1" runat="server">
    3.     <div>
    4.         <asp:ListBox ID="ItemList" runat="server" Rows="10" Width="150px"></asp:ListBox>
    5.         <asp:Button ID="deleteBtn" runat="server" CommandName="delete" OnClientClick="deleteBtn_Click"
    6.             Text="删除此项" OnClick="deleteBtn_Click" /> <br />
    7.          <asp:TextBox ID="Item" runat="server" Height="18px" Width="290px"></asp:TextBox>
    8.         <asp:Button ID="AddBtn" runat="server" Text="增加新选项" OnClick="AddBtn_Click" /></div>
    9. </form>
    10. ...
  • 在线投票页面(OnlineVote.aspx)

 

 

    1. ...
    2. <form id="form1" runat="server">
    3.     <div>
    4.         <asp:GridView ID="VoteList" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="VoteID">
    5.             <Columns>
    6.                 <asp:TemplateField HeaderText="勾选" SortExpression="VoteID">
    7.                     <ItemTemplate>
    8.                         <asp:CheckBox ID="VoteCheck" runat="server" />
    9.                     </ItemTemplate>
    10.                     <ItemStyle HorizontalAlign="Center" />
    11.                 </asp:TemplateField>
    12.                 <asp:BoundField DataField="Item" HeaderText="投票选项" SortExpression="Item" >
    13.                     <ControlStyle BackColor="#E0E0E0" />
    14.                     <ItemStyle Width="200px" HorizontalAlign="Center" />
    15.                 </asp:BoundField>
    16.                 <asp:BoundField DataField="VoteID" ShowHeader="False" SortExpression="VoteID" Visible="False" />
    17.             </Columns>
    18.             <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
    19.             <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
    20.             <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
    21.             <RowStyle BackColor="White" ForeColor="#330099" />
    22.             <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
    23.         </asp:GridView>
    24.     
    25.     </div>
    26.         <asp:Button ID="VoteBtn" runat="server" Text="我要投票" OnClick="VoteBtn_Click" /> 
    27.         <asp:Button ID="ShowVote" runat="server" Text="查看结果" PostBackUrl="~/ShowVoteResult.aspx" /> 
    28.         <asp:Label ID="VoteMessage" runat="server">投票成功!</asp:Label><br />
    29.         <br />
    30. </form>
    31. ...
  • 查看投票结果页面(ShowVoteResult.aspx)

 

 

  1. ...
  2. <form id="form1" runat="server">
  3.     <div>
  4.         <asp:GridView ID="VoteList" runat="server" BackColor="White" BorderColor="#CC9966"
  5.             BorderStyle="None" BorderWidth="1px" CellPadding="4" AutoGenerateColumns="False">
  6.             <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
  7.             <RowStyle BackColor="White" ForeColor="#330099" />
  8.             <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
  9.             <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
  10.             <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
  11.             <Columns>
  12.                 <asp:BoundField DataField="Item" HeaderText="投票项目" SortExpression="Item" />
  13.                 <asp:TemplateField HeaderText="所占总票的百分比">
  14.                     <ItemStyle Width="300px" />
  15.                     <ItemTemplate>
  16.                         <asp:Image ID="VoteDegree" runat="server" Width="" Height="20px" ImageUrl="~/Images/Vote.gif" />
  17.                     </ItemTemplate>
  18.                 </asp:TemplateField>
  19.                 <asp:BoundField DataField="VoteCount" HeaderText="票数" SortExpression="VoteCount" />
  20.             </Columns>
  21.         </asp:GridView>
  22.         <asp:Label ID="VoteMessage" runat="server" Text="Label"></asp:Label> <asp:Button
  23.             ID="Button1" runat="server" PostBackUrl="~/OnlineVote.aspx" Text="返回继续投票" /><br />
  24.     
  25.     </div>
  26. </form>
  27. ...

6、页面功能设计

  • 投票选项管理(VoteItemManage.aspx.cs)
    1.  ...   
    2.     protected void Page_Load(object sender, EventArgs e)
    3.     {
    4.         if (!Page.IsPostBack)
    5.         {
    6.             BindVoteListData();
    7.         }
    8.     }
    9.     protected void BindVoteListData()
    10.     {
    11.         WebVote.Vote vote = new Vote();
    12.         SqlDataReader rs = vote.GetVotes();
    13.         ItemList.DataTextField = "Item";
    14.         ItemList.DataValueField = "VoteID";
    15.         ItemList.DataSource = rs;
    16.         ItemList.DataBind();
    17.         rs.Close();
    18.     }
    19.     protected void AddBtn_Click(object sender, EventArgs e)
    20.     {
    21.         if (Item.Text.Length > 0)
    22.         {
    23.             WebVote.Vote vote = new Vote();
    24.             try
    25.             {
    26.                 vote.AddVote(Item.Text.Trim());
    27.                 BindVoteListData();
    28.                 Response.Write("<script>alert('" + ASPNET2System.OPERATIONADDSUCCESSMESSAGE + "')</script>");
    29.             }
    30.             catch (Exception ex)
    31.             {
    32.                 Response.Redirect("~/DesktopModules/ErrorPage.aspx?ErrorUrl=" + ASPNET2System.RedirectErrorUrl(Request.RawUrl) + "&ErrorMessage=" + ex.Message.Replace("/n"""));
    33.             }
    34.         }
    35.    
    36.     }
    37.     protected void deleteBtn_Click(object sender, EventArgs e)
    38.     {
    39.         if (ItemList.SelectedIndex <= -1)
    40.         {
    41.             Response.Write("<script>alert('" + ASPNET2System.OPERATIONNOSELECTMESSAGE + "')</script>");
    42.             return;
    43.         }
    44.         WebVote.Vote vote = new Vote();
    45.         try
    46.         {
    47.             vote.DeleteVote(int.Parse(ItemList.SelectedValue));
    48.             BindVoteListData();
    49.         }
    50.         catch (Exception ex)
    51.         {
    52.             Response.Redirect("~/DesktopModules/ErrorPage.aspx?ErrorUrl=" + ASPNET2System.RedirectErrorUrl(Request.RawUrl) + "&ErrorMessage=" + ex.Message.Replace("/n"""));
    53.         }
    54.     }
    55.     ...
  • 在线投票(OnlineVote.aspx.cs)
    1.    ... 
    2.    protected void Page_Load(object sender, EventArgs e)
    3.     {
    4.         if (!Page.IsPostBack)
    5.         {
    6.             BindVoteListData();
    7.             VoteMessage.Visible = false;
    8.         }   
    9.     }
    10.     private void BindVoteListData()
    11.     {
    12.         WebVote.Vote vote = new Vote();
    13.         SqlDataReader rs = vote.GetVotes();
    14.         VoteList.DataSource = rs;
    15.         VoteList.DataBind();
    16.         rs.Close();
    17.     }
    18.     protected void VoteBtn_Click(object sender, EventArgs e)
    19.     {
    20.         WebVote.Vote vote = new Vote();
    21.         try
    22.         {
    23.             //for (int i = 0; i <= VoteList.Rows.Count - 1; i++)
    24.             foreach (GridViewRow row in VoteList.Rows)
    25.             {
    26.                 CheckBox chk = (CheckBox)row.FindControl("VoteCheck");
    27.                 if (chk != null)
    28.                 {
    29.                     if (chk.Checked == true)
    30.                     {
    31.                         vote.UpdateVote(int.Parse(VoteList.DataKeys[row.RowIndex].Value.ToString()));
    32.                         VoteMessage.Visible = true;
    33.                     }
    34.                 }
    35.             }
    36.             Response.Write("<script>window.alert('感谢投票!')</script>");
    37.         }
    38.         catch (Exception ex)
    39.         {
    40.             Response.Redirect("~/DesktopModules/ErrorPage.aspx?ErrorUrl=" + ASPNET2System.RedirectErrorUrl(Request.RawUrl) + "&ErrorMessage=" + ex.Message.Replace("/n"""));
    41.         }
    42.     }
    43.     ...

  • 查看投票结果(ShowVoteResult.aspx.cs)

  1.     ...
  2.     int voteTotal = 0;
  3.     protected void Page_Load(object sender, EventArgs e)
  4.     {
  5.         SetVoteTotal();
  6.         if (!Page.IsPostBack)
  7.         {
  8.             BindVoteListData();
  9.             ShowImageDegree();
  10.             VoteMessage.Text = "总票数:" + voteTotal.ToString() + "票";
  11.         }
  12.     }
  13.     protected void BindVoteListData()
  14.     {
  15.         WebVote.Vote vote = new Vote();
  16.         SqlDataReader rs = vote.GetVotes();
  17.         VoteList.DataSource = rs;
  18.         VoteList.DataBind();
  19.         rs.Close();
  20.     }
  21.     protected void SetVoteTotal()
  22.     {
  23.         WebVote.Vote vote = new Vote();
  24.         SqlDataReader rs = vote.GetVotes();
  25.         voteTotal = 0;
  26.         while (rs.Read())
  27.         {
  28.             voteTotal += int.Parse(rs["voteCount"].ToString());
  29.         }
  30.         rs.Close();
  31.     }
  32.     protected void ShowImageDegree()
  33.     {
  34.         foreach (GridViewRow row in VoteList.Rows)
  35.         {
  36.             Image img = (Image)row.FindControl("VoteDegree");
  37.             if (img != null)
  38.             {
  39.                 //vote.UpdateVote(Int32.Parse(VoteList.DataKeys[row.RowIndex].Value.ToString()));
  40.                 string dw = VoteList.Rows[row.RowIndex].Cells[2].Text.ToString();
  41.                 img.Width = FormatVoteImage(FormatVoteCount(dw));
  42.             }
  43.         }
  44.     }
  45.     public int FormatVoteCount(string voteCount)
  46.     {
  47.         if (voteCount.Length <= 0)
  48.         {
  49.             return (0);
  50.         }
  51.         if (voteTotal > 0)
  52.         {
  53.             return (int.Parse(voteCount) * 100 / voteTotal);
  54.         }
  55.         return (0);
  56.     }
  57.     public int FormatVoteImage(int voteCount)
  58.     {
  59.         return (voteCount * 3);
  60.     }
  61.     ...

 

 

 

 

 

 

7、小结

SQLHelper以及Gridview控件的使用为本系统实现的主要手段。其中,Gridview控件中的遍历数据格的代码是最基础也是最需要掌握的内容。

抱歉!评论已关闭.