Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

how to create online poll system with percentage graphs using asp.net

Jan 9, 2011
Introduction

Here I will explain how to create online poll system with percentage graphs using asp.net.

Description:

In many websites we will see online polls like which browser is best browser? We can submit our votes to these polls and they will display result with graphs after seen all these polls I tried to implement simple application for online polls with percentage graphs using as.net.
Here I am using XML to store all the poll options and retrieving all the options and displaying result based on polls options. Here I need to say one thing before implement this application I don’t know the exact purpose of XML whenever I implement this application I got idea regarding XML. XML is used to store the data and we can use it in any application and it will support for all the languages. Here I explained clearly how to insert and retrieve data from XML and how to bind that data to repeater

Here in my application I used only simple table concepts to display graphs I didn’t used any graph tools let see how I implemented

Design your aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<style type="text/css">

.ButtonStyle {
background-color: #9EBEDE;
color: Black;
font-family: verdana;
font-size: 8pt;

}
.BarStyle
{

background-color: #996633;
}
.TablePollResultFoot
{
background-color: #B0C4DE;
font-weight: bold;
height:30px;
font-size: 13px;
}
.gridview
{
border: solid 1px #CCCCCC;
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="border:1px solid #9EBEDE" align="center" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td  align="left">
<b><span style="color:#FF6600"> Online Poll Example with XML </span>  </b>
</td>
</tr>
<tr>
<td height="10px"></td>
</tr>
<tr>
<td  >
<b>which one is best browser?</b>
</td>
</tr>
<tr>
<td height="5px"></td>
</tr>
<tr>
<td align="left">
<asp:RadioButtonList ID="radVote" runat="server">
<asp:ListItem>Mozilla</asp:ListItem>
<asp:ListItem>Internet Explorer</asp:ListItem>
<asp:ListItem>Google Chrome</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<asp:Button ID="btnVote" runat="server" Text="Vote"
onclick="btnVote_Click" CssClass="ButtonStyle" />
<asp:Button ID="btnResult" runat="server" Text="Reult" CssClass="ButtonStyle"
onclick="btnResult_Click" />
<br />
<asp:Label ID="lblStatus" runat="server" />
</td>
</tr>
<tr>
<td align="left">
<asp:GridView runat="server" ID="gvResult" BackColor="White" CellPadding="4"
EnableModelValidation="True" AutoGenerateColumns="false"
onrowdatabound="gvResult_RowDataBound" EmptyDataText="No one submit votes">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#4682B4" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />

<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<Columns>
<asp:TemplateField HeaderText="Options" HeaderStyle-HorizontalAlign="Left"  ItemStyle-Width="20%">
<ItemTemplate>
<asp:Label ID="lblOptions" runat="server" Text='<%#Bind("OPTION_NAME") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Votes" HeaderStyle-HorizontalAlign="Left"  ItemStyle-Width="10%">
<ItemTemplate>
<asp:Label ID="lblVotes" runat="server" Text='<%#Bind("VOTES") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="%" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="lblpercentage" runat="server" Text='<%#Bind("PERCENTAGE","{0:f2}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bar" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="55%" >
<ItemTemplate>
<table runat="server" id="tblBar">
<tr class="BarStyle"><td height="8px"></td></tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
After that add XML file to your application and give name as "Votes.xml" intially xml file like this root element is compulsory for XML files that’s why I added CommentInformation in XML file that root element in XML file.

<?xml version="1.0" encoding="utf-8"?>
<VotesInformation>
 </VotesInformation>
After that add this namespace in codebehind


using System.Xml;
using System.Drawing;
After that write the following code in code behind


int Count = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnVote_Click(object sender, EventArgs e)
{
if (radVote.SelectedItem != null)
{
InsertVotes(radVote.SelectedItem.ToString());
}
else
{

lblStatus.ForeColor = Color.Red;
lblStatus.Text = "Please select at least one option to vote for poll";
}
}

protected void InsertVotes(string theVote)
{
try
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("Votes.xml"));
XmlElement parentelement = xmldoc.CreateElement("Vote");
XmlElement votechoice = xmldoc.CreateElement("Choice");
votechoice.InnerText = theVote;
parentelement.AppendChild(votechoice);
xmldoc.DocumentElement.AppendChild(parentelement);
xmldoc.Save(Server.MapPath("Votes.xml"));
lblStatus.ForeColor = Color.Green;
lblStatus.Text = "Thank you for your vote.";
}

