Link combo box and parallel array - c#

I need help linking or mapping a combo box to a parallel array in C#. I have a class project where I need to create a payroll system that displays the Net Pay after taxes.
I want to link parallel arrays that have all the employee information needed for payroll to the option selected in the combo box. I feel like I almost have it, but I don't know how to link the option selected from the combo box and the parallel arrays I have set up.
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 ZNSPayrollSystem
{
public partial class ZNSPayrollSystem : Form
{
public ZNSPayrollSystem()
{
InitializeComponent();
string[] arr = { "001 Peters", "002 Barnes", "003 Harris" };
cboEmp.DataSource = arr.ToArray();
}
private void btnCalc_Click(object sender, EventArgs e)
{
//parallel arrays
int[] empID = { 001, 002, 003 };
string[] empName = { "James Peters", "Sarah Barnes", "Candice Harris" };
double[] hrsWorked = { 40, 40, 40 };
double[] empWage = { 55.50, 65.50, 75.70 };
//declarations
double dblTaxRate = 8.2 / 100;
double dblNetPay;
double dblGrossPay;
double dblTaxWithheld;
dblGrossPay = hrsWorked[] * empWage[];
dblTaxWithheld = dblGrossPay * dblTaxRate;
dblNetPay = dblGrossPay - dblTaxWithheld;
txtGross.Text = dblGrossPay.ToString();
txtTax.Text = dblTaxWithheld.ToString();
txtNetPay.Text = dblNetPay.ToString();
}
}
}

Use the SelectedIndex property of the Combobox:
int i = cboEmp.SelectedIndex;
if (i != -1)
{
dblGrossPay = hrsWorked[i] * empWage[i];
}
i == -1 means nothing is selected. You may want to handle this separately to avoid getting any exceptions.

Related

Unwanted labels appear on RangeBar chart AxisX when adding data

I have a Chart (RangeBarChart) with a ChartArea attached to it. The ChartArea has one Series attached to it. I also have a List<string>, this stringlist is filled with the values I want the Axislabels on my AxisX to have. In my example screenshot, this stringlist contains 6 strings.
All the 6 labels are named correct, but at the upper and lower limits of my AxisX, the labels are numbered as well, see screenshot (upper part, '-1' and the '6' labels are undesired).
Screenshot link: https://imgur.com/a/pwYF4yl
I add data to my chart with two lines of code in a foreach loop. I found that when I comment out these two lines, the extra numbers on my axis don't appear, but obviously this is a non-solution, as I'm also not showing any data. I also can't delete the labels manually in code because I have no pointIndices pointing to them. When looking at my series.Points[] collection in the debugger, all their X-values are between 0 and 5 (also in screenshot).
How can I get rid of these labels?
I recreated the unwanted behaviour in a quick test project, just add a Chart called 'chart' in the designer and copy this code in the code part of your main form and you can recreate the problem for yourself.
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.Windows.Forms.DataVisualization.Charting;
namespace XAxisLabelsNumbersTest
{
public partial class Form1 : Form
{
ChartArea ca;
Series serie;
List<string> xLabels = new List<string> {"Label1", "Label2", "Label3", "Label4", "Label5", "Label6"};
List<myObj> myObjList = new List<myObj>();
public class myObj
{
public Int32 begin { get; set; }
public Int32 end { get; set; }
public int xcord { get; set; }
public int pointIndex { get; set; }
public string label { get; set; }
public myObj(Int32 begin, Int32 end, string label)
{
this.begin = begin;
this.end = end;
this.label = label;
}
}
public Form1()
{
InitializeComponent();
// Setting some properties regarding chart behaviour
ca = chart.ChartAreas.Add("ca");
serie = chart.Series.Add("serie");
serie.ChartArea = ca.Name;
serie.ChartType = SeriesChartType.RangeBar;
serie.XValueType = ChartValueType.String;
serie.YValueType = ChartValueType.Int32;
serie["PixelPointWidth"] = "10";
//ca.AxisY.LabelStyle.Format = "HH:mm tt";
ca.AxisX.MajorGrid.Interval = 1;
ca.AxisY.Minimum = 0;
ca.AxisY.Maximum = 6;
Title title = new Title("Title");
chart.Titles.Add(title);
title.DockedToChartArea = ca.Name;
title.IsDockedInsideChartArea = false;
title.Font = new Font("Serif", 18);
ca.AxisX.LabelAutoFitStyle = LabelAutoFitStyles.None;
ca.AxisX.LabelStyle.Font = new Font("Trebuchet MS", ca.AxisX.LabelAutoFitMaxFontSize, FontStyle.Bold);
ca.AxisX.LabelStyle.Interval = 1;
// Create Labels from xLabels
for (int i = 0; i < xLabels.Count; i++)
{
int pi = serie.Points.AddXY(i, null, null);
serie.Points[pi].AxisLabel = xLabels[i];
}
// Fill myObjList with testdata
myObjList.Add(new myObj(0, 1, "Label1"));
myObjList.Add(new myObj(1, 2, "Label2"));
myObjList.Add(new myObj(2, 3, "Label3"));
myObjList.Add(new myObj(3, 4, "Label4"));
myObjList.Add(new myObj(4, 5, "Label5"));
myObjList.Add(new myObj(5, 6, "Label6"));
// Fill serie with data from myObjList
// Comment out this foreach block and the weird label numbering is gone...
foreach (myObj myObj in myObjList)
{
myObj.xcord = xLabels.FindIndex(Label => Label.Equals(myObj.label));
myObj.pointIndex = serie.Points.AddXY(myObj.xcord, myObj.begin, myObj.end);
}
}
}
}
You can hide both 'endlabels' by setting this axis property: Axis.LabelStyle.IsEndLabelVisible:
ca.Axis.LabelStyle.IsEndLabelVisible = false;

