Creating A Voting Poll With ASP - NET 4.0 and C# - ASP PDF
Creating A Voting Poll With ASP - NET 4.0 and C# - ASP PDF
CreatingaVotingPollwithASP.NET4.0andC#ASP.NETTutorials|Tutorials,Downloads,&CodeExamples
ASP.NETTutorials|Tutorials,Downloads,&
CodeExamples
Search Keyword
Home
ASP.NETTutorials
ASP.NETResources
AboutUs
ContactUs
CreatingaVotingPollwithASP.NET4.0andC#
SeemoretutorialsinAdvanced.ThisposthasNoComments.
2
Thistutorialwilldemonstratehowtocreateanonlinepolltoallowuserstovoteonlyonceusing
ASP.NET4.0andC#.
Forthistutorialwewillbecreatingasimplewebpagethatwillshowthetotalvotesfortwotopicsin
adatabaseandallowtheusertovoteonlyonetime.Todothis,wewillbecreatingadatabasetokeep
trackofhowmanyvoteshavebeencountedforeachtopicandifauserhasvotedalready.
AddingtheDefault.aspxPage
AtthispointinthetutorialIhavecreatedanewASP.NETEmptyWebSite.Next,weneedtoadda
simpleformthatwillallowausertologinandvote.Todothis:
1. Rightclicktheprojectinyoursolutionexplorer.
2. Selectaddnewitem
3. Selectawebform.
4. NameitDefault.aspx.
5. Clickadd.
6. OpenDefault.aspxuptodesignmode.
7. Draganddropaloginviewcontrolontothewebform.
8. ExpandtheloginviewtasksmenuandselectAnonymousTemplatefromthedropdownlist.
9. Draganddropalogincontrolintotheloginview.
10. Underneaththeloginviewaddinanewtablethathas2rowsand2columns.
11. Draganddropalabelintothetopleftcellofthetable.
12. ChangetheIDpropertyofthelabeltolblA.
13. Draganddropalabelintothetoprightcellofthetable.
14. ChangetheIDpropertyofthelabeltolblB.
15. Draganddropabuttonintothebottomleftcellofthetable.
16. ChangetheIDpropertyofthebuttontobtnA.
17. ChangetheTextpropertyofthebuttontoVoteA.
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/
1/9
1/5/2015
CreatingaVotingPollwithASP.NET4.0andC#ASP.NETTutorials|Tutorials,Downloads,&CodeExamples
18. Draganddropabuttonintothebottomrightcellofthetable.
19. ChangetheIDpropertyofthebuttontobtnB.
20. ChangetheTextpropertofthebuttontoVoteB.
Youshouldnowhaveasimpleformthatlookslikethis:
AddingtheDatabase
Next,weneedtoaddinadatabasewithafewsmalltablesthatwillallowustokeeptrackofthe
votes.Todothis:
1. Rightclicktheprojectinyoursolutionexplorer.
2. SelectaddASP.NETfolder.
3. SelectApp_Data.
4. RightclicktheApp_Datafolder.
5. Selectaddnewitem
6. SelectaSQLDatabase.
7. NameitDatabase.mdf.
8. Clickadd.
Next,weneedtoaddintwotables,onetokeeptrackofthevotesandonetokeeptrackoftheusers
whohavealreadyvoted.Todothis:
1. ExpandtheDatabase.mdffolderinyourserver/databaseexplorer.
2. RightclicktheTablesfolder.
3. Selectaddnewtable.
4. Addthefollowingcolumnswiththeirrespectivetypestothetable:
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/
2/9
1/5/2015
CreatingaVotingPollwithASP.NET4.0andC#ASP.NETTutorials|Tutorials,Downloads,&CodeExamples
ColumnName DataType
VoteIn
nvarchar(50)
NumVotes
int
5. SavethetableasVotes.
6. RightclicktheTablesfolder.
7. Selectaddnewtable.
8. Addthefollowingcolumnswiththeirrespectivetypestothetable:
ColumnName DataType
UserName
nvarchar(50)
9. SavethetableasVoted.
AddingtheConnectionString
Nowthatwehaveourdatabasesetup,weneedtoaddaconnectionstringtoit.Todothis,addinthe
followingcodetotheWeb.Configfileinbetweentheandtags:
XHTML
0
1 <connectionStrings>
2
<add name="ConnectionString" connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated
Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
3 </connectionStrings>
4
EnablingandCreatingUsers
Inorderforustovote,wearegoingtoneedtobeloggedintoanaccount.Toenableusercreationand
createanewuser:
1. ClicktheASP.NETConfigurationiconinyoursolutionexplorer.
2. IntheASP.NETWebSiteAdministrationToolclicktheSecuritytab.
3. ClickSelectauthenticationtype.
4. SelectFromtheinternet.
5. ClickDone.
6. ClickCreateUser.
7. Fillouttheinformationandcreateanewaccount.
8. ClosetheASP.NETWebSiteAdministrationTool.
AddingtheVotingFunctionality
Next,weneedtoaddinsomeC#codethatwillallowustovoteifweareloggedinandhavenotyet
voted.Toavoidincorrectpollsweavoidlettingusersvotemorethanonetime.HereIamgoingto
limittheirvotingby1voteperuniqueusername,howeverwecanjustaseasilylimitthisanotherway
byusingsomethinglikeanIPorevenaMACaddress.Tobegin,openupDefault.aspx.csupfor
editingandaddthefollowingcodetothePage_Loadeventmethod:
C#
0
1
2
3
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/
3/9
1/5/2015
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
CreatingaVotingPollwithASP.NET4.0andC#ASP.NETTutorials|Tutorials,Downloads,&CodeExamples
Thiscodewilldeterminewhetherornottoenablethevotingbuttonsbasedoniftheuserisloggedin
andhasalreadyvotedornot.Next,wearegoingtowriteamethodthatwillactuallysubmitaVote
givenaVoteIdpassedbyastringtoit.Todothis,addthefollowingmethodtotheDefault.aspx.cs
classunderthePage_Loadmethod:
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/
4/9
1/5/2015
CreatingaVotingPollwithASP.NET4.0andC#ASP.NETTutorials|Tutorials,Downloads,&CodeExamples
C#
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");
ThiswillcalltheVotemethodweaddedearlier,passingtheVoteIdforoptionAthattheuserhas
chosentovotefor.Next,weneedtodothesamethingforbtnB,gobacktotheDefault.aspxand
doubleclickbtnBandaddthefollowingcodetothebtnB_Clickeventmethod:
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/
5/9
1/5/2015
CreatingaVotingPollwithASP.NET4.0andC#ASP.NETTutorials|Tutorials,Downloads,&CodeExamples
C#
0
1 protected void btnB_Click(object sender, EventArgs e)
2 {
3
//call the vote method passing the B option
4
Vote("B");
5 }
6
ThiswillcalltheVotemethodpassingtheVoteIdforoptionB.
Testing
Totestthisout,goaheadandloadupthewebsite.Logintotheaccountthatyoucreatedearlierand
choosetovoteforoptionAbyclickingbtnA.Noticethatthepageisreloadedandthebuttonsare
nowdisabledeventhoughyouareloggedin,thisisbecauseyouraccounthasalreadyvoted.Navigate
totheVotestableinyourdatabase,rightclickit,andselectShowTableData.Noticethatthenumber
ofvotescorrespondingtooptionAhasincreasedfrom39to40.Thisisnotthemostsecurevoting
system,butitisfairlyeasytoimplementandwilllimiteachaccounttoonevotewhilekeepingan
accuratecountofallvotes.
TheDefault.aspxsourcelookslikethis:
XHTML
0
1 <body>
2
<form id="form1" runat="server">
3
<div>
4
<asp:LoginView ID="LoginView1" runat="server">
5
<AnonymousTemplate>
6
<asp:Login ID="Login1" runat="server">
7
</asp:Login>
8
</AnonymousTemplate>
9
</asp:LoginView>
10
<br />
11
<table>
12
<tr>
13
<td>
14
<asp:Label ID="lblA" runat="server" Text="Label">
</asp:Label>
15
</td>
16
<td>
17
<asp:Label ID="lblB" runat="server" Text="Label">
</asp:Label>
18
</td>
19
</tr>
20
<tr>
21
<td>
22
<asp:Button ID="btnA" runat="server" Text="Vote A"
onclick="btnA_Click" />
23
</td>
24
<td>
25
<asp:Button ID="btnB" runat="server" Text="Vote B"
onclick="btnB_Click" />
26
</td>
27
</tr>
28
</table>
29
30
</div>
31
</form>
32 </body>
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/
6/9
1/5/2015
CreatingaVotingPollwithASP.NET4.0andC#ASP.NETTutorials|Tutorials,Downloads,&CodeExamples
33
DownloadSourceFiles
LeaveAResponse
Name(required)
Mail(willnotbepublished)(required)
Website
Captcha*
Typethetextdisplayedabove:
SubmitComment
SubscribeToOurFeed
FollowUsOnTwitter
Navigation
Categories
Pages
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/
7/9
1/5/2015
CreatingaVotingPollwithASP.NET4.0andC#ASP.NETTutorials|Tutorials,Downloads,&CodeExamples
Advanced
Ajax
Basics
Charts
Controls
Database
Email
ErrorHandling
File
Graphics
InternetBrowsers
JavaScript
Network
Performance
Syntax
UserInterfaceandThemes
Validation
VisualWebDeveloper
WebServices
WebsiteNavigation
XML
Recent
Tutorials
Comments
AdjustCustomErrorsinASP.NET
ClearTextBoxesonaFormwithC#
CreateanASPPanelBarusingTelerikControls
ASPNETLightboxusingTelerikControls
CreateaButtonwithTelerikRadControlsforASP.NETAJAXinVisualBasic
Browse
AboutUs
ASP.NETTutorials
ContactUs
Search
ASP.NETResources
AboutUs
ASPNETTutorials.comisresponsibleforbringingyouanexhaustivelistofASP.NETtutorialsthat
areeasytofollowandsimpletoimplement.Beginnersandexpertsalikewillfindagreatrangeof
tutorialsforallyourASP.NETneeds.
LearnMoreAboutUs
Resources
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/
8/9
1/5/2015
CreatingaVotingPollwithASP.NET4.0andC#ASP.NETTutorials|Tutorials,Downloads,&CodeExamples
.NET4.0TutorialsandCodeExamples
AJAXTutorialsandCodeExamples
DatabaseTutorialsandExamples
ProgrammingTutorialsandCodeExamples
VisualBasic.NETTutorialsandCodeExamples
WebDevelopmentTutorialsandArticles
2013AllRightsReserved
http://www.aspnettutorials.com/tutorials/advanced/votepollasp4cs/
9/9