Making simple poll page - c#

I want to do a simple poll page and I have a code that should work but it seems that the .cs file don't want to recognize the gridview
public partial class _Default : System.Web.UI.Page
{
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";
}
}
protected void btnResult_Click(object sender, EventArgs e)
{
readXML();
}
}
the gvResult, radVote, lblStatus all have an error saying that the name doesn't exist in the current context. I have checked the names and everything seems to be fine but still I get this errors.
In the html I have radiobuttonlist, a gridview, one button for voting and one button for showing the results

Your page files may have fallen out of synch with the designer file. Create a new page, move your grid there, and see if that fixes it?
You could manually add declaration of control in the designer file yourself, but this is not recommended.

Or, you can just delete the designer file and have ASP.Net regenerate it. There's a longer explanation here but basically, you just delete the problem .designer.cs file. To regenerate it, click on the .aspx file in Solution Explorer, then click “Convert to Web Application”.

Related

return to main after paying

i have POS system to fastfood, created by c# and sql server.
after the payment process show me window "Order Successfully Paid" after clicking to ok return to form ProductsReceiptPreview again,
i want after payment process go to the form main.
this is my code.......
private void lblPayments_Click(object sender, EventArgs e)
{
if (pnlPayments.Height != lbl.Height)
{
pnlPayments.Height = lbl.Height;
btnDone.Text = "DONE";
lbl.Text = "RECEIPT";
btnDone.Image = Resources.done;
Data.Show();
}
else
{
pnlPayments.Height = 394;
btnDone.Text = "RECEIPT";
lbl.Text = "AMOUNT";
btnDone.Image = Resources.receipt;
Data.Hide();
}
}
private void Touch_Click(object sender, EventArgs e)
{
var btn = (Button)sender;
txtCashReceived.Text += btn.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
if(txtCashReceived.Text.Length >0) txtCashReceived.Text =
txtCashReceived.Text.Remove(txtCashReceived.Text.Length - 1);
}
double totalBill = 0;
private void btnPay_Click(object sender, EventArgs e)
{
if (txtCashReceived.Text.Length > 0 && totalBill <=
Convert.ToInt32(txtCashReceived.Text) && Data.RowCount > 0)
{
int i = 0;
foreach (var rep in ListReports)
{
i++;
var report = new ModelReports();
report.Productname = rep.Productname;
report.TotalSales = rep.TotalSales;
report.TotalTransactions = rep.TotalTransactions;
report.Save();
}
var rpd = new ProductsReceiptPreview(dataReceiptBindingSource,
txtTotal.Text, txtCashReceived.Text, txtChange.Text);
rpd.ShowDialog();
if (i == ListReports.Count)
{
MessageBox.Show("Order Successfully Paid");
}
pnlProducts.Controls.Clear();
pnlCategoryPanel.Visible = false;
dataReceiptBindingSource.Clear();
LoadTables();
btnDone.PerformClick();
}
else
{
MessageBox.Show("Please pay your order.");
txtCashReceived.Text = "0";
}
}
private void btnPay_Click_1(object sender, EventArgs e)
{
if (txtCashReceived.Text.Length > 0 && totalBill <=
Convert.ToInt32(txtCashReceived.Text) && Data.RowCount > 0)
{
int i = 0;
foreach (var rep in ListReports)
{
i++;
var report = new ModelReports();
report.Productname = rep.Productname;
report.TotalSales = rep.TotalSales;
report.TotalTransactions = rep.TotalTransactions;
report.Save();
}
if (i == ListReports.Count)
{
MessageBox.Show("Order Successfully Paid");
txtCashReceived.Text = "0";
}
pnlProducts.Controls.Clear();
pnlCategoryPanel.Visible = false;
dataReceiptBindingSource.Clear();
LoadTables();
btnDone.PerformClick();
}
else
{
MessageBox.Show("Please pay your order.");
}
}
If you call some code from main then it will return to main when the call is finished. In the case of a Form, it's handled on a different thread started from main. The thread will never return back to main in this context. If you are using a click event to do some action and want to call some other code when that happens, then you need to re-design your infrastructure. Look into SOLID development principles and dependency injection.
https://www.codeproject.com/Tips/1033646/SOLID-Principle-with-Csharp-Example
https://simpleinjector.readthedocs.io/en/latest/windowsformsintegration.html

Removing an item from a listbox in C#