Label Text won't update C# - Refresh and Application.DoEvents do not work

Thank you for checking out my thread.
So, my little cousin has this 'exam' at the end of his school year, where he needs to choose various words synonyms. I decided this would be a pretty good opportunity to practise my C# skills (which are pretty non-existent).
Originally I started out by writing the program as a simple Python script.
However, I think it should be easier for a kid to learn those stuff if there's an actual interface to the program, so I decided on using Visual C# to create this "simple" quiz - a good opportunity to practise the language.
I want the program to change the labels, according to the question - I've written two functions in Form1
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string LabelText
{
get
{
return this.label12.Text;
}
set
{
this.label12.Text = value;
}
}
public void UpdateQuestion(string QNum)
{
LabelText = QNum;
label12.Refresh();
Application.DoEvents();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label11_Click(object sender, EventArgs e)
{
}
private void label12_Click(object sender, EventArgs e)
{
}
}
but both do not seem to change the value of the label, when I use them in my Main.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 NewForm = new Form1();
Application.Run(NewForm);
string[][] list = new string[10][];
list[0] = new[] { "abandon", "leave" };
list[1] = new[] { "abbreviate", "shorten" };
list[2] = new[] { "option", "choice" };
list[3] = new[] { "Inferior", "lesser", "second-class", "second-fiddle", "minor", "subservient", "lowly", "humble", "menial" };
list[4] = new[] { "Nauseous", "sick", "nauseated", "queasy", "bilious" };
list[5] = new[] { "Uniform", "constant", "consistent", "steady", "invariable", "unvarying", "unfluctuating", "unvaried", "unchanging", "unwavering", "undeviating", "stable", "static", "sustained", "regular", "fixed", "even", "equal", "equable", "monotonous" };
list[6] = new[] { "Incision", "cut", "opening", "slit" };
list[7] = new[] { "perplexed", "puzzled" };
list[8] = new[] { "polarity", "difference", "separation", "opposition", "contradiction" };
list[9] = new[] { "Abundance", "profusion", "plenty", "wealth", "copiousness" };
for (int counter = 0; counter < 20; counter++) {
NewForm.UpdateQuestion("Question Number");
}
}
}
If I use the methods inside my Constructor they work. Refreshing does not work either.
Thank you so much in advance, I hope that someone will be able to help me!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 NewForm = new Form1();
Application.Run(NewForm); // program stops executing here and goes to draw your form
//program resumes execution here after you close your form.
string[][] list = new string[10][];
list[0] = new[] { "abandon", "leave" };
list[1] = new[] { "abbreviate", "shorten" };
list[2] = new[] { "option", "choice" };
list[3] = new[] { "Inferior", "lesser", "second-class", "second-fiddle", "minor", "subservient", "lowly", "humble", "menial" };
list[4] = new[] { "Nauseous", "sick", "nauseated", "queasy", "bilious" };
list[5] = new[] { "Uniform", "constant", "consistent", "steady", "invariable", "unvarying", "unfluctuating", "unvaried", "unchanging", "unwavering", "undeviating", "stable", "static", "sustained", "regular", "fixed", "even", "equal", "equable", "monotonous" };
list[6] = new[] { "Incision", "cut", "opening", "slit" };
list[7] = new[] { "perplexed", "puzzled" };
list[8] = new[] { "polarity", "difference", "separation", "opposition", "contradiction" };
list[9] = new[] { "Abundance", "profusion", "plenty", "wealth", "copiousness" };
for (int counter = 0; counter < 20; counter++) {
NewForm.UpdateQuestion("Question Number");
}
}
}
The problem is with the structure of your code.
After the application starts a new form, it stops executing you code after the line Application.Run (NewForm);
After that line is executed, the application renders the new form and waits for you to interact with the form. The only time program execution would get to the line
string[][] list = new string[10][];
is when you exit the program and by that time your form is already gone. So you could put your logic in the constructor. Or look for a more efficient way to do it.

