I have a program where a user fills in a form and hits calculate, then when the user hits summary it will show all the users that have entered in data. When more users enter data, they are simply added to the summary using the same lbl (lblUsers) the only problem I am having is being able to delete the most recent entry into the summary which would be the newest made label.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LifeInsurance
{
public partial class frmMain : Form
{
double commissionRate;
double insuranceAmount;
double totalAmount;
int numberOfCustomers;
double totalInsuranceDollars;
double totalCommission;
private void btnClearAll_Click(object sender, EventArgs e)
{
lblUsers.Text = "";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
insuranceAmount = int.Parse(txtInsuranceAmount.Text);
}catch (Exception)
{
MessageBox.Show("You must enter all details");
}
if(insuranceAmount>= 1000)
{
commissionRate = 0.005;
totalAmount = insuranceAmount * 0.005;
}
if (insuranceAmount >= 100000)
{
commissionRate = 0.0010;
totalAmount = insuranceAmount * 0.0010;
}
if (insuranceAmount >= 1000000)
{
commissionRate = 0.0015;
totalAmount = insuranceAmount * 0.0015;
}
totalInsuranceDollars += totalAmount;
totalCommission += commissionRate;
numberOfCustomers += 1;
lblUsers.Text += "Name: "+txtFirstName.Text +" "+ txtLastName.Text+"
"+ "Payout Amount: "+totalAmount+Environment.NewLine;
lblUsers.Text += "Total Policies: " + numberOfCustomers+" " + "Total
Insurance Dollars Earned: " + totalInsuranceDollars+" " + "Total
Commission Earned: " + totalCommission+Environment.NewLine;
}
private void btnSummary_Click(object sender, EventArgs e)
{
lblUsers.Visible = true ;
}
private void btnClear_Click(object sender, EventArgs e)
{
//remove one label
}
}
}
I'm sorry, if I understand correctly you want your Label to show all but the last entry when the user clicks "Summary" is that correct? So in your screenshot it shows 3 entries, but you want only 2 entries to be shown?
If so, see if this helps:
public static void btnSummary_Click(object sender, EventArgs e)
{
string currentText = lblUsers.Text;
int positionOfLastEntry = currentText.LastIndexOf("Name:");
string textWithoutLastEntry = currentText.Substring(0, positionOfLastEntry);
lblUsers.Text = textWithoutLastEntry;
lblUsers.Visible = true;
}
Related
So I'm trying to make a simple banking website using C# and ASP.net and I'm just learning about Session Variables for the first time. I have a starting account balance of 1000 dollars and I want to transfer that to another page and have that balance updated via withdrawals or deposits and then update the balance. Heres my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project4.Forms
{
public partial class Services : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click1(object sender, EventArgs e)
{
double userInput = double.Parse(txtAmount.Text);
Session["userInput"] = userInput;
Session["balance"] = 1000.00;
double balance = Convert.ToDouble(Session["balance"]);
Session["userAction"] = ddlSelectService.SelectedItem.Text;
if (ddlSelectService.SelectedItem.Text == "Withdrawl")
{
balance -= userInput;
}
else if (ddlSelectService.SelectedItem.Text == "Deposit")
{
balance += userInput;
}
else
{
}
Response.Redirect("Status.aspx");
}
}
}
I understand the root of my problem is probably the original Session["balance"] = 1000.00; but I'm not sure how to declare a starting amount and then it not affect the balance when I return to this page from the results page. Any help is appreciated, also as I said in the beginning this is a barebones simple atm website please don't suggest anything too crazy because I am a beginner.
I don't do asp.net, so this is just a guess, but maybe try only setting the default value if it's null, something like: if (Session["balance"] == null) Session["balance"] = 1000;. It also seems like this should be in the Page_Load event, not the btnSubmit_Click event, since it only has to happen once.
Finally, don't forget to update the session variable after setting the new balance:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["balance"] == null) Session["balance"] = 1000;
}
protected void btnSubmit_Click1(object sender, EventArgs e)
{
double userInput;
if (!double.TryParse(txtAmount.Text, out userInput))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert",
"alert('Input must be a valid double');", true);
return;
}
Session["userInput"] = userInput;
double balance = Convert.ToDouble(Session["balance"]);
Session["userAction"] = ddlSelectService.SelectedItem.Text;
if (Session["userAction"] == "Withdrawl")
{
balance -= userInput;
}
else if (Session["userAction"] == "Deposit")
{
balance += userInput;
}
Session["balance"] = balance;
Response.Redirect("Status.aspx");
}
I am trying to get the cell value in a string from the selected cell in the "Document Number" column in a DataGridView. My code to retrieve data from SharePoint and populate the DataGridView works fine, but I seem to be caught in a loop there? I cannot execute any other methods after populating the DataGridView . I can select a new search term and execute the Button1_Click event again successfully, but I cannot get any other methods to execute?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace BuyersForeverFriend
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string userSearch = textBox1.Text;
button1.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
using (ClientContext ctx = new ClientContext("https://teamsites.nafta.fcagroup.com/sites/PSOAPPS/iws/"))
{
var userInput = textBox1.Text;
Web web = ctx.Web;
List list = web.Lists.GetById(new Guid("61ef6657-eff7-42cb-99e1-8afd590334ec"));
var q = new CamlQuery() { ViewXml = "<View><Query><Where><Contains><FieldRef Name='Item_x0020_Description' /><Value Type='Note'>" + userInput + "</Value></Contains></Where></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Topic_x002d_' /><FieldRef Name='Item_x0020_Description' /></ViewFields><QueryOptions /></View>" };
var r = list.GetItems(q);
ctx.Load(r);
ctx.ExecuteQuery();
if (r.Count != 0)
{
var searchResults = new DataTable();
searchResults.Columns.AddRange(new[]
{
new DataColumn("ID"), new DataColumn("Document Number"), new DataColumn("Item Description"), new DataColumn("Topic")});
foreach (var oListItem in r)
{
searchResults.Rows.Add(oListItem["ID"], oListItem["Title"], oListItem["Item_x0020_Description"],
oListItem["Topic_x002d_"]);
}
if (dataGridView1 != null)
{
dataGridView1.DataSource = searchResults;
dataGridView1.Refresh();
dataGridView1.Columns[2].DefaultCellStyle.Format = "dd'/'MM'/'yyyy";
var dataGridViewColumn = dataGridView1.Columns["ID"];
if (dataGridViewColumn != null)
dataGridViewColumn.Visible = false;
}
else
MessageBox.Show("after else statement");
}
}
MessageBox.Show("after sharepoint if statement");
return;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("a cell was clicked");
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
MessageBox.Show("starting routine");
if (dataGridView1.SelectedCells.Count > 0)
{
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
string a = Convert.ToString(selectedRow.Cells["Document Number"].Value);
MessageBox.Show(a);
textBox2.Text = ("The var =" + a);
}
else MessageBox.Show("if did not end up true");
}
}
}
I failed to initialize these, after adding them to the form method...poof everything works! :
public Form1()
{
InitializeComponent();
dataGridView1.CellClick += dataGridView1_CellClick;
dataGridView1.SelectionChanged += dataGridView1_SelectionChanged;
}
I want develop a calculator by using c#, and I do not use method click for all button from 0 to 9 I want I have just one method and if I click the each button wrote in textbox by using sender and tags.
best regards
enter code here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Final
{
public partial class Form1 : Form
{
bool names;
int counter;
string name;
double ans, num;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void button6_Click(object sender, EventArgs e)
{
textBox1.Text += "1";
counter++;
again();
}
private void button7_Click(object sender, EventArgs e)
{
textBox1.Text += "2";
counter++;
again();
}
private void button8_Click(object sender, EventArgs e)
{
textBox1.Text += "3";
counter++;
again();
}
You can have just one handler for all digit buttons, and then you can extract its value like this:
int num = int.Parse(((Button)sender).Text);
This assumes that you set the Text property of the buttons to: 0,1,2..9
You can access the Tag property just like the Text:
var txt = ((Button)sender).Tag).ToString();
textBox1.Text += txt;
Set .Tag to correspondent value and then retrieve it from sender by casting it to Button type.
private void button_Click(object sender, EventArgs e)
{
var button = (Button)sender;
textBox1.Text += button.Tag.ToString();
counter++;
again();
}
public Form1()
{
InitializeComponent();
button1.Tag = 1;
button1.Click += button_Click;
button2.Tag = 2;
button2.Click += button_Click;
// and so on for other buttons
}
I'm currently having issues with my code in terms of getting a printing option to show up when thy click a specific button.
I am making a reminder program and was just experimenting. Also would like to know the most efficient way to add a daily notification system to my program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Mail;
using System.IO;
using System.Drawing.Printing;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
namespace simpleapp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add("Reminder: " + textBox1.Text);
}
private void input_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
listBox1.Items.Add("Reminder: " + textBox1.Text );
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int rmd = listBox1.SelectedIndices.Count - 1; rmd >= 0; rmd--)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndices[rmd]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.SelectionMode = SelectionMode.MultiExtended;
}
private void button6_Click(object sender, EventArgs e)
{
FAQ faqs = new FAQ();
faqs.Show();
}
// When the Button is Clicked the List is saved in a ".txt file format for the user to view later
private void button3_Click(object sender, EventArgs e)
{
var Savingfileas = new SaveFileDialog();
Savingfileas.Filter = "Text (*.txt)|*.txt ";
if (Savingfileas.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (var Reminder = new StreamWriter(Savingfileas.FileName, false))
foreach (var item in listBox1.Items)
Reminder.Write(item.ToString() + Environment.NewLine);
MessageBox.Show("File has been successfully saved"+ '\n' + "Thank you for using the Remindr program");
}
}
private void button4_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
Email_Client emc = new Email_Client();
emc.Show();
}
}
}
You have a few options. One is to graphically layout a print document and iterate through your listbox while drawing the text in the textbox using x and y coordinates. A better way would be to get your listbox items into a dataset and use it to generate a report. Are you storing these items in a database for retrieval? Here's a link that should help you get started. The tutorial is in VB.Net but there's only a small amount of code to this and should be easy to repeat using C# code.
Here is an absolutely minimal example of printing a ListBox.
It assumes your ListBox contains strings and shows a PrintPreviewDialog; it sets the page unit to mm, do pick a unit you are comfortable with..!
Of course you may chose one or more different fonts etc..
private PrintDocument document = new PrintDocument();
private void printButton_Click(object sender, EventArgs e)
{
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = document;
ppd.Document.DocumentName = "TESTING";
document.PrintPage += document_PrintPage;
ppd.ShowDialog();
}
void document_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
int leading = 5;
int leftMargin = 25;
int topMargin = 10;
// a few simple formatting options..
StringFormat FmtRight = new StringFormat() { Alignment = StringAlignment.Far};
StringFormat FmtLeft = new StringFormat() { Alignment = StringAlignment.Near};
StringFormat FmtCenter = new StringFormat() { Alignment = StringAlignment.Near};
StringFormat fmt = FmtRight;
using (Font font = new Font( "Arial Narrow", 12f))
{
SizeF sz = e.Graphics.MeasureString("_|", Font);
float h = sz.Height + leading;
for (int i = 0; i < listBox1.Items.Count; i++)
e.Graphics.DrawString(listBox1.Items[i].ToString(), font , Brushes.Black,
leftMargin, topMargin + h * i, fmt);
}
}
The actual printing is triggered when the user clicks the printer symbol in the dialog.
Note that there are more StringFormat options!
I have a program which is able to retrieve various registry values using C# codes which was compiled and created using VS 2010.
However the problem arises when I tried to display the results retrieved from the Windows Registry into a rich text box within a form.
The form only shows 1 line which is the last value in the Array that contains the results.
Please do give some advice on the codes. Thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace Syscrawl
{
public partial class FTK_Menu_Browsing_History : Form
{
public FTK_Menu_Browsing_History()
{
InitializeComponent();
}
private void buttonFileHistory_Click(object sender, EventArgs e)
{
this.Hide();
FTK_Menu_File_History mfh = new FTK_Menu_File_History();
mfh.ShowDialog();
this.Close();
}
private void buttonEncryptedFiles_Click(object sender, EventArgs e)
{
this.Hide();
FTK_Menu_Encrypted_Files mef = new FTK_Menu_Encrypted_Files();
mef.ShowDialog();
this.Close();
}
private void buttonRecentlyAccessedFiles_Click(object sender, EventArgs e)
{
this.Hide();
FTK_Menu_Recently_Accessed_Files mraf = new FTK_Menu_Recently_Accessed_Files();
mraf.ShowDialog();
this.Close();
}
private void buttonRegistryHistory_Click(object sender, EventArgs e)
{
this.Hide();
FTK_Menu_Registry_History mrh = new FTK_Menu_Registry_History();
mrh.ShowDialog();
this.Close();
}
private void buttonMainMenu_Click(object sender, EventArgs e)
{
this.Hide();
Menu m = new Menu();
m.ShowDialog();
this.Close();
}
private void buttonLogOut_Click(object sender, EventArgs e)
{
this.Hide();
Syscrawl_Login sl = new Syscrawl_Login();
sl.ShowDialog();
this.Close();
}
private void FTK_Menu_Browsing_History_Load(object sender, EventArgs e)
{
try
{
RegistryKey rk = Registry.CurrentUser;
rk = rk.OpenSubKey("Software\\Microsoft\\Internet Explorer\\TypedURLs",
false);
PrintKeys(rk);
rk.Close();
}
catch (Exception MyError)
{
richTextBoxBrowsing.Text="An error has occurred: " + MyError.Message;
}
}
void PrintKeys(RegistryKey rk)
{
if (rk == null)
{
richTextBoxBrowsing.Text="Couldn't open the desired subkey.";
return;
}
richTextBoxBrowsing.Text = "Subkeys of " + rk.Name;
try
{
string[] valnames = rk.GetValueNames();
int i = 0;
foreach (string s in valnames)
{
string val = (string)rk.GetValue(valnames[i++]);
richTextBoxBrowsing.Text="-----------------------------------------------";
richTextBoxBrowsing.Text=s + " contains " + val;
}
}
catch (Exception MyError)
{
richTextBoxBrowsing.Text = "An errors has occurred: " + MyError.Message;
}
}
private void richTextBoxBrowsing_TextChanged(object sender, EventArgs e)
{
}
}
}
By saying:
richTextBoxBrowsing.Text=
in each iteration of your loop, you keep on overwriting the text. So only the last call to the Text property gets printed.
You need to set the richTextBoxBrowsing.TextMode property to multiline, and then instead call:
richTextBoxBrowsing.AppendText(s + " contains " + val + "\n");
Oh, and by the way, use: string val = rk.GetValue(s).ToString();
so you can remove the int i = 0; declaration
You should use richTextBoxBrowsing.AppendText(...)
You're changing the entire contents with each call, instead of appending to it:
richTextBoxBrowsing.Text=s + " contains " + val;
should be
richTextBoxBrowsing.AppendText(s+" contains " + val+Environment.NewLine);
Confirm that you set
richTextBoxBrowsing.TextMode to
MultiLine
Change richTextBoxBrowsing.Text+=s + " contains " + val; in foreach loop
Use Debug.WriteLine to debug return
value
I think your loop is not correct.
In _void PrintKeys()_ your Loop overwerites your RichTextBox.Text-Value try something like:
String temp = "-----------------------------------------------";
foreach (string s in valnames)
{
String val = (String)rk.GetValue(valnames[i++]);
temp=temp+s + " contains " + val;
}
RichTextBox.text = temp;