I have a winform, that takes a number of params, executes an stored procedure and then populates a DataGridView with the results.
What I'd like to do is add a string the bottom of my winform that returns a message, including a count of total rows returned.
This presently works fine, using the following syntax :
deskSearchResultCount.Text = String.Format("Your search returned {0} results", deskDataGridView.RowCount );
However as the majority of my application has been written out in the initial form, I was moving sections into classes, to 'tidy it up' a bit - (I'm still very new to c# so apologies if this is a n00b mistake)
Once I add a class called Summary, I would like to call my RowCount as follows :
Summary Returned = new Summary();
deskSearchResultCount.Text = String.Format("Your search returned {0} results", Returned.Total("Desk"));
With my Summary class containing the following :
public class Summary : ContactAnalysisToolbox
{
public int Total(string type)
{
if (type == "Desk")
{
return deskDataGridView.Rows.Count;
}
else
{
return visionDataGridView.Rows.Count;
}
}
However the returned count is always 0. When stepping through the process also, at no point does it appear to be attempting to set itself as anything different.
Can anyone please help / point me in the right direction?
Thanks.
Edit -
I've included the full form also -
using System;
using System.Diagnostics;
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.DirectoryServices.AccountManagement;
using System.IO;
//
// Todo :
// -- Capture Assigned Team In Output
//
//
namespace CallsAnalysisToolbox
{
public partial class ContactAnalysisToolbox : Form
{
public ContactAnalysisToolbox()
{
InitializeComponent();
// Grabs username for current user and displays a welcome message
this.welcomeMessage.Text = "Welcome " + UserPrincipal.Current.Name;
}
private void searchVision_Click(object sender, EventArgs e)
{
try
{
// Run sp_incomingCalls on SQLCLUSTER
this.rep_IncomingCallsTableAdapter.Fill(this.visionReportsDataSet.Rep_IncomingCalls, dateTimePicker1.Value, dateTimePicker2.Value, textBox1.Text, textBox2.Text);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
// Make export button active when search returns results
exportVisionButton.Enabled = (visionDataGridView.Rows.Count > 0);
// Assign returned row count to visionSearchResultCount label and then display label
visionSearchResultCount.Text = String.Format("Your search returned {0} results", visionDataGridView.RowCount);
visionSearchResultCount.Visible = true;
}
private void searchDesk_Click(object sender, EventArgs e)
{
try
{
// Run sp_caseActivity on SQLCLUSTER
this.rPT_CaseActivityTableAdapter.Fill(this.deskDataSet.RPT_CaseActivity, deskFrom.Value, deskTo.Value, deskClientList.Text, deskBenefitList.Text, deskStatusList.Text);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
if (deskDataGridView.Rows.Count > 0)
{
exportDeskButton.Enabled = true;
deskSearchResultCount.Visible = true;
Summary Returned = new Summary();
deskSearchResultCount.Text = String.Format("Your search returned {0} results", Returned.Total("Desk"));
deskSummaryData.Visible = true;
noDataDesk.Visible = false;
// Populate the summary tab
// Get Email / Phone case count
deskTotalCaseResults.Text = deskDataGridView.RowCount.ToString();
//deskTotalEmailCasesResults.Text = emailCount.ToString();
//deskTotalPhoneCasesResults.Text = phoneCount.ToString();
}
}
//TODO : Combine Export functions. Ideally just a single function rather than the repeated logic within the Export class for each datagrid
private void exportVisionButton_Click(object sender, EventArgs e)
{
Export Export = new Export();
Export.ReturnedResult("Vision");
}
private void exportDeskButton_Click(object sender, EventArgs e)
{
Export Export = new Export();
Export.ReturnedResult("Desk");
}
private void deskDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
// Limit 'open case in browser' action to first cell
if (deskDataGridView.CurrentCell.ColumnIndex.Equals(0))
{
string url = string.Format("https://qa.internal.local/agent/case/{0}", deskDataGridView.Rows[e.RowIndex].Cells[0].Value);
Process.Start(url);
}
}
}
}
For example you could do something like this. It's called Method Extension
Try this
public static class Helpers
{
public static string ToTotalCount(this DataGridView item)
{
return string.Format("Your search returned {0} results", item.Rows.Count);
}
}
In your form make sure that the namespace of the class Helpers is in the usings:
deskSearchResultCount.Text = deskDataGridView.ToTotalCount();
Related
I have created 2 text boxes that take the name and email address, stores it in a "text" file and display the contents in a list box. I have everything done but when it displays in the list box this is the output that I get.
"System.Windows.Forms.TextBox, Text: tony"
"System.Windows.Forms.TextBox, Text: tony#tony.com"
Can anyone tell me why it is doing that please? I'm still new to c# and I know this is a minor thing I just do not know where to look
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.IO;
namespace _iLab_Week7
{
public partial class Form1 : Form
{
private StreamReader inFile; //streamreader for input
private StreamWriter outFile; //streamwriter for output
const string filename = "contacts.txt";
public Form1()
{
InitializeComponent();
}
private void btnAddContact_Click(object sender, EventArgs e)
{
//Disable the "add contact" and "email"
btnAddContact.Enabled=false;
txtBoxEmail.Enabled=false;
//check for and create contacts.txt file
if(!File.Exists(filename))
File.Create(filename);
if(File.Exists(filename))
{
try
{
//create the file stream
outFile = new StreamWriter(filename, true);
//get the item from the name and email text box
//write it to the file
outFile.WriteLine(txtBoxName);
outFile.WriteLine(txtBoxEmail + "\n");
//close the file
outFile.Close();
//clear the textbox
txtBoxName.Text="";
txtBoxEmail.Text="";
//the cursor in the text box
txtBoxName.Focus();
txtBoxEmail.Focus();
}
catch (DirectoryNotFoundException exc)
{
lstBoxContact.Items.Add(exc.Message);
}
catch (System.IO.IOException exc)
{
lstBoxContact.Items.Add(exc.Message);
}
string listItem;
this.lstBoxContact.Items.Clear();
btnAddContact.Enabled = false;
try
{
//open file for reading
inFile=new StreamReader(filename);
//read from file and add to list box
while ((listItem=inFile.ReadLine()) !=null)
{
this.lstBoxContact.Items.Add(listItem);
}
//Close the file
inFile.Close();
}
catch (System.IO.IOException exc)
{
this.lstBoxContact.Items.Add(exc);
}
}
else
{
this.lstBoxContact.Items.Add("File Unabailable");
}
}
private void lstBoxContact_SelectedIndexChanged(object sender, EventArgs e)
{
//enable button
btnAddContact.Enabled = true;
txtBoxName.Enabled = true;
txtBoxEmail.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosedEventArgs e)
{
//make sure files are closed
try
{
inFile.Close();
outFile.Close();
}
catch { }
}
}
Replace
outFile.WriteLine(txtBoxName);
outFile.WriteLine(txtBoxEmail + "\n");
with
outFile.WriteLine(txtBoxName.Text);
outFile.WriteLine(txtBoxEmail.Text + "\n");
and try...
ADDED : When you say txtBoxName, you are referring to the txtBoxName object as a whole, which contains many properties - like Text, ForeColor, Font etc.... To get only the value or content, you need to specify the property which gives you that - which is the Text property
More about TextBox
outFile.WriteLine(txtBoxName);
is equivalent to
outFile.WriteLine(txtBoxName.ToString());
For most classes, the ToString() method is the same as Object.ToString(). This method just displays the name of the type of the instance you're trying to display. So you might have only seen
System.Windows.Forms.TextBox
However, the TextBox class helpfully overrides this method and displays both the type name and the value of the Text property.
But as Saagar Elias Jacky said. This is not what you actually intended to do, so just display txtBoxName.Text as he suggested.
I am fairly new to C# programming and am having some trouble figuring out how to perform this. I am trying to say in the program that if the textBoxes are not filled in than streamWriter should not send anything to the file and a messageBox pops up. As of now only the messageBox pops up but information is still being sent to the file. I am trying to use something like this if ((fileOut != null)) however I am not finding a good place to insert it or if this is what should be used. Any help would be much appreciated. 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 System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Calculate payroll
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
decimal hoursWorked;
decimal hourlyPayRate;
decimal basePay;
decimal overtimeHours;
decimal overtimePay;
decimal grossPay;
// Get the hours worked and hourly pay rate.
hoursWorked = decimal.Parse(txtHoursWorked.Text);
hourlyPayRate = decimal.Parse(txtHourlyRate.Text);
// Determine the gross pay.
if (hoursWorked >= 40)
{
// Calculate the base pay (without overtime).
basePay = hourlyPayRate * 40;
// Calculate the number of overtime hours.
overtimeHours = hoursWorked - 40;
// Calculate the overtime pay.
overtimePay = overtimeHours * hourlyPayRate * 1.5m;
// Calculate the gross pay.
grossPay = basePay + overtimePay;
}
else
{
// Calculate the gross pay.
grossPay = hoursWorked * hourlyPayRate;
}
// Display the gross pay.
lblGrossPay.Text = Convert.ToString(grossPay);
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
} //Writes text to files
StreamWriter fileOut = new StreamWriter("employeePay.dat", true);
//if (!(fileOut != null))//I am trying this. However stated this way nothing is passed to the file
{
fileOut.Write(txtName.Text);
fileOut.Write(",");
fileOut.Write(txtNumber.Text);
fileOut.Write(",");
fileOut.Write(txtHourlyRate.Text);
fileOut.Write(",");
fileOut.Write(txtHoursWorked.Text);
fileOut.Write(",");
fileOut.WriteLine(lblGrossPay.Text);
}
fileOut.Close();
LoadContacts();
}
// Clear all text from output labels & input textboxes
private void btnClera_Click(object sender, EventArgs e)
{
// Clear the TextBoxes and gross pay label.
txtName.Text = "";
txtNumber.Text = "";
txtHoursWorked.Text = "";
txtHourlyRate.Text = "";
lblGrossPay.Text = "";
// Reset the focus.
//txtHoursWorked.Focus();
}
// End program
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
void LoadContacts()
{
try
{
lstEmployeePay.Items.Clear();
string employeePay;
if (File.Exists("employeePay.dat"))
{
StreamReader fileIn = new StreamReader("employeePay.dat");
while (!fileIn.EndOfStream)
{
employeePay = fileIn.ReadLine();
string[] fields = employeePay.Split(',');
lstEmployeePay.Items.Add(fields[0]);
lstEmployeePay.Items.Add(fields[1]);
lstEmployeePay.Items.Add(fields[2]);
lstEmployeePay.Items.Add(fields[3]);
lstEmployeePay.Items.Add(fields[4]);
lstEmployeePay.Items.Add("");
}
fileIn.Close();
}
}
catch (FileNotFoundException ex)
{
MessageBox.Show("The file does not exist, please try again");
}
catch (Exception ex)
{
}
}
}
}
All you need is a return statement after showing the message box. Like
MessageBox.Show("");
return;
I would also like to make some other recommendations here.
You can check if the textboxes are empty by doing
if(string.IsNullorWhiteSpace(yourtextboxt.text)
You should do the parsing using decimal.tryparse. It will not throw an exception.
You need to move your stream writer within the exception handling as everything after the catch still gets executed.
I would also consider wrapping the StreamWriter in a using statement to guarantee it is closed when the function exits.
try
{
// other code here
using(var fileOut = new StreamWriter("employeePay.dat", true)
{
fileOut.Write(txtName.Text);
fileOut.Write(",");
fileOut.Write(txtNumber.Text);
fileOut.Write(",");
fileOut.Write(txtHourlyRate.Text);
fileOut.Write(",");
fileOut.Write(txtHoursWorked.Text);
fileOut.Write(",");
fileOut.WriteLine(lblGrossPay.Text);
}
}
catch(...)
{
MessageBox();
}
// any code after the catch will still 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;
namespace Cameron_PickerillTrinitapoli_Assn1
{
public partial class seasonalBttnChanger : Form
{
public seasonalBttnChanger()
{
InitializeComponent();
}
//Triggers when program first loads
//Sets up
private void bttnChanger_Load(object sender, EventArgs e)
{
List<Button> lstTxt = new List<Button>
{
bttnSpring, bttnSummer, bttnAutumn, bttnWinter
};
//Wiring up event handlers in run time
foreach (Button txt in lstTxt)
{
txt.MouseEnter += button_MouseEnter;
txt.MouseLeave += button_MouseLeave;
}
}
// Sets up different background colors for TextBoxes
//* Static values for the color of each button need
//to be added.
//**Not what I was trying to accomplish
//**This needs to go somewhere else
void button_MouseEnter(object sender, EventArgs e)
{
try
{
// Event handlers always pass the parameter "sender" in as an object.
// You have to downcast it back to the actual type.
String bttnName = null;
String bttnNameSpring = "Spring";
String bttnNameSummer = "Summer";
String bttnNameAutumn = "Autumn";
String bttnNameWinter = "Winter";
Button txt = (Button)sender;
// stkColor.Push(txt.BackColor);
//txt.BackColor = Color.Red;
bttnName = txt.Name;
if (bttnName == bttnNameSpring)
{
txt.BackColor = Color.LightGreen;
}
else if (bttnName == bttnNameSummer)
{
//txt.BackColor = Color.Red;
txt.BackColor = Color.Red;
}
else if (bttnName == bttnNameAutumn)
{
txt.BackColor = Color.Yellow;
}
else if (bttnName == bttnNameWinter)
{
txt.BackColor = Color.Cyan;
}
}
catch (Exception ex)
{
MessageBox.Show("Error:\n " + ex.Message);
}
}
//Handler for mouse leaving the button
void button_MouseLeave(object sender, EventArgs e)
{
try
{
Button txt = (Button)sender;
//txt.BackColor = stkColor.Pop();
}
catch (Exception ex)
{
MessageBox.Show("Error:\n " + ex.Message);
}
}
}
}
}
Alright, so I'm just trying to create a simple program that changes the background colors of these buttons to some plain colors when you mouse over them. I had the same thing working using TextBox, but I need to get it working with button. I changed everything over to use the Button class, and it seems to have all the same functionality, but now the program runs, but nothing happens when you mouse over the buttons.
I'm pretty new to c#, stack exchange, and only slightly less so to programming in general, so sorry if I'm dinking up on etiquette/formatting my questions, etc.
I think you are trying to reference your buttons title when you are actually calling the button name
Changing:
String bttnName = null;
String bttnNameSpring = "Spring";
String bttnNameSummer = "Summer";
String bttnNameAutumn = "Autumn";
String bttnNameWinter = "Winter";
Button txt = (Button)sender;
To:
String bttnName = null;
String bttnNameSpring = "bttnSpring";
String bttnNameSummer = "bttnSummer";
String bttnNameAutumn = "bttnAutumn";
String bttnNameWinter = "bttnWinter";
Causes the code to work.
If you do infact want to use the "Spring", "Summer" etc reference than i would suggest changing
bttnName = txt.Name;
to
bttnName = txt.Text;
And ensure that the Text of the labels is set correctly
All of a sudden my form window has begun to close as soon as the application is launched. There's nothing in the output window that gives a hint as to what could be causing it and there are no errors thrown at me either. Does anybody have any ideas?
I've provided to form's class.
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;
namespace ProjectBoardManagement {
public partial class CreateBoard : Form {
Functions funcs = new Functions();
public CreateBoard() {
InitializeComponent();
}
private void CreateBoardButton_Click(object sender, EventArgs e) {
String BoardName = BoardNameText.Text;
String Pages = "";
String Labels = "";
foreach (ListViewItem i in PageNameList.Items) {
Pages = (Pages + i.Name.ToString() + ",");
}
foreach (ListViewItem i in LabelNameList.Items) {
Labels = (Labels + i.Name.ToString() + ",");
}
String BoardFile = ("board_" + BoardName + ".txt");
funcs.SaveSetting(BoardFile, "name", BoardName);
funcs.SaveSetting(BoardFile, "pages", Pages);
funcs.SaveSetting(BoardFile, "labels", Labels);
FormManagement.CreateBoard.Hide();
FormManagement.BoardList.LoadBoardList();
}
private void PageNameButtonAdd_Click(object sender, EventArgs e) {
String pagename = PageNameText.Text;
if (pagename != "") {
PageNameList.Items.Add(pagename);
}
PageNameText.Text = "";
}
private void LabelNameButtonAdd_Click(object sender, EventArgs e) {
String labelname = LabelNameText.Text;
if (labelname != "") {
LabelNameList.Items.Add(labelname);
}
LabelNameText.Text = "";
}
}
}
Obvious first thing to do - run it in Debug mode and stop execution on all exceptions. This should give you enough information on how to go from there.
Otherwise Functions funcs = new Functions(); looks suspicious.
This question already has answers here:
C# - Winforms - Global Variables
(8 answers)
Closed 9 years ago.
I have been trying, without success, to share a variable between multiple forms. I am very new to c# and so have been failing miserably despite reading a couple of things about it.. Below is the programs code:
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 System.Data.Common;
using System.Data.OleDb;
namespace login
{
public partial class LoginScreen : Form
{
public LoginScreen()
{
InitializeComponent();
}
// Variables
int count = 0;
public static System.Data.OleDb.OleDbConnection con =
new System.Data.OleDb.OleDbConnection();//database connection
string dbProvider;
string dbSource;
OleDbDataAdapter da; // create database adapter 'da'
// CREATE DATASET VARIABLE ds1 TO HOLD THE DATABASE
public static DataSet ds1 = new DataSet();
string accountNo;
string sql;
string password;
int rownum = 0;
bool valid = false;
private void btnLogin_Click(object sender, EventArgs e)
{
accountNo = txtBoxAccntNo.Text;
valid = validate(); //uses validate() method to check validity
if (valid == true && accountNo == "11111111")
{
ManagerScreen Manager = new ManagerScreen();
this.Hide();
Manager.Show();
}
else if (valid == true)
{
s customer = new s();
this.Hide();
customer.Show();
}
else
{
if (count == 2)
{
this.Close();
}
count += 1;
txtBoxAccntNo.Clear();
txtBoxPinNo.Clear();
}
}
private void txtBoxAccntNo_TextChanged(object sender, EventArgs e)
{
}
private void LoginScreen_Load(object sender, EventArgs e)
{
// open database connection and load contents
// database connection
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"; // this is the database provider
dbSource = "Data Source = 'C:\\Bank.accdb'"; // navigation path
con.ConnectionString = dbProvider + dbSource;
}
private void btnExit_Click(object sender, EventArgs e)
{
// If button exit selected hide this form and open the welcome screen
WelcomeForm Welcome = new WelcomeForm();
this.Hide();
Welcome.Show();
}
// IsValid method checks that pass and login are valid
private bool validate()
{
ds1 = new DataSet();
con.Open();
// Validate Account number
sql = "SELECT * FROM tblCustomers WHERE ((tblCustomers.AccountNo) = '" + txtBoxAccntNo.Text + "')";
da = new OleDbDataAdapter(sql, con);
rownum = da.Fill(ds1, "tblCustomers");
con.Close();
if (rownum != 1)
{
MessageBox.Show("Not a valid Account number! - Try Again ");
return false;
}
else
{
// validate the pin
password = ds1.Tables["tblCustomers"].Rows[0][4].ToString();
if (password == txtBoxPinNo.Text)
{
MessageBox.Show("valid");
return true;
}
else
{
MessageBox.Show("Not a valid password - please try again ");
return false;
}
}
}
}
}
I want to share the variable accountNo with all other forms. Please advise, as I really need to get on with this. Thank you for any help.
You can make that accountNo property as static or either you can have some getter method to access that too.
If you set accountNo as static you can access it by just calling
ClassName.PropertyName
in your case
LoginScreen.accountNo will be the account number property.
Simple code sample
public partial class LoginScreen : Form
{
public LoginScreen()
{
InitializeComponent();
}
public static string accountNo;
}
public class AnotherClass
{
string accountNo = LoginScreen.accountNo;
}
The right way to go about this is to use the form to retrieve the information and then store it somewhere else to be accessed as you need it. Don't access it directly in the form from elsewhere - this will require you to keep the login form in scope for the whole application lifecycle. This probably isn't what you want.
In practice, this means creating something like a Global static class that everything has access to:
public static class Globals {
public static string AccountNumber {
get;
set;
}
}
From in your login form, after validating the login as correct, you would simply do:
Globals.AccountNumber = txtBoxAcctNo.Text;
Then, anywhere else you need the AccountNumber, you can access it as Globals.AccountNumber.
I can recommend one of three ways to achieve what you want:
Make accountNo a public static variable. Then, other forms can access it by LoginScreen.accountNo (it's better to have a property to control visibility). This is a good approach if you might have many active instances of LoginScreen and they all might update accountNo and you want any form which accesses this field to get the latest value.
Implement a singleton pattern for the entire form and have accountNo in it as a public variable. This is a good approach if you will only have one instance of the firm active at any time.
Have accountNo be static member in another class and have LoginScreen access it by UtilClass.accountNo. This is a good approach if other forms/classes might want to update the field and/or it's a field which shouldn't be associated with this form.