Upload
watsontamil
View
66
Download
0
Embed Size (px)
Citation preview
1/5/2015 Creating a Voting Poll with ASP.NET 4.0 and C# ASP.NET Tutorials | Tutorials, Downloads, & Code Examples
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/ 1/9
2
ASP.NET Tutorials | Tutorials, Downloads, &Code Examples
Search Keyword
HomeASP.NET TutorialsASP.NET ResourcesAbout UsContact Us
Creating a Voting Poll with ASP.NET 4.0 and C#
See more tutorials in Advanced. This post has No Comments.
This tutorial will demonstrate how to create an online poll to allow users to vote only once usingASP.NET 4.0 and C#.
For this tutorial we will be creating a simple web page that will show the total votes for two topics ina database and allow the user to vote only one time. To do this, we will be creating a database to keeptrack of how many votes have been counted for each topic and if a user has voted already.
Adding the Default.aspx Page
At this point in the tutorial I have created a new ASP.NET Empty Web Site. Next, we need to add asimple form that will allow a user to login and vote. To do this:
1. Right click the project in your solution explorer.2. Select add new item…3. Select a web form.4. Name it ‘Default.aspx’.5. Click add.6. Open Default.aspx up to design mode.7. Drag and drop a loginview control onto the web form.8. Expand the loginview tasks menu and select AnonymousTemplate from the drop down list.9. Drag and drop a login control into the loginview.10. Underneath the loginview add in a new table that has 2 rows and 2 columns.11. Drag and drop a label into the top left cell of the table.12. Change the ID property of the label to ‘lblA’.13. Drag and drop a label into the top right cell of the table.14. Change the ID property of the label to ‘lblB’.15. Drag and drop a button into the bottom left cell of the table.16. Change the ID property of the button to ‘btnA’.17. Change the Text property of the button to ‘Vote A’.
1/5/2015 Creating a Voting Poll with ASP.NET 4.0 and C# ASP.NET Tutorials | Tutorials, Downloads, & Code Examples
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/ 2/9
18. Drag and drop a button into the bottom right cell of the table.19. Change the ID property of the button to ‘btnB’.20. Change the Text propert of the button to ‘Vote B’.
You should now have a simple form that looks like this:
Adding the Database
Next, we need to add in a database with a few small tables that will allow us to keep track of thevotes. To do this:
1. Right click the project in your solution explorer.2. Select add ASP.NET folder.3. Select App_Data.4. Right click the App_Data folder.5. Select add new item…6. Select a SQL Database.7. Name it ‘Database.mdf’.8. Click add.
Next, we need to add in two tables, one to keep track of the votes and one to keep track of the userswho have already voted. To do this:
1. Expand the Database.mdf folder in your server/database explorer.2. Right click the Tables folder.3. Select add new table.
4. Add the following columns with their respective types to the table:
1/5/2015 Creating a Voting Poll with ASP.NET 4.0 and C# ASP.NET Tutorials | Tutorials, Downloads, & Code Examples
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/ 3/9
Column Name Data TypeVoteIn nvarchar(50)NumVotes int
5. Save the table as ‘Votes’.6. Right click the Tables folder.7. Select add new table.8. Add the following columns with their respective types to the table:
Column Name Data TypeUserName nvarchar(50)
9. Save the table as ‘Voted’.
Adding the ConnectionString
Now that we have our database setup, we need to add a connection string to it. To do this, add in thefollowing code to the Web.Config file in between the and tags:
Enabling and Creating UsersIn order for us to vote, we are going to need to be logged in to an account. To enable user creation andcreate a new user:
1. Click the ASP.NET Configuration icon in your solution explorer.2. In the ASP.NET Web Site Administration Tool click the Security tab.3. Click Select authentication type.4. Select From the internet.5. Click Done.6. Click Create User.7. Fill out the information and create a new account.8. Close the ASP.NET Web Site Administration Tool.
Adding the Voting Functionality
Next, we need to add in some C# code that will allow us to vote if we are logged in and have not yetvoted. To avoid incorrect polls we avoid letting users vote more than one time. Here I am going tolimit their voting by 1 vote per unique username, however we can just as easily limit this another wayby using something like an IP or even a MAC address. To begin, open up Default.aspx.cs up forediting and add the following code to the Page_Load event method:
012
34
<connectionStrings> <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/></connectionStrings>
0123
protected void Page_Load(object sender, EventArgs e){ SqlDataReader rdr;
XHTML
C#
1/5/2015 Creating a Voting Poll with ASP.NET 4.0 and C# ASP.NET Tutorials | Tutorials, Downloads, & Code Examples
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/ 4/9
This code will determine whether or not to enable the voting buttons based on if the user is logged inand has already voted or not. Next, we are going to write a method that will actually submit a Votegiven a VoteId passed by a string to it. To do this, add the following method to the Default.aspx.csclass under the Page_Load method:
456
789101112131415161718192021222324252627282930313233343536
373839404142434445464748495051525354555657585960
//GET # OF VOTES TO DISPLAY //connect to our db SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString //sql command to select everything from the first table SqlCommand cmd = new SqlCommand("SELECT * FROM Votes", conn); cmd.CommandType = CommandType.Text; using (conn) { //connect to the database conn.Open(); //execute the qeury and store the results in our sqldatareader rdr = cmd.ExecuteReader(); //read all entries and populate our labels and buttons while (rdr.Read()) { if (rdr["VoteId"].ToString() == "A") lblA.Text = rdr["NumVotes"].ToString(); if (rdr["VoteId"].ToString() == "B") lblB.Text = rdr["NumVotes"].ToString(); } } //disable the voting buttons until we can verify that the current user is eligible btnA.Enabled = false; btnB.Enabled = false; //if user is currently logged in if (Page.User.Identity.IsAuthenticated) { //check if user is in the database conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString //the sql command to select the current user from the voted table cmd = new SqlCommand("SELECT * FROM Voted WHERE UserName=@UserName", conn cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@UserName", User.Identity.Name); using (conn) { //connect to the database conn.Open(); //execute query and store results in our sqldatareader rdr = cmd.ExecuteReader(); //if no entries are read if (!rdr.Read()) { //user was not found, they are eligible //enable buttons for voting btnA.Enabled = true; btnB.Enabled = true; } } }}
1/5/2015 Creating a Voting Poll with ASP.NET 4.0 and C# ASP.NET Tutorials | Tutorials, Downloads, & Code Examples
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/ 5/9
This will call the Vote method we added earlier, passing the VoteId for option ‘A’ that the user haschosen to vote for. Next, we need to do the same thing for btnB, go back to the Default.aspx anddouble click btnB and add the following code to the btnB_Click event method:
private void Vote(string VoteId){ //ADD THEIR VOTE //connect to our db SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); //command to increment the vote at the proper id SqlCommand cmd = new SqlCommand("UPDATE Votes SET NumVotes = NumVotes+1 WHERE VoteId=@VoteId", conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@VoteId", VoteId); using (conn) { //connect to the database conn.Open(); //execute query cmd.ExecuteNonQuery(); } //ADD THEIR NAME TO THE VOTED DATABASE SO THAT THEY WILL NOT BE ALLOWED TO VOTE AGAIN //connect to our db conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); //command to add their username to out voted table cmd = new SqlCommand("INSERT INTO Voted(UserName) VALUES (@UserName)", conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@UserName", Page.User.Identity.Name); using (conn) { //connect to the database conn.Open(); //execute query cmd.ExecuteNonQuery(); } //reload the page Response.Redirect("Default.aspx");}[csharp]
This will first increment the vote number in the proper cell of the Votes table based on the VoteId passed to it, and then add the current username to the Voted table which gets checked when the voting buttons are enabled. This will prevent the user from voting again. Next, we need to add in the code for the voting buttons. To do this, open up Default.aspx to design mode and double click btnA and add the following code to the btnA_Click event method:
[csharp]protected void btnA_Click(object sender, EventArgs e){ //call the vote method passing the A option Vote("A");
C#
1/5/2015 Creating a Voting Poll with ASP.NET 4.0 and C# ASP.NET Tutorials | Tutorials, Downloads, & Code Examples
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/ 6/9
This will call the Vote method passing the VoteId for option ‘B’.
Testing
To test this out, go ahead and load up the web site. Login to the account that you created earlier andchoose to vote for option ‘A’ by clicking btnA. Notice that the page is reloaded and the buttons arenow disabled even though you are logged in, this is because your account has already voted. Navigateto the Votes table in your database, right click it, and select Show Table Data. Notice that the numberof votes corresponding to option ‘A’ has increased from 39 to 40. This is not the most secure votingsystem, but it is fairly easy to implement and will limit each account to one vote while keeping anaccurate count of all votes.
The Default.aspx source looks like this:
0123456
protected void btnB_Click(object sender, EventArgs e){ //call the vote method passing the B option Vote("B");}
01234567891011121314
151617
1819202122
232425
26272829303132
<body> <form id="form1" runat="server"> <div> <asp:LoginView ID="LoginView1" runat="server"> <AnonymousTemplate> <asp:Login ID="Login1" runat="server"> </asp:Login> </AnonymousTemplate> </asp:LoginView> <br /> <table> <tr> <td> <asp:Label ID="lblA" runat="server" Text="Label"></asp:Label> </td> <td> <asp:Label ID="lblB" runat="server" Text="Label"></asp:Label> </td> </tr> <tr> <td> <asp:Button ID="btnA" runat="server" Text="Vote A" onclick="btnA_Click" /> </td> <td> <asp:Button ID="btnB" runat="server" Text="Vote B" onclick="btnB_Click" /> </td> </tr> </table> </div> </form></body>
C#
XHTML
1/5/2015 Creating a Voting Poll with ASP.NET 4.0 and C# ASP.NET Tutorials | Tutorials, Downloads, & Code Examples
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/ 7/9
Download Source Files
Leave A Response
Name (required)
Mail (will not be published) (required)
Website
Captcha *
Type the text displayed above:
Submit CommentSubscribe To Our FeedFollow Us On Twitter
Navigation
CategoriesPages
33
1/5/2015 Creating a Voting Poll with ASP.NET 4.0 and C# ASP.NET Tutorials | Tutorials, Downloads, & Code Examples
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/ 8/9
AdvancedAjaxBasicsChartsControlsDatabaseEmailError HandlingFileGraphicsInternet BrowsersJavaScriptNetworkPerformanceSyntaxUser Interface and ThemesValidationVisual Web DeveloperWeb ServicesWebsite NavigationXML
Recent
TutorialsComments
Adjust Custom Errors in ASP.NETClear Text Boxes on a Form with C#Create an ASP Panel Bar using Telerik ControlsASPNET Lightbox using Telerik ControlsCreate a Button with Telerik RadControls for ASP.NET AJAX in Visual Basic
Browse
About UsASP.NET TutorialsContact UsSearchASP.NET Resources
About Us
ASPNETTutorials.com is responsible for bringing you an exhaustive list of ASP.NET tutorials thatare easy to follow and simple to implement. Beginners and experts alike will find a great range oftutorials for all your ASP.NET needs.
Learn More About Us
Resources
1/5/2015 Creating a Voting Poll with ASP.NET 4.0 and C# ASP.NET Tutorials | Tutorials, Downloads, & Code Examples
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/ 9/9
.NET 4.0 Tutorials and Code ExamplesAJAX Tutorials and Code ExamplesDatabase Tutorials and ExamplesProgramming Tutorials and Code ExamplesVisual Basic .NET Tutorials and Code ExamplesWeb Development Tutorials and Articles
© 2013 All Rights Reserved