Hello I'm trying to click a button to remove and item but I keep getting an
'IndexOutOfRange' Exception.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
clientNum = clientList.Items.Count;
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
if (dateSeletion[clientList.SelectedIndex] != null)
{
dateCalender.SelectionStart = todayDate[clientList.SelectedIndex];
Check();
}
else
{
nameLbl.Text = nameSeletion[clientList.SelectedIndex];
dateText.Text = "";
}
}
The if (dateSeletion[clientList.SelectedIndex] != null) is where I'm having the error.
The button code is
private void button1_Click(object sender, EventArgs e)
{
clientList.Items.Remove(clientList.Items[clientList.SelectedIndex]);
}
the dateSelection is defined in the save button and Initialization
private void SaveBtn_Click(object sender, EventArgs e)
{
//save the list array for names
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
dateSeletion[clientList.SelectedIndex] = dateCalender.SelectionStart.Date.ToShortDateString() +
" " + clientTime.Value.ToShortTimeString();
todayDate[clientList.SelectedIndex] = dateCalender.SelectionStart;
dateCalender.BoldedDates = todayDate;
Check();
}
public ClientForm()
{
InitializeComponent();
clientNum = clientList.Items.Count;
todayDate = new DateTime[clientNum];
dateSeletion = new string[clientNum];
nameSeletion = new string[clientNum];
clientTime.CustomFormat = "hh:mm tt";
//initialize the list array for names
for (int i = 0; i < clientNum; i++)
{
nameSeletion[i] = clientList.Items[i].ToString();
}
}
Try this
clientList.RemoveAt(clientList.SelectedIndex);

how to add and catch event of linkbutton inside the gridview by dynamically

<asp:GridView ID="grid_planningStaff" runat="server"
AutoGenerateColumns="false"
OnRowCommand="yourgridview_RowCommand"
CssClass="table_style01 table100"
BorderWidth="3px"
ForeColor="Black"
OnRowDataBound="grid_planning_RowdataBound">
protected void grid_planning_RowdataBound(object sender, GridViewRowEventArgs e)
{
//try
//{
if (e.Row.RowType != DataControlRowType.Header)
{
DataSet ds = new DataSet();
planningStaffCommon.StaffID = sid;
ds = objDALPlanningModule.GetStaffMeetingData(planningStaffCommon);
if (ds.Tables[0].Rows.Count > 0)
{
for (int J = 0; J < ds.Tables[0].Rows.Count; J++)
{
dateofcell = Convert.ToString(ds.Tables[0].Rows[J]["FromDate"]);
from = Convert.ToInt16(ds.Tables[0].Rows[J]["datea"]);
string clientids = Convert.ToString(ds.Tables[0].Rows[J]["MeetingType"]);
colorvalue = Convert.ToInt32(ds.Tables[0].Rows[J]["ColorValues"]);
//set Color
if (colorvalue == 1)
{
//DataSet dscolor = new DataSet();
//objDALPlanningModule._dtLOVDescription=clientids;
//dscolor=objDALPlanningModule.GetParaMeterDetailsDAL();
//if (dscolor.Tables[0] != null)
//{
// setcolor = Convert.ToString(dscolor.Tables[0].Rows[0]["Value"]);
//}
//else
//{
//break
//}
if (clientids == "Test Value1")
{
setcolor = "GREEN";
}
else
if (clientids == "Testy Value2")
{
setcolor = "ORANGE";
}
else
{
setcolor = "RED";
}
}
else
{
setcolor = "Aqua";
}
//color and fill clients
for (int i = from; i <= from; i++)
{
LinkButton lkBtn = new LinkButton();
lkBtn.ForeColor = Color.Black;
lkBtn.Font.Underline = false;
lkBtn.ID = "link_button" + i;
lkBtn.Text = clientids;
lkBtn.CommandName = "Edit";
//lkBtn.OnClientClick = "Edit";
//lkBtn.Click += ViewDetails;
HiddenField hdndate = new HiddenField();
hdndate.ID = "hdn" + i;
hdndate.Value = dateofcell;
e.Row.Cells[i].Controls.Add(hdndate);
e.Row.Cells[i].BackColor = Color.FromName(setcolor);
e.Row.Cells[i].Controls.Add(lkBtn);
}
}
}
//hide other extra created rows
for (int i = 1; i < grid_planningStaff.Rows.Count; i++)
{
grid_planningStaff.Rows[0].Visible = true;
grid_planningStaff.Rows[i].Visible = false;
}
}
//}
//catch (Exception)
//{
// throw;
//}
}
protected void yourgridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
this.FindControl("grdwv" + e.CommandArgument).Visible = false;
//i am assuming other gridview is on your .aspx page
}
}
Assuming you want to bind to an event on click, you just bind the method to the lkBtn.Click event:
LinkButton lkBtn = new LinkButton();
lkBtn.ForeColor = Color.Black;
lkBtn.Font.Underline = false;
lkBtn.ID = "link_button" + i;
lkBtn.Text = clientids;
lkBtn.CommandName = "Edit";
lkBtn.Click +=button_Click;
The method to handle the event:
void button_Click(object sender, EventArgs e)
{
//add code here for the button
}