convert visio vba method into c#

Hello I would like to convert this vba method into C#. I am trying to get the IDs of a selection and print them out. In particular I am having trouble converting the GetIDs() method(a built in method within visio vba) into C#.
Public Sub getCapabilityRectIDs()
Dim vsoSelection1 As Visio.Selection
Dim selectionIDs() As Long
Set vsoSelection1 = Application.ActiveWindow.Page.CreateSelection(visSelTypeByLayer, visSelModeSkipSuper, "Capability")
Application.ActiveWindow.Selection = vsoSelection1
Call vsoSelection1.GetIDs(selectionIDs)
For i = 0 To UBound(selectionIDs)
Debug.Print selectionIDs(i)
Next i
End Sub
This is what I have so far in C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Visio = Microsoft.Office.Interop.Visio;
class Program
{
static void Main(string[] args)
{
//create the object that will do the drawing
VisioDrawer Drawer = new VisioDrawer();
Drawer.selectShpLayer("Capability");
}
}
class VisioDrawer
{
public Visio.Application VisApp;
public static Visio.Page acPage;
public Visio.Selection LayerSelection;
public VisioDrawer()
{
//create the application
VisApp = new Visio.Application();
VisApp.Documents.Open(#"............. - abc.vsdm");
ActiveDoc = VisApp.ActiveDocument;
acPage = VisApp.ActivePage;
}
public void selectShpLayer (string layerName){
Int i = 0;
long[] lngRowIDs;
//this selects the shapes of the selected layer
LayerSelection = acPage.CreateSelection(Microsoft.Office.Interop.Visio.VisSelectionTypes.visSelTypeByLayer, Microsoft.Office.Interop.Visio.VisSelectMode.visSelModeOnlySuper,layerName);
LayerSelection.GetIDs(lngRowIDs);
for (i = 0; i < lngRowIDs.Length; i++)
{
Debug.Write(lngRowIDs[i]);
}
}
}
Thanks in advance!
I created a visio doc and drew 3 simple shapes. I then created a layer called "cool" and added those 3 shapes to it.
I don't understand enough about the shape selection, you had visSelModeOnlySuper which may work for you, but did not work for the case I created. The default is visSelModeSkipSuper (which worked for me)
Here's the API page that describes how to use the createSelection:
https://msdn.microsoft.com/en-us/library/office/ff765565.aspx
Here is my sample code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Visio = Microsoft.Office.Interop.Visio;
class Program
{
static void Main(string[] args)
{
//create the object that will do the drawing
VisioDrawer Drawer = new VisioDrawer();
Drawer.selectShpLayer("cool");
}
}
class VisioDrawer
{
public Visio.Application VisApp;
public static Visio.Page acPage;
public Visio.Selection LayerSelection;
public VisioDrawer()
{
//create the application
VisApp = new Visio.Application();
VisApp.Documents.Open(#"c:\temp\trial.vsdm");
acPage = VisApp.ActivePage;
}
public void selectShpLayer(string layerName)
{
int i = 0;
int[] lngRowIDs;
Array lngRowIDArray;
//this selects the shapes of the selected layer
LayerSelection = acPage.CreateSelection(Microsoft.Office.Interop.Visio.VisSelectionTypes.visSelTypeByLayer, Microsoft.Office.Interop.Visio.VisSelectMode.visSelModeSkipSuper, layerName);
LayerSelection.GetIDs(out lngRowIDArray);
lngRowIDs = (int[])lngRowIDArray;
for (i = 0; i < lngRowIDs.Length; i++)
{
Debug.Write("Object ID: " + lngRowIDs[i].ToString() + "\n");
}
}
}
And it produces this output:
Object ID: 1
Object ID: 2
Object ID: 3
If you change the debug line to this:
Debug.Write("Object ID: " + lngRowIDs[i].ToString() + " -- " + acPage.Shapes.ItemFromID[i].Name + "\n");
The output gets even more useful:
Object ID: 1 -- ThePage
Object ID: 2 -- Circle
Object ID: 3 -- Rectangle

Altering string array value with radio button

I'm having an issue with altering the value of a string array based on what radio button is selected, it's written in C# using Visual Studio 2013 professional.
Basically all that needs to happen is if the radio button called "smallCarRadBtn" is selected, then the string array call "carSize" has to hold the word "Small", and likewise for the other two radio buttons "medCarRadBtn" and "largeCarRadBtn".
At the moment it is telling me:
"Cannot implicitly convert type 'char' to 'string[]'
I have 'highlighted' the area that contains the code for this with asterisks'*'. Any help would be appreciated.
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 Assignment2
{
public partial class Form1 : Form
{
TimeSpan daysHiredIn;
DateTime startDate, endDate;
DateTime dateToday = DateTime.Today;
public static string[] names = new string[50];
public static string[] carSize = new string[50];
public static int[] cardNumb = new int[50];
public static int[] cost = new int[50];
public static TimeSpan[] daysHired = new TimeSpan[50];
public static int entryCount = 0, cardNumbIn, carFee = 45, intDaysHired;
public Form1()
{
InitializeComponent();
smallCarRadBtn.Checked = true;
}
private void confirmBtn_Click(object sender, EventArgs e)
{
if (entryCount >= 50)
{
MessageBox.Show("Arrays are Full");//if array is full
}
else if (nameTxtBox.Text == "")
{
MessageBox.Show("You must enter a name");//Nothing entered
}
else if (!int.TryParse(cardNumbTxtBox.Text, out cardNumbIn))
{
MessageBox.Show("You must enter an integer number");
cardNumbTxtBox.SelectAll();
cardNumbTxtBox.Focus();
return;
}
else if (hireStartDatePicker.Value < dateToday)
{
MessageBox.Show("You cannot enter a date earlier than today");
}
else if (hireEndDatePicker.Value < dateToday)
{
MessageBox.Show("You cannot enter a date earlier than today");
}
else
{
*******************************************************************************************
if (smallCarRadBtn.Checked)
{
carSize = ("small"[entryCount]);
}
else if (MedCarRadBtn.Checked)
{
carSize = ("Medium"[entryCount]);
}
else if (largeCarRadBtn.Checked)
{
carSize = ("Large"[entryCount]);
}
*******************************************************************************************
names[entryCount] = nameTxtBox.Text;
cardNumb[entryCount] = cardNumbIn;
endDate = (hireEndDatePicker.Value);
startDate = (hireStartDatePicker.Value);
daysHiredIn = (endDate - startDate);
cost[entryCount] = (carFee * daysHiredIn);
daysHired[entryCount] = daysHiredIn;
entryCount++;
nameTxtBox.SelectAll();
nameTxtBox.Focus();
}
}
private void viewBtn_Click(object sender, EventArgs e)
{
for (entryCount = 0; entryCount < 50; entryCount++)
{
listBox1.Items.Add(names[entryCount]+"\t"+daysHired[entryCount].Days.ToString());
}
}
}
}
carSize is an array of strings but you are trying to assign it a char:
carSize = ("small"[entryCount]);
Here the "small" is a string, and "small"[entryCount] returns the character at the index entryCount
You should change carSize to char[] if you want to stores characters, and set the elements using indexer instead of assigning the array directly. Or if you want to store the text + entryCount then you should concatenate strings:
carSize[index] = "small" + entryCount;
Or if you just want to set carSize[entryCount] then:
carSize[entryCount] = "small";

Morse code converter only outputs one character c#

I am trying to get the outputLabel to be a label control box where the morse code will output to. I am not sure why only the first morse code character is displayed but not the rest of the code. (if I type "cat" I only get first morse code character in outlabel)
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 MorseCode
{
public partial class morseCodeForm : Form
{
public morseCodeForm()
{
InitializeComponent();
}
//Anthony Rosamilia
//Make a key,value system to translate the user text.
//Make sure usertext appears only in lower case to minimise errors.
private void convertButton_Click(object sender, EventArgs e)
{
Dictionary<char, String> morseCode = new Dictionary<char, String>()
{
{'a' , ".-"},{'b' , "-..."},{'c' , "-.-."}, //alpha
{'d' , "-.."},{'e' , "."},{'f' , "..-."},
{'g' , "--."},{'h' , "...."},{'i' , ".."},
{'j' , ".---"},{'k' , "-.-"},{'l' , ".-.."},
{'m' , "--"},{'n' , "-."},{'o' , "---"},
{'p' , ".--."},{'q' , "--.-"},{'r' , ".-."},
{'s' , ".-."},{'t' , "-"},{'u' , "..-"},
{'v' , "...-"},{'w' , ".--"},{'x' , "-..-"},
{'y' , "-.--"},{'z' , "--.."},
//Numbers
{'0' , "-----"},{'1' , ".----"},{'2' , "..----"},{'3' , "...--"},
{'4' , "....-"},{'5' , "....."},{'6' , "-...."},{'7' , "--..."},
{'8' , "---.."},{'9' , "----."},
};
string userText = inputTextBox.Text;
userText = userText.ToLower();
for (int index = 0; index < userText.Length; index++)
{
/* if (index > 0)
{
outLabel.Text = ('/').ToString();
}
*/char t = userText[index];
if (morseCode.ContainsKey(t))
{
outLabel.Text = (morseCode[t]);
}
}
}
private void clearButton_Click(object sender, EventArgs e)
{
inputTextBox.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
outLabel.Text = (morseCode[t]);
You're setting the Text property to a completely new value, not appending. Wouldn't it be odd if that assignment did append a string to what was already there?
You need to preserve the old value:
outLabel.Text += morseCode[t];
That, however, creates a new string every time you append. Better solution; build the string up with a StringBuilder first, i.e., a mutable string.
var sb = new StringBuilder();
for (int index = 0; index < userText.Length; index++)
{
var t = userText[index].ToLower();
string morseValue;
// no need for ContainsKey/[], use a single lookup
if (morseCode.TryGetValue(t, out morseValue))
{
sb.Append(morseValue);
}
}
outLabel.Text = sb.ToString();

Categories