catch
{
lblStatus.Text = "Sorry, unable to process request. Please try again.";
}
}

protected void readXML()
{
int mCount=0;
int iCount=0;
int gCount=0;
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Votes.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count>0)
{
int dscount = ds.Tables[0].Rows.Count;
for (int i = 0; i < dscount; i++)
{
if (ds.Tables[0].Rows[i][0].ToString() == "Mozilla")
mCount++;
else if (ds.Tables[0].Rows[i][0].ToString() == "Internet Explorer")
iCount++;
else if (ds.Tables[0].Rows[i][0].ToString() == "Google Chrome")
gCount++;
}
double theTotal;
theTotal = mCount + iCount + gCount;
double mPercent;
double oPercent;
double gPercent;
mPercent = (mCount / theTotal) * 100;
oPercent = (iCount / theTotal) * 100;
gPercent = (gCount / theTotal) * 100;
double totalpercentage = mPercent + oPercent + gPercent;
string[] votescount = { mCount.ToString(), iCount.ToString(), gCount.ToString() };
string[] array = { mPercent.ToString(), oPercent.ToString(), gPercent.ToString() };
DataTable dt = new DataTable();
dt.Columns.Add("OPTION_NAME");
dt.Columns.Add("VOTES");
dt.Columns.Add("PERCENTAGE");
int count = radVote.Items.Count;
Count = count + 1;
for (int i = 0; i < count; i++)
{
dt.Rows.Add();
dt.Rows[i]["OPTION_NAME"] = radVote.Items[i].ToString();
dt.Rows[i]["VOTES"] = votescount[i];
dt.Rows[i]["PERCENTAGE"] = array[i];
}
dt.Rows.Add("Total", theTotal, totalpercentage);
gvResult.DataSource = dt;
gvResult.DataBind();
}
else
{
gvResult.DataSource = null;
gvResult.DataBind();
}

}

protected void butResults_Click(object sender, EventArgs e)
{
readXML();
}
int cnt = 0;
protected void gvResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
cnt++;
Label lblpercent = (Label)e.Row.FindControl("lblpercentage");
HtmlTable tblpercent = (HtmlTable)e.Row.FindControl("tblBar");
tblpercent.Width = lblpercent.Text+"%";
if (lblpercent.Text == "0")
{
tblpercent.Visible = false;
}

if (cnt == Count)
{
e.Row.CssClass = "TablePollResultFoot";
}
}
foreach (TableCell tc in e.Row.Cells)
{
tc.Attributes["style"] = "border-color:#CCCCCC";
}
}
Demo


Download sample code attached



If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

16 comments :

Anonymous said...

nice post but i need to show graph without using XML and record will be bind from the database and to show graph on the percentage of vote.
http://soft-engineering.blogspot.com

Anonymous said...

this code not working
error in web.config i m using vs2010

Suresh Dasari said...

hi i did this example in vs 2008 if you open this application with vs 2010 it will ask you to convert higher version so at that time version problem will arise to avoid that problem you should create new website in vs2010 and copy and paste the aspx page and code behind code in your website and use your own website web.config file and follow my instructions it will work for you

madanforall said...

it is not working in online sir did u give suggestion?

Suresh Dasari said...

hi madhan for me it's working fine r u getting any error after deploy the application

Anonymous said...

Hi Suresh,

I keep getting the "Sorry, unable to process request. Please try again." error and it's not inserting my vote into the xml file. Is there something I can do to get it to work?

Thanks - Jude

Anonymous said...

Thanks for Sharing .. Nice Post.... May i know how to prevent a particular User voting again and again?
eg -:only prevent using Cookies.(Without Login )

er.Ashok said...

add more namespace
using System.Data;
using System.Web.UI.HtmlControls;

then it is work perfectly.
thanks

Unknown said...

Great Post man keep rocks.....

Anonymous said...

greatt Post....

but if i need to store data in sql server then how to do this can you give example

Create Poll on Facebook said...

This blog is definitely awesome as well as informative. I have found a bunch of useful things out of it. Thanks a lot!

Anonymous said...

thnks

Unknown said...

Not working Server but local system working fine..
error says 'Sorry, unable to process request. Please try again' pls help me

Unknown said...

can u post this article using sql server Database ..............suresh Sir plz

Anonymous said...

this example is for student only.

Anonymous said...

This is very good. I found a problem in that "btnResults" in html had "butResults" in code behind, but when fixed, the page and functionality was fine. Thank you for your examples!

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.