I need to compare a name of an object (test) with the name of a test that has been placed into a queue. The logic I have is to use a foreach loop so that for each test in the queue I can compare the name that the user provides with the name on each test until it finds a match (in which it will tell the user the score they made on the test in a message box).
The code in the snippet is incomplete; using submittedTests with a getter doesn't work (doesn't give me an option to do so in intellisense).
This takes place in the btnFindTest_Click method. This is the code that I have so far:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConsoleApplication1
{
public partial class Form1 : Form
{
//Stack and Queue calls
Queue submittedTest = new Queue();
Stack outForChecking = new Stack();
public Form1()
{
InitializeComponent();
}
private void btnSubmitTest_Click(object sender, EventArgs e)
{
//generates a random test score
Random rdm = new Random();
int testScore = rdm.Next(0, 100);
string score = testScore.ToString();
//assigns user input to a variable
string name = txtName.Text;
//Generate a new test that passes in
Test tests = new Test(name, score);
//shows the user the name they just enetered
label3.Text = String.Format("{0}", name);
//adds submitted test to the queue, then displays that test in a list box
submittedTest.Enqueue(tests);
listSubTests.Items.Add(new Test(name, score));
//Clears input box for next user input
txtName.Clear();
}
private void btnFindTest_Click(object sender, EventArgs e)
{
string compareName = "";
string tempName = txtName.Text;
foreach (Test tests in submittedTest)
{
if (compareName == tempName)
{
System.Windows.Forms.MessageBox.Show("Your score was --");
}
}
}
public void txtName_TextChanged(object sender, EventArgs e)
{
}
private void txtScore_TextChanged(object sender, EventArgs e)
{
}
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
}
}
And the test object is defined in it's own class here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Test
{
private string name;
private string score;
public string Name
{
get { return name; }
set { name = value; }
}
public string Score
{
get { return score; }
set { score = value; }
}
public Test(string name, string score)
{
this.name = name;
this.score = score;
}
public override string ToString()
{
return (String.Format("{0} {1} ", name, score));
}
}
}
I'm reletively new to C# and this project is for school, so if I'm far off, please let me know!
Based on your example, you may have forgotten to use the object:
foreach (Test tests in submittedTest)
{
if (tests.Name == tempName)
{
System.Windows.Forms.MessageBox.Show("Your score was --");
}
}
Related
I am having a problem with my code where i run into an error when i try to click the join button. It says the ap.Connect(authrequest) is returning a null value so it cannot return a bool value. I am doing this in visual studio in a .net forms i think.
Thanks for you help.
Ps i am a student
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 SimpleWifi;
namespace desk_flat
{
public partial class formConnect : Form
{
private static Wifi wifi;
public formConnect()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wifi = new Wifi();
List<AccessPoint> aps = wifi.GetAccessPoints();
foreach (AccessPoint ap in aps)
{
ListViewItem listobj = new ListViewItem(ap.Name);
listobj.SubItems.Add(ap.SignalStrength + "'''");
listobj.Tag = ap;
lstWifi.Items.Add(listobj);
}
}
private bool ConnectWifi(AccessPoint ap, string password)
{
AuthRequest authrequest = new AuthRequest(ap);
authrequest.Password = password;
return ap.Connect(authrequest);
}
private void btnJoin_Click(object sender, EventArgs e)
{
if (lstWifi.Items.Count > 0 && txtbPassword.Text.Length > 0)
{
ListViewItem selectedItem = lstWifi.SelectedItems[0];
AccessPoint ap = (AccessPoint)selectedItem.Tag;
if (ConnectWifi(ap, txtbPassword.Text))
{
lblStatus.Text = "You have connected to " + ap.Name;
}
else
{
lblStatus.Text = "Connection has failed";
}
}
else
{
lblStatus.Text = "Enter a password or select a network";
}
}
}
}
I have two forms in WFA C#.
FORM1:
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 WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
if (checkBox1.Checked == true)
{
f2.intr = checkBox1.Text;
}
if (checkBox2.Checked == true)
{
f2.intr2 = checkBox2.Text;
}
if (checkBox3.Checked == true)
{
f2.intr3 = checkBox3.Text;
}
if (checkBox4.Checked == true)
{
f2.intr4 = checkBox4.Text;
}
if (checkBox5.Checked == true)
{
f2.intr5 = checkBox5.Text;
}
f2.ShowDialog();
}
}
}
FORM2:
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 WindowsFormsApplication8
{
public partial class Form2 : Form
{
public string gen, intr, intr2, intr3, intr4, intr5;
public string interest
{
get { return intr; }
set { intr = value; }
}
public string interest2
{
get { return intr2; }
set { intr2 = value; }
}
public string interest3
{
get { return intr3; }
set { intr3 = value; }
}
public string interest4
{
get { return intr4; }
set { intr4 = value; }
}
public string interest5
{
get { return intr5; }
set { intr5 = value; }
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = "Interests: " + interest + "\n" + interest2 + "\n" + interest3 + "\n" + interest4 + "\n" + interest5;
}
}
}
I have 5 checkboxes inside a groupbox. This outputs the selected items to label1. The output looks like this when I check all the checkboxes:
art
science
math
history
sports
and whenever I check boxes randomly for example i'll check the art and history. The output is like this:
art
history
it leaves two spaces.
In the design of form1 there are the checkbox1,checkbox2,checkbox3,checkbox4,checkbox5 inside a groupbox.
In the design of form2 there is only label1.
How can I separate the selected items by a comma in one line?
I'm new to c# helpp.
You could put all the interests in an array:
string[] interests = { interest, interest2, interest3, interest4, interest5 };
Then you could remove the non-selected ones:
string[] selectedInterests = interests.Where(str => !String.IsNullOrEmpty(str)).ToArray();
At the end you can join them into a single string:
label1.Text = String.Join(", ", selectedInterests);
I'm creating an add in for Microsoft Excel that includes a ribbon tab. On this tab is a button with the following code:
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
}
}
The button opens up a separate form where the user specifies budget_cell, account_cell, and transaction_cell. I then pass that data to the above code in SolutionName.ThisAddIn.cs (where SolutionName is the namespace of the solution). Strictly speaking, the code works. However, the data doesn't show up in the cells until the button is pressed a second time. Why is that? Is it because I'm retrieving the data from a different object in the solution?
Also, I've been trying to get this code and the aforementioned form to activate when the add in first starts up.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
I've been at this for a good twelve hours now, and I can't get it to work. What am I missing?
ThisAddIn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace AccountingAddIn
{
public partial class ThisAddIn
{
public static string budget_cell = "";
public static string account_cell = "";
public static string transaction_cell = "";
public static string date_cell = "";
public static string time_cell = "";
public static string description_cell = "";
public static bool date = false;
public static bool time = false;
public static bool description = false;
public static decimal budget = 0;
List<Account> accounts = new List<Account>();
public void budgetStartUp()
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
if (date == true)
{
displayWorksheet.Range[date_cell].Value2 = "Date";
}
if (time == true)
{
displayWorksheet.Range[time_cell].Value2 = "Time";
}
if (description == true)
{
displayWorksheet.Range[description_cell].Value2 = "Description";
}
Account na = new Account(0, displayWorksheet);
accounts.Add(na);
}
}
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
return Globals.Factory.GetRibbonFactory().CreateRibbonManager(
new Microsoft.Office.Tools.Ribbon.IRibbonExtension[] { new MyRibbon() });
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
CreateRibbonExtensibilityObject();
budgetStartUp();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
}
}
frmStartup.cs:
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 AccountingAddIn
{
public partial class frmStartup : Form
{
public frmStartup()
{
InitializeComponent();
}
private void btnHelp_Click(object sender, EventArgs e)
{
MessageBox.Show("Please enter a starting amount for your budget and " +
"which cells will display the running total for your " +
"accounts." +
"\n\nNote: Leaving the budget blank will" +
" result in a starting budget of $0.00.");
}
private void btnOkay_Click(object sender, EventArgs e)
{
AccountingSeminar.ThisAddIn.budget += Convert.ToDecimal(txtStartingAmount.Text);
AccountingSeminar.ThisAddIn.budget_cell = txtBudget.Text;
AccountingSeminar.ThisAddIn.account_cell = txtAccount.Text;
AccountingSeminar.ThisAddIn.transaction_cell = txtTransaction.Text;
if (chkDate.Checked)
{
AccountingSeminar.ThisAddIn.date_cell = txtDate.Text;
AccountingSeminar.ThisAddIn.date = true;
}
if (chkTime.Checked)
{
AccountingSeminar.ThisAddIn.time_cell = txtTime.Text;
AccountingSeminar.ThisAddIn.time = true;
}
if (chkDescription.Checked)
{
AccountingSeminar.ThisAddIn.description_cell = txtDescription.Text;
AccountingSeminar.ThisAddIn.description = true;
}
Close();
}
}
}
Hi am a fairly novice when it comes to c# and I have being trying to read out a text file then splitting it into sections with classes but have trouble with where to declare them an then how to cycle through the records. here's my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Windows.Forms;
namespace Assignment_3
{
public partial class Form1 : Form
{
string s;
string ss;
int i = 1;
string infilename;
int num;
SortedList sList = new SortedList();
int x = 0;
public Form1()
{
InitializeComponent();
student myself = new student();
infilename = "text.txt";
StreamReader sr1 = new StreamReader(infilename);
sList.Clear();
while ((s = sr1.ReadLine()) != null)
{
string[] strs = s.Split(',');
myself.firstname = strs[0];
myself.middlename = strs[1];
myself.surname = strs[2];
myself.dob = DateTime.Parse(strs[3]);
myself.dob.ToString(strs[3]);
myself.sex = strs[4];
ss = myself.dob.ToString("u");
sList.Add(myself.firstname, myself);
}
sr1.Close();
num = sList.Count;
student[] pArray = new student[num];
string[] keys = new string[num];
foreach (DictionaryEntry d in sList)
{
keys[x] = (string)d.Key;
pArray[x] = (student)d.Value;
x++;
}
if (i == 0)
{lblmessage.Text = "Already at the first record."; i = 1; }
if (i == num)
{lblmessage.Text = "Already at the last record.";i = num-1; }
lbllastname.Text = pArray[i].surname;
lblfirstname.Text = pArray[i].firstname;
lblsecondname.Text = pArray[i].middlename;
lbldob.Text = pArray[i].dob.ToString();
lblsex.Text = pArray[i].sex;
}
private void btnlast_Click(object sender, EventArgs e)
{
i = num;
}
private void btnfirst_Click(object sender, EventArgs e)
{
i = 0;
}
private void btnnext_Click(object sender, EventArgs e)
{
i++;
}
private void btnprev_Click(object sender, EventArgs e)
{
i--;
}
}
}
and my class file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment_3
{
class student
{
public string firstname;
public string middlename;
public string surname;
public DateTime dob;
public string sex;
}
}
anyone have any ideas where am going wrong?? I have no errors but find that the text fields do not update with the new record's and then when stepped through the array class holds the correct amount of records and fields, I feel its going to be something very obvious put cant put my finger on it.
Any help would be very appreciated.
You should create new instance of student inside for loop. Because at the moment you have only one instance of student class and all items in SortedList are pointing to same object.
I am getting the following error from my C# Windows Application:
Error 1 No overload for 'CreateLabelInPanel' matches delegate 'WorksOrderStore.ProcessDbConnDetailsDelegate' H:\c\WorksOrderFactory\WorksOrderFactory\WorksOrderClient.cs 43 39 WorksOrderFactory
I have 3 .cs files that essentially:
Opens a windows
Has an option for the users to connect to a db
When that is selected, the system will go off and connect to the db, and load some data in (just test data for now)
Then using a delegate, the system should do soemthing, which for testing will be to create a label. However I haven't coded this part yet.
But I can't build until I get this error sorted.
The 3 fiels are called:
WorksOrderClient.cs (which is the MAIN)
WorksOrderStore.cs
LoginBox.cs
Here's the code for each file:
WorksOrderClient.cs:
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 WorksOrderStore;
namespace WorksOrderFactory
{
using WorksOrderStore;
public partial class WorksOrderClient : Form
{
LoginBox lb = new LoginBox();
private static WorksOrderDB wodb = new WorksOrderDB();
private static int num_conns = 0;
public WorksOrderClient()
{
InitializeComponent();
}
private void connectToADBToolStripMenuItem_Click(object sender, EventArgs e)
{
lb.ShowDialog();
lb.Visible = true;
}
public static bool createDBConnDetObj(string username, string password, string database)
{
// increase the number of connections
num_conns = num_conns + 1;
// create the connection object
wodb.AddDbConnDetails(username, password, database, num_conns);
// create a new delegate object associated with the static
// method WorksOrderClient.createLabelInPanel
wodb.ProcessDbConnDetails(new ProcessDbConnDetailsDelegate(CreateLabelInPanel));
return true;
}
static void CreateLabelInPanel(DbConnDetails dbcd)
{
Console.Write("hellO");
string tmp = (string)dbcd.username;
//Console.Write(tmp);
}
private void WorksOrderClient_Load(object sender, EventArgs e)
{
}
}
}
WorksOrderStore.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WorksOrderFactory;
namespace WorksOrderStore
{
using System.Collections;
// Describes a book in the book list:
public struct WorksOrder
{
public string contractor_code { get; set; } // contractor ID
public string email_address { get; set; } // contractors email address
public string date_issued { get; set; } // date the works order was issued
public string wo_ref { get; set; } // works order ref
public string status { get; set; } // status ... not used
public job_status js { get; set; } // status of this worksorder within this system
public WorksOrder(string contractor_code, string email_address, string date_issued, string wo_ref) : this()
{
this.contractor_code = contractor_code;
this.email_address = email_address;
this.date_issued = date_issued;
this.wo_ref = wo_ref;
this.js = job_status.Pending;
}
}
// Declare a delegate type for processing a WorksOrder:
//public delegate void ProcessWorksOrderDelegate(WorksOrder worksorder);
// Maintains a worksorder database.
public class WorksOrderDB
{
// List of all worksorders in the database:
ArrayList list = new ArrayList();
// Add a worksorder to the database:
public void AddWorksOrder(string contractor_code, string email_address, string date_issued, string wo_ref)
{
list.Add(new WorksOrder(contractor_code, email_address, date_issued, wo_ref));
}
// Call a passed-in delegate on each pending works order to process it:
/*public void ProcessPendingWorksOrders(ProcessWorksOrderDelegate processWorksOrder)
{
foreach (WorksOrder wo in list)
{
if (wo.js.Equals(job_status.Pending))
// Calling the delegate:
processWorksOrder(wo);
}
}*/
// Add a DbConnDetails to the database:
public void AddDbConnDetails(string username, string password, string database, int conn_num)
{
list.Add(new DbConnDetails(username, password, database, conn_num));
}
// Call a passed-in delegate on each dbconndet to process it:
public void ProcessDbConnDetails(ProcessDbConnDetailsDelegate processDBConnDetails)
{
foreach (DbConnDetails wo in list)
{
processDBConnDetails(wo);
}
}
}
// statuses for worksorders in this system
public enum job_status
{
Pending,
InProgress,
Completed
}
public struct DbConnDetails
{
public string username { get; set; } // username
public string password { get; set; } // password
public string database { get; set; } // database
public int conn_num { get; set; } // this objects connection number.
public ArrayList woList { get; set; } // list of works orders for this connection
// this constructor just sets the db connection details
// the woList array will get created later .. not a lot later but a bit.
public DbConnDetails(string username, string password, string database, int conn_num) : this()
{
this.username = username;
this.password = password;
this.database = database;
this.conn_num = conn_num;
woList = new ArrayList();
}
}
// Declare a delegate type for processing a DbConnDetails:
public delegate void ProcessDbConnDetailsDelegate(DbConnDetails dbConnDetails);
}
LoginBox.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WorksOrderFactory
{
public partial class LoginBox : Form
{
public LoginBox()
{
InitializeComponent();
}
private void LoginBox_Load(object sender, EventArgs e)
{
this.Visible = true;
this.Show();
//usernameText.Text = "Username";
//new Font(usernameText.Font, FontStyle.Italic);
}
private void cancelBtn_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginBtn_Click(object sender, EventArgs e)
{
// set up a connection details object.
bool success = WorksOrderClient.createDBConnDetObj(usernameText.Text, passwordText.Text, databaseText.Text);
}
private void LoginBox_Load_1(object sender, EventArgs e)
{
}
}
}
Any ideas??
Cheers,
m
The one thing jumps out when comparing the definition of the delegate with the definition of the method you're trying to use:
static void CreateLabelInPanel(DbConnDetails dbcd)
public delegate void ProcessDbConnDetailsDelegate(DbConnDetails dbConnDetails)
CreateLabelInPanel should probably not be declared as static.
The compiler is just saying that the method you are providing to a delegate is not matching the signature expected by the delegate.
So, in your case.
//To get this line working...
wodb.ProcessDbConnDetails(new ProcessDbConnDetailsDelegate(SomeMethod1));
//The method signature should be like this.
static void SomeMethod1(DbConnDetails dbcd)
//OR even this -- Instance/Static methods can be supplied to same delegate.
void SomeInstanceMethod(DbConnDetails dbcd)..
And if not, the compiler would complain.
Also, by any chance, do you have two classes with the name "DbConnDetails" ???
My best guess is you are referring to "DbConnDetails" that lies in different namespace than the one expected by the delegate.
thanks #amby and #massif and anyone else I may have missed.
This was a school boy error.
It turns out I had another file (which I thought I'd deleted) that also contained a class and constructor called DbConnDetails. I did a search for DbConnDetails in the solution.
I renamed that class/constructor and the filename as well, to be safe.
I then declared
static void CreateLabelInPanel(DbConnDetails dbcd)
which means that the app now compiles/builds again.
Thanks again to everyone.