DataGridView Rows Count 0 After Event Handler

I have run into a very strange issue dynamically building a DataGridView and a group of radio buttons. I have a group of radio buttons and a DataGridView inside of a Panel. The issue I am running into is I am trying to get the number of rows in the DataGridView using an event handler on some radio buttons. The DataTable I am using has 3 rows. You can recreate this problem manually adding rows to the DGV, it doesn't matter. When I call the rows.count after I initialize the DataGridView it works as planned and returns 3 but when an EventHandler is fired the row count returned is 0. My code is as follows:
private DataSet testData;
private DataTable testDataTable;
public Form1(API _api)
{
InitializeComponent();
api = _api;
businessLayer = new BusinessLayer();
testData = api.getDataSet();
testDataTable = businessLayer.getDataTable(testData);
buildDataGridView();
}
// Build the DataGridView
private void buildDataGridView()
{
int numOfRows = testDataTable.Rows.Count;
DataGridView testDataGridView = new DataGridView();
testDataGridView.Columns.Add("Description", "");
testDataGridView.Columns.Add("Name", "");
testDataGridView.Rows.Add(numOfRows);
testDataGridView.Location = new Point(150, 20);
for (int i = 0; i < numOfRows; i++)
{
RadioButton rbutton = new RadioButton();
rbutton.Name = testDataTable.Rows[i].Field<string>("Name").ToString() + "RadioButton";
rbutton.Text = testDataTable.Rows[i].Field<string>("Name");
rbutton.Tag = testDataTable.Rows[i].Field<string>("SortOrder");
rbutton.CheckedChanged += rbutton_CheckedChanged;
if (i == 0)
{
rbutton.Checked = true;
}
rbutton.Location = new Point(5, 20 * (i + 1));
testPanel.Controls.Add(definition);
}
testPanel.Controls.Add(testDataGridView);
textBox1.Text = testDataGridView.Rows.Count.ToString();
}
// RadioButton CheckChanged EventHandler
private void definition_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
if(rb.Checked)
{
textBox1.Text = testDataGridView.Rows.Count.ToString();
}
}
This has really got me confused but if I figure it out I am bound to learn something here. I don't know if this has something to do with the fact that the DGV and the radio buttons are inside of a Panel, I don't know...Thanks for any help with this and helping me learn!
As Grant Winney explained in a comment the DataGridView referenced in buildDataGridView() and the one referenced in definition_CheckedChanged() are not the same...an example of memory heap and memory stack. Here is a more simple example of what I was trying to do:
public partial class TestingForm2 : Form
{
private DataTable testDataTable;
// Must Declare here so the value is stored in heap memory
// so other functions can access and use the value
private DataGridView testDataGridView;
public TestingForm2()
{
InitializeComponent();
buildDataTable();
buildDataGridView();
buildRadioButtons();
}
private void buildRadioButtons()
{
int numOfRadioButtons = testDataTable.Rows.Count;
for(int i = 0; i < numOfRadioButtons; i++)
{
RadioButton rb = new RadioButton();
rb.Name = testDataTable.Rows[i].Field<string>("Name") + "RadioButton";
rb.Text = testDataTable.Rows[i].Field<string>("Name");
rb.Tag = testDataTable.Rows[i].Field<string>("Number");
if(i == 0)
{
rb.Checked = true;
}
rb.Location = new Point(5, 20 * (i + 1));
rb.CheckedChanged += rb_CheckedChanged;
panel1.Controls.Add(rb);
}
}
private void buildDataGridView()
{
// Get number of rows in testDataTable
int numOfRows = testDataTable.Rows.Count;
// Build the empty DGV
// If I were to declare the DGV here the value given would have
// been stored in the memory stack and could only be accessed by
// this function. This is where I went wrong and made a silly mistake
testDataGridView = new DataGridView();
testDataGridView.Columns.Add("Name", "");
testDataGridView.Columns.Add("Number", "");
testDataGridView.Rows.Add(numOfRows);
testDataGridView.Location = new Point(150, 20);
testDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
testDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
testDataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
testDataGridView.AllowUserToAddRows = false;
testDataGridView.AllowUserToDeleteRows = false;
testDataGridView.MultiSelect = false;
testDataGridView.ColumnHeadersVisible = false;
testDataGridView.RowHeadersVisible = false;
panel1.Controls.Add(testDataGridView);
}
private void buildDataTable()
{
testDataTable = new DataTable();
// Add the Columns
testDataTable.Columns.Add("Name");
testDataTable.Columns.Add("Number");
// Create and add the rows
for (int i = 0; i < 3; i++)
{
// Create the new row
DataRow dr;
object[] rowItems = new object[testDataTable.Columns.Count];
if (i == 0)
{
rowItems[0] = "Bob";
rowItems[1] = "1";
}
else if (i == 1)
{
rowItems[0] = "John";
rowItems[1] = "2";
}
else
{
rowItems[0] = "George";
rowItems[1] = "3";
}
// Add the row
dr = testDataTable.NewRow();
dr.ItemArray = rowItems;
testDataTable.Rows.Add(dr);
}
}
private void TestingForm2_Load(object sender, EventArgs e)
{
textBox1.Text = testDataGridView.Rows.Count.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = testDataGridView.Rows.Count.ToString();
}
private void rb_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
int index = int.Parse(rb.Tag.ToString()) - 1;
if (rb.Checked)
{
testDataGridView.Rows[index].Selected = true;
}
}
}
Sorry for the mistake everyone! Thanks for the help!

Redirect on select click in gridview

I have 2 GridViews with select rows enabled in my form. Can someone help me on coding where it can redirect to a different form on a click of a select in GridView instead of a button click (like I have coded)?
namespace TicketsApp
{
public partial class SearchTickets : System.Web.UI.Page
{
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["TicketsConnectionString"].ConnectionString;
ArrayList selectedSportEvent = new ArrayList();
protected void btnSearch_Click1(object sender, EventArgs e)
{
DataAccess myData = new DataAccess();
ArrayList parameters = new ArrayList();
//Updates the selected by the dates specified
SqlDataReader results;
parameters.Add(new SqlParameter("#StartDate", CalStartDate.SelectedDate));
parameters.Add(new SqlParameter("#EndDate", CalEndDate.SelectedDate));
results = myData.GetDataReader("SearchTickets", connect, parameters);
//Clear sort expression
grdSearch.DataSourceID = String.Empty;
this.grdSearch.DataSource = results;
this.grdSearch.DataBind();
//makes gridview Search visible
grdSearch.Visible = true;
grdUpdated.Visible = false;
//make sure the dates are selected
if (CalStartDate.SelectedDate < DateTime.Today || CalEndDate.SelectedDate < DateTime.Today)
{
CalStartDate.Focus();
return;
}
if (CalEndDate.SelectedDate < DateTime.Today)
{
lblCalError.Visible = true;
return;
}
}
protected void btnUpdate_Click1(object sender, EventArgs e)
{
DataAccess myData = new DataAccess();
ArrayList parameters = new ArrayList();
//updates the selection by the sport selected
SqlDataReader results;
parameters.Add(new SqlParameter("#SportName", ddlSportType.SelectedItem.ToString()));
results = myData.GetDataReader("SearchTicketsBySport", connect, parameters);
//Clear sort expression
grdUpdated.DataSourceID = String.Empty;
this.grdUpdated.DataSource = results;
this.grdUpdated.DataBind();
//Makes gridview updated visible
grdUpdated.Visible = true;
grdSearch.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session.Remove("EventData");
}
CalStartDate.SelectedDate = DateTime.Today;
CalEndDate.SelectedDate = DateTime.Today;
}
//Adds the item selected to the array
protected void grdSearch_SelectedIndexChanged(object sender, EventArgs e)
{
selectedSportEvent.Clear();
int x;
for (x = 1; x < grdSearch.SelectedRow.Cells.Count; x++)
{
int selectedRow = grdSearch.SelectedIndex;
GridViewRow r = grdSearch.Rows[selectedRow];
Session["EventID"] = r.Cells[1].Text;
Session["description"] = r.Cells[2].Text;
Session["ticketcost"] = r.Cells[7].Text;
Session["numtickets"] = r.Cells[6].Text;
Session["State"] = r.Cells[9].Text;
Session["Section"] = r.Cells[4].Text;
Session["Row"] = r.Cells[5].Text;
Session["date"] = r.Cells[8].Text;
}
}
//Adds the item selected to the array
protected void grdUpdated_SelectedIndexChanged(object sender, EventArgs e)
{
selectedSportEvent.Clear();
int x;
for (x = 1; x < grdUpdated.SelectedRow.Cells.Count; x++)
{
int selectedRow = grdUpdated.SelectedIndex;
GridViewRow r = grdUpdated.Rows[selectedRow];
Session["EventID"] = r.Cells[1].Text;
Session["description"] = r.Cells[2].Text;
Session["ticketcost"] = r.Cells[7].Text;
Session["numtickets"] = r.Cells[6].Text;
Session["State"] = r.Cells[9].Text;
Session["Section"] = r.Cells[4].Text;
Session["Row"] = r.Cells[5].Text;
Session["date"] = r.Cells[8].Text;
}
}
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
//Redirects to TicketOrder form
Response.Redirect("TicketOrder.aspx");
}
protected void CalStartDate_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date < (System.DateTime.Now.AddDays(-1)))
{
e.Day.IsSelectable = false; e.Cell.Font.Strikeout = true;
}
}
}
}

Categories