CheckBoxList控件用法实现投票实例

来源:互联网 发布:万网阿里云 编辑:程序博客网 时间:2024/04/30 02:23

ASP.NET的控件分为四类:内部控件、复杂控件、列表控件和验证控件

其中内部控件的使用方法和HTML控件的相似,通过使用runat="server"属性在服务器上执行。

列表控件用于创建数据列表,标准的列表控件有Repeater,DataList和DataGrid。

复杂控件完成的功能相对来说比较复杂,具体的使用后面的博客在详细介绍。

验证控件一般在客户端脚本上执行。

下面详细介绍关于CheckBoxList控件的使用

CheckBoxList控件的作用:为数据库中的数据创建一组复选框

绑定数据时的用法:

1、  this.CheckBoxList1.DataTextField=””;表示显示在前台看到的值,也即在控件中显示的值。

2、  this.CheckBoxList1.DatavalueField=””;表示隐藏的值,在前台看不见只能在源代码中查看。

SqlDataReader sdr = cmdItem.ExecuteReader();this.rBtnItems.DataSource = sdr;this.rBtnItems.DataTextField = "voteItem";this.rBtnItems.DataValueField = "voteDetailsID";this.rBtnItems.DataBind();

投票实例:

数据库设计:



项目设计:


vote.aspx窗体界面如下:


创建一个DB类,连接服务器操作:

SqlConnection con = new SqlConnection("server=192.168.24.155;database=vote;uid=sa;pwd=123456;");            return con;当窗体第一次加载的时候首先在label中显示需要投票的标题://创建连接  SqlConnection con = DB.createConnection();  con.Open();//创建命令对象  SqlCommand cmd = new SqlCommand("select voteTitle from voteMaster where voteID="+this.voteID,con);//查询选举的标题  string title = Convert.ToString(cmd.ExecuteScalar());  this.lblTitle.Text = title;(添加引用using System.Data.SqlClient;)

然后查询对应的投票条目:

//创建一个新的命令对象SqlCommand cmdItem = new SqlCommand("select voteDetailsID,voteItem from voteDetails where voteID=" + this.voteID, con);SqlDataReader sdr = cmdItem.ExecuteReader();

将查询的结果在控件中显示出来,然后关闭连接:

//绑定数据源 this.rbtnItems.DataSource = sdr; this.rbtnItems.DataTextField = "voteItem"; this.rbtnItems.DataValueField = "voteDetailsID"; this.DataBind();sdr.Close();con.Close();

点击投票按钮,将对应的票数加1,然后将总票数加1。

由于外键的作用,做到联合表的操作,需要使用触发器:

create trigger [dbo].[updateMaster]on [dbo].[voteDetails]for updateasbegin    update voteMaster set voteSum=voteSum+1 where voteID=(select top 1 voteID from inserted)endGO
代码编写:

SqlConnection con = DB.createConnection();con.Open();SqlCommand cmd = new SqlCommand();cmd.Connection = con;cmd.CommandText = "update voteDetails set voteNum=voteNum+1 where voteID="+voteID+" and voteDetailsID="+this.rbtnItems.SelectedValue.ToString();cmd.ExecuteNonQuery();con.Close();

点击“结果”按钮,将直接跳转到显示结果的界面:

Response.Redirect("showResult.aspx?voteid="+this.voteID);

这里采用get的提交表单的方式

在showResult.aspx页中显示结果,通过Request.QueryString获得voteID。

string voteID=Request.QueryString["voteid"].ToString();SqlConnection con = DB.createConnection();//查询对应的投票条目SqlCommand cmdItem = new SqlCommand("select * from voteDetails where voteID="+voteID,con);SqlDataReader sdr = cmdItem.ExecuteReader();while(sdr.Read()){     Response.Write("<font size=15>" +sdr.GetString(2)+"-"+sdr.GetInt32(3).ToString()+"</font><br>");}   sdr.Close();

到这里,整个投票的小例子就已经完成了,最后的结果:




在对待通过条件查询数据库的时候采用拼接字符串的形式,在一定程度会导致SQL注入,关于这部分的内容上篇博客已经介绍了,这里不详细讲了。


0 0
原创粉丝点击