Can someone shorten this code?
There are 14 Buttons and 8 text Boxes. The action will be perform if the textbox is not empty and if it is not empty, then when you click it the button corresponding with the letter in the textbox will be visible again making the textbox empty.
private void txt1_Click(object sender, EventArgs e)
{
if (txt1.Text == "J")
{
txt1.Text = "";
btn1.Visible = true;
}
else if (txt1.Text == "M")
{
txt1.Text = "";
btn2.Visible = true;
}
else if (txt1.Text == "Y")
{
txt1.Text = "";
btn3.Visible = true;
}
else if (txt1.Text == "E")
{
if (btn4.Visible == true)
{
txt1.Text = "";
btn5.Visible = true;
}
else
{
txt1.Text = "";
btn4.Visible = true;
}
}
else if (txt1.Text == "Q")
{
txt1.Text = "";
btn6.Visible = true;
}
else if (txt1.Text == "L")
{
if (btn7.Visible == true)
{
txt1.Text = "";
btn10.Visible = true;
}
else
{
txt1.Text = "";
btn7.Visible = true;
}
}
else if (txt1.Text == "B")
{
txt1.Text = "";
btn8.Visible = true;
}
else if (txt1.Text == "C")
{
txt1.Text = "";
btn9.Visible = true;
}
else if (txt1.Text == "P")
{
txt1.Text = "";
btn11.Visible = true;
}
else if (txt1.Text == "I")
{
txt1.Text = "";
btn12.Visible = true;
}
else if (txt1.Text == "K")
{
txt1.Text = "";
btn13.Visible = true;
}
else if (txt1.Text == "O")
{
txt1.Text = "";
btn14.Visible = true;
}
}
Assuming all the btn variables are part of the state of your class then you can declare a method like so:
public Button Click(String txt) {
switch(txt) {
case "J":
return btn1;
case "M":
return btn2;
case "Y":
return btn3;
case "E":
return (btn4.Visible ? btn5 : btn4);
case "Q":
return btn6;
case "L":
return (btn7.Visible ? btn10 : btn7);
case "B":
return btn8;
case "C":
return btn9;
case "P":
return btn11;
case "I":
return btn12;
case "K":
return btn13;
case "O":
return btn14;
}
return null;
}
and then you call it:
var button = Click(txt1.Text);
if(button != null) {
button.Visible = true;
txt1.Text = "";
}
If however the btn variables have local scope, than instead of a method you can just define an inline Func<String,Button> delegate as so:
Func<String, Button> Click = txt => {
switch(txt) {
...
}
};
You'd still have to handle the special cases ("E" and "L") but you could use a Dictionary<string, Button> which would allow you to do a lookup:
var buttonDictionary = new Dictionary<string, Button>();
buttonDictionary["J"] = btn1;
buttonDictionary["M"] = btn2;
//etc...
if (buttonDictionary.Keys.Contains(txt1.Text))
{
txt1.Text = "";
buttonDictionary[txt1.Text].Visible = false;
}
That would reduce most of the repetitive code.
Looking at this: I'd suggest you go back think of more logical way to do whatever you're doing.
Out of my experience, any enormous chains of if-else in code represent that there has been a logical issue somewhere.
Also, familiarize yourself with switch statements
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have no clue what the problem is.
Here is my code:
namespace TimeClock
{
public partial class Form1 : Form
{
String Code;
String Name;
String InOut;
String allTextIn;
String allTextOut;
Boolean Joshua = false;
int JoshuaInt = 1;
Boolean Alec = false;
int AlecInt = 3;
Boolean Kyle = false;
int KyleInt = 5;
Boolean Jeffrey = false;
int JeffreyInt = 7;
Boolean Carl = false;
int CarlInt = 9;
Boolean Angela = false;
int AngelaInt = 11;
Boolean Kendra = false;
int KendraInt = 13;
Boolean Susan = false;
int SusanInt = 15;
Boolean Kory = false;
int KoryInt = 17;
Boolean Jeanine = false;
int JeanineInt = 19;
Boolean Daniel = false;
int DanielInt = 21;
Boolean Steven = false;
int StevenInt = 23;
Boolean Jacob = false;
int JacobInt = 25;
Boolean Mario = false;
int MarioInt = 27;
int Index;
String csvPath = "C:/Users/Public/TimeClockData.csv";
StringBuilder Header = new StringBuilder();
StringBuilder csvData = new StringBuilder();
private static SpeechSynthesizer synth = new SpeechSynthesizer();
Thread saveData;
Thread clock;
Thread location;
public Form1()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
TopMost = true;
Header.AppendLine("Timestamp, Name");
File.AppendAllText(csvPath, Header.ToString());
textBox1.Font = new Font("Arial", 30, FontStyle.Bold);
clock = new Thread(new ThreadStart(Clock));
clock.Start();
location = new Thread(new ThreadStart(GetPugsleyLocation));
location.Start();
}
private void Clock()
{
DateTime timeStamp = DateTime.Now;
textBox2.Text = timeStamp.ToString();
}
private void GetPugsleyLocation()
{
Ping ping = new Ping();
string ip = "";
IPAddress address = IPAddress.Parse(ip);
PingReply pong = ping.Send(address);
if (pong.Status == IPStatus.Success)
{
textBox3.Text = "Pugsley is here now";
}
else
{
textBox3.Text = "Pugsley is not here right now";
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
FormBorderStyle = FormBorderStyle.Sizable;
WindowState = FormWindowState.Normal;
TopMost = false;
}
}
public static void SpeakNow(string message)
{
synth.SelectVoiceByHints(VoiceGender.Male);
synth.Speak(message);
synth.Rate = -2;
}
public void saveDataThread()
{
DateTime timeStamp = DateTime.Now;
csvData.AppendLine(timeStamp + "," + Name + "," + InOut);
File.AppendAllText(csvPath, csvData.ToString());
csvData.Clear();
InOut = null;
}
private void Number_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
Code = Code + button.Text;
textBox1.Text = Code;
}
private void Enter_Click(object sender, EventArgs e)
{
//in or out
Button button = (Button)sender;
Name = "";
var list = new List<string>();
list.Add("107");
list.Add("104");
list.Add("115");
list.Add("131");
list.Add("113");
list.Add("112");
list.Add("126");
list.Add("117");
list.Add("130");
list.Add("116");
list.Add("108");
list.Add("133");
list.Add("122");
list.Add("106");
if (list.Contains(Code))
{
if (Code == "107")
{
Name = "Joshua";
Index = JoshuaInt;
if (Joshua == false)
{
InOut = "In";
Joshua = true;
goto done;
}
if (Joshua == true)
{
InOut = "Out";
Joshua = false;
goto done;
}
}
if (Code == "104")
{
Name = "Alec";
Index = AlecInt;
if (Alec == false)
{
InOut = "In";
Alec = true;
goto done;
}
if (Alec == true)
{
InOut = "Out";
Alec = false;
goto done;
}
}
if (Code == "115")
{
Name = "Kyle";
Index = KyleInt;
if (Kyle == false)
{
InOut = "In";
Kyle = true;
goto done;
}
if (Kyle == true)
{
InOut = "Out";
Kyle = false;
goto done;
}
}
if (Code == "131")
{
Name = "Jeffrey";
Index = JeffreyInt;
if (Jeffrey == false)
{
InOut = "In";
Jeffrey = true;
goto done;
}
if (Jeffrey == true)
{
InOut = "Out";
Jeffrey = false;
goto done;
}
}
if (Code == "113")
{
Name = "Carl";
Index = CarlInt;
if (Carl == false)
{
InOut = "In";
Carl = true;
goto done;
}
if (Carl == true)
{
InOut = "Out";
Carl = false;
goto done;
}
}
if (Code == "112")
{
Name = "Angela";
Index = AngelaInt;
if (Angela == false)
{
InOut = "In";
Angela = true;
goto done;
}
if (Angela == true)
{
InOut = "Out";
Angela = false;
goto done;
}
}
if (Code == "126")
{
Name = "Kendra";
Index = KendraInt;
if (Kendra == false)
{
InOut = "In";
Kendra = true;
goto done;
}
if (Kendra == true)
{
InOut = "Out";
Kendra = false;
goto done;
}
}
if (Code == "117")
{
Name = "Susan";
Index = SusanInt;
if (Susan == false)
{
InOut = "In";
Susan = true;
goto done;
}
if (Susan == true)
{
InOut = "Out";
Susan = false;
goto done;
}
}
if (Code == "130")
{
Name = "Kory";
Index = KoryInt;
if (Kory == false)
{
InOut = "In";
Kory = true;
goto done;
}
if (Kory == true)
{
InOut = "Out";
Kory = false;
goto done;
}
}
if (Code == "116")
{
Name = "Jeanine";
Index = JeanineInt;
if (Jeanine == false)
{
InOut = "In";
Jeanine = true;
goto done;
}
if (Jeanine == true)
{
InOut = "Out";
Jeanine = false;
goto done;
}
}
if (Code == "108")
{
Name = "Daniel";
Index = DanielInt;
if (Daniel == false)
{
InOut = "In";
Daniel = true;
goto done;
}
if (Daniel == true)
{
InOut = "Out";
Daniel = false;
goto done;
}
}
if (Code == "133")
{
Name = "Steven";
Index = StevenInt;
if (Steven == false)
{
InOut = "In";
Steven = true;
goto done;
}
if (Steven == true)
{
InOut = "Out";
Steven = false;
goto done;
}
}
if (Code == "122")
{
Name = "Jacob";
Index = JacobInt;
if (Jacob == false)
{
InOut = "In";
Jacob = true;
goto done;
}
if (Jacob == true)
{
InOut = "Out";
Jacob = false;
goto done;
}
}
if (Code == "106")
{
Name = "Mario";
Index = MarioInt;
if (Mario == false)
{
InOut = "In";
Mario = true;
goto done;
}
if (Mario == true)
{
InOut = "Out";
Mario = false;
goto done;
}
}
}
else
{
goto clear;
}
done:
InOut = button.Text;
saveData = new Thread(new ThreadStart(saveDataThread));
saveData.Start();
String[] textIn = System.IO.File.ReadAllLines(#"C:\Users\Public\textIn.txt");
String[] textOut = System.IO.File.ReadAllLines(#"C:\Users\Public\textOut.txt");
allTextIn = textIn[Index];
allTextOut = textOut[Index];
if (InOut == "In")
{
if (allTextIn != "/")
{
SpeakNow(allTextIn);
}
else
{
SpeakNow("Hello" + Name);
}
}
else
{
if (allTextOut != "/")
{
SpeakNow(allTextOut);
}
else
{
SpeakNow("Goodbye" + Name);
}
}
clear:
Code = null;
textBox1.Text = Code;
}
private void Backspace_Click(object sender, EventArgs e)
{
//Backspace
if (Code.Length >= 1)
{
Code = Code.Substring(0, Code.Length - 1);
textBox1.Text = Code;
}
}
private void Clear_Click(object sender, EventArgs e)
{
//Clear
Code = null;
textBox1.Text = Code;
}
}
}
It runs for a couple of seconds, then crashes. I am newish to C# and visual studio. Like I said, I have no clue what the problem is. I read that it might be caused by the threads changing the UI, but another version worked with the threads changing the UI, so I have no clue. Please help me!
You can't access the UI directly from your threads like you're doing.
Call Invoke on your controls first:
private void Clock()
{
textBox2.Invoke(new Action(() => textBox2.Text = DateTime.Now.ToString()));
}
private void GetPugsleyLocation()
{
...
...
textBox3.Invoke(new Action(() =>
textBox3.Text = "Pugsley is " + (pong.Status == IPStatus.Success ? "" : "not") + " here now"));
}
I've got to make a calculator for school, everything works except the minus button: 5-5 = -5 for example.
I know that the problem exists somewhere in my case "minus" but I just
can't get it figured out..
Here's the code.
Most of the variables are in dutch, I hope that won't be a problem!
Note: this problem exists when i do this: 5 - 5, so not using the equals button.
private int totaal = 0;
private Boolean lastClicked, equalsPressed, tussen = false;
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
switch(((Button)sender).Name){
case "one":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "1";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "1";
}
break;
case "two":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "2";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "2";
}
break;
case "three":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "3";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "3";
}
break;
case "four":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "4";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "4";
}
break;
case "five":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "5";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "5";
}
break;
case "six":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "6";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "6";
}
break;
case "seven":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "7";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "7";
}
break;
case "eight":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "8";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "8";
}
break;
case "nine":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "9";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "9";
}
break;
case "zero":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "0";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "0";
}
break;
case "plus":
totaal = totaal + Convert.ToInt32(uitkomstBox.Text);
uitkomstBox.Text = totaal.ToString();
tussen = true;
lastClicked = true;
break;
case "minus":
totaal = totaal - Convert.ToInt32(uitkomstBox.Text);
uitkomstBox.Text = totaal.ToString();
tussen = true;
lastClicked = false;
break;
case "clear":
uitkomstBox.Text = "";
totaal = 0;
break;
case "equals":
if (lastClicked)
{
uitkomstBox.Text = (totaal + Convert.ToInt32(uitkomstBox.Text)).ToString();
}
else
{
uitkomstBox.Text = (Convert.ToInt32(uitkomstBox.Text) - totaal).ToString();
}
equalsPressed = true;
totaal = 0;
break;
}
}
}
}
The problem is that you are subtracting the number twice. Once in the switch statement and then again here:
if (lastClicked)
{
uitkomstBox.Text = (totaal + Convert.ToInt32(uitkomstBox.Text)).ToString();
}
else
{
// You have already subtracted the number but then you are subtracting it again!
uitkomstBox.Text = (Convert.ToInt32(uitkomstBox.Text) - totaal).ToString();
}
It's the logic of the plus and minus buttons you need to check.
Take yourself through the code step by step.
In the beginning, totaal = 0 and uitkomnstBox.Text is empty. Then you click "5". So uitkomstBox.Text is "5". Then you click the "minus" button. totaal now changes to -5. i.e. before you have even entered a number to subtract from it. Then you click "5" again (to complete 5 - 5) but totaal doesn't change in this case until you click the equals button, at which point it hits that lastClicked logic which I don't really get... (I think it should end up as zero after that but you said the problem exists if you don't click "equals").
So it's not just that you're subtracting twice but you're subtracting before you even have a number to subtract.
As a possible solution, what I'd suggest is something like this: execute the logic of the operation ("plus" or "minus") after the next number is complete.
i.e. When someone clicks "minus" save this in memory somewhere until they have finished entering the next number, then subtract it from the total, or if they clicked "plus" add it. For the first number, process "plus" (e.g. 5 - 5 is processed as if it was entered as + 5 - 5)
private char operation = '+'; // Default first operation to "plus"
// Your other code...
// ...
// ...
case "plus" :
if (operation == '+') {
totaal += Convert.ToInt32(uitkomnstBox.Text);
}
if (operation == '-') {
totaal -= Convert.ToInt32(uitkomnstBox.Text);
}
operation = '+';
// anything else you want
break;
case "minus" :
if (operation == '+') {
totaal += Convert.ToInt32(uitkomnstBox.Text);
}
if (operation == '-') {
totaal -= Convert.ToInt32(uitkomnstBox.Text);
}
operation = '-';
// anything else you want
break;
case "equals" :
if (operation == '+') {
totaal += Convert.ToInt32(uitkomnstBox.Text);
}
if (operation == '-') {
totaal -= Convert.ToInt32(uitkomnstBox.Text);
}
operation = '+'; // Set back to default for next calculation
// anything else you want
break;
It looks like you are subtracting from totaal twice. Are you sure that adding works correctly? Check the code for your "=" button.
Also, maybe consider storing numbers for calculation in some counter int (or any other number type, if you are planning to allow fractions), rather than in textbox, since then you have to convert it back and forth just for the calculation.
What am I doing wrong here?
At the end of the function, I'm returning the result.
public bool isStipends()
{
try
{
bool result = true;
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
else
{
return result;
}
}
catch
{
return false;
}
}
In the code behind of the button, I call:
private void btnupdatestipends_Click(object sender, EventArgs e)
{
try
{
if (isStipends() == true)
{
MessageBox.Show("TEST");
}
}
catch { }
}
However, it gives me an error on the function itself.
Error 3 'AddressBookMaint.Form1.isStipends()': not all code paths return a value C:\Win\AddressBookMaint\AddressBookMaint\Form1.cs 5040 22 AddressBookMaint
Any suggestions?
Thank you.
Error 1
You are only returning if none of the if's are true since the `return` is in the last `else` clause.
Solution
Break out the `return` from the last `else` and place it in the `try` block *(or even outside of the try/catch and you will solve error 2 as well)*.
Error 2
You will only return if there are no exceptions since you have the `return` at the end of the `try` block and no `return` in the `catch` block.
Solution
Add a `return` in the `catch` block and the code will compile.
Here's a working version of your code
public bool isStipends()
{
bool result = true;
try
{
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
}
catch
{
result = false;
}
return result;
}
You either need to return something in your catch:
public bool Method() {
try {
return true;
}
catch {
return false;
}
}
Or just return a single value at the bottom:
public bool Method() {
bool result = false;
try {
...
result = true;
}
catch {}
return result;
}
replace your method isStipends by this on:
public bool isStipends()
{
try
{
bool result = true;
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
return result;
}
catch { }
}
Your code only specifies the return in the final else block. In all your other code paths, including the catch block, you haven't specified any return value. You can drop that final else block and add a return value at the end of your function, like this:
public bool isStipends()
{
bool result = true;
try
{
...
}
catch
{
result = false;
}
return result;
}
However, catching all exceptions like this is very bad practice, and you certainly don't need to do it inside every function. You should only catch the exceptions you can meaningfully handle and allow the rest to bubble up. Set a global unhandled exception if need be to gracefully bail out of your application.
See Best Practices for Exceptions
The error is telling you that there are ways that do not return any value, if there is a mistake your catch instruction will returns nothing.
returns some value in your instruction catch.
You are not returning anything anywhere in your code... except for your last else statement. To compile all paths should return a bool value for your method. You should return a value in every if or if else and else statement, and in your catch block.
This will work:
public bool isStipends()
{
try
{
bool result = true;
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
else
{
return result;
}
}
catch
{
return false;
}
return result;
}
I have some label controls in a panel with id ResultsPanel. To find the label controls on the page, I did the following:
for (int ctr = 0; ctr < lblString.Length - 1; ctr++)
{
//string labelID = string.Format("lblResult{0}", ctr);
int mylbl = ctr + 1;
string lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString())).Text;
lblResult = lblString[mylbl].ToString();
}
lblResult1.Text = lblString.ToString();
lblString is a stringBuilder Object with 24 numbers. The Idea is to map each of the numbers in the stringbuilder object to labels in this manner:
lblResult1.Text = lblString[mylbl].ToString(); to the 24th label. But I can't seem to generate the labels and map the values to the label control.
Change the line to
Label lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString()));
lblResult.Text = lblString[mylbl].ToString();
Your question and code are a bit misleading, but I will try my best anyway.
Your code:
for (int ctr = 0; ctr < lblString.Length - 1; ctr++)
{
//string labelID = string.Format("lblResult{0}", ctr);
int mylbl = ctr + 1;
string lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString())).Text;
lblResult = lblString[mylbl].ToString();
}
lblResult1.Text = lblString.ToString();
If you have labels in the order of label1, label2, label3 ... then I would write something like this:
private void MapLabels()
{
var labelsResult = string.Empty;
var labelString = "123456789";
for (int i = 0; i < labelString.Length; i++)
{
var control = this.FindControl("label" + labelString[i]);
if(control != null)
{
labelsResult += ((Label)control).Text;
}
}
labelResult1.Text = labelsResult;
}
Let me know if you get stuck.
Hope this will help you. Like this you can get the value of label too.
public void GetControlsValuePopulated(Control control, Type controlType, Dictionary<string, string> dictControlPageValParam)
{
try
{
if (control.HasControls())
{
GetControlsValuePopulated(control, controlType, dictControlPageValParam);
}
else
{
if (controlType == null || controlType.IsAssignableFrom(control.GetType()))
{
if (control.ID != null)
{
bool FoundControl = dictControlPageValParam.ContainsKey(control.ID.Substring(3));
if (FoundControl)
{
switch (control.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
TextBox txt = (TextBox)control;
txt.Text = dictControlPageValParam[txt.ID.Substring(3)];
break;
case "System.Web.UI.WebControls.CheckBox":
CheckBox chk = (CheckBox)control;
if (dictControlPageValParam[chk.ID.Substring(3)].ToUpper() == "TRUE" || dictControlPageValParam[chk.ID.Substring(3)].ToUpper() == "T")
{
chk.Checked = true;
}
else
{
chk.Checked = false;
}
break;
case "System.Web.UI.WebControls.DropDownList":
DropDownList ddl = (DropDownList)control;
//ddl.SelectedValue = dictControlPageValParam[ddl.ID.Substring(3)];
break;
case "System.Web.UI.WebControls.RadioButtonList":
RadioButtonList rbl = (RadioButtonList)control;
rbl.SelectedValue = dictControlPageValParam[rbl.ID.Substring(3)];
break;
case "System.Web.UI.WebControls.HiddenField":
HiddenField hdn = (HiddenField)control;
hdn.Value = dictControlPageValParam[hdn.ID.Substring(3)];
break;
}
}
}
}
}
}
catch (Exception)
{
throw;
}
}
public void GetChildControlsId(Control control, Type controlType)
{
try
{
if (control.HasControls())
{
GetChildControlsId(control, controlType);
}
else
{
if (controlType == null || controlType.IsAssignableFrom(control.GetType()))
{
///checking if control already existing in the collection
if (control.ID != null)
{
bool FoundControl = controlHt.ContainsKey(control.ID);
if (!FoundControl)
{
switch (control.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
TextBox txt = (TextBox)control;
controlTypeName = txt.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = txt.Text;
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.CheckBox":
CheckBox chk = (CheckBox)control;
controlTypeName = chk.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = chk.Checked.ToString();
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.DropDownList":
DropDownList ddl = (DropDownList)control;
controlTypeName = ddl.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = ddl.SelectedValue.ToString();
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.RadioButtonList":
RadioButtonList rbl = (RadioButtonList)control;
controlTypeName = rbl.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = rbl.SelectedValue.ToString();
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.HiddenField":
HiddenField hdn = (HiddenField)control;
controlTypeName = hdn.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = hdn.Value;
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
}
}
}
}
}
}
catch (Exception)
{
throw;
}
}
i have the following code in WPA, and i am trying to convert it to WPF. I tried Keydown instead of Keypress and changed, for example,
(e.keyChar == '-') to (e.key == e.Subtract):
its not working the same
I cant find the equal sign within e.key
first code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
foreach (TextBox tb in this.Controls.OfType<TextBox>())
{
tb.Enter += textBox_Enter;
}
}
void textBox_Enter(object sender, EventArgs e)
{
focusedTextbox = (TextBox)sender;
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '+')
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 1;
e.Handled = true;
}
else if (e.KeyChar == '-')
{
if (focusedTextbox != null)
{
if (focusedTextbox.Text == "")
{
e.Handled = false;
}
else
{
e.Handled = true;
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 2;
}
}
}
else if (e.KeyChar == '*')
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 3;
e.Handled = true;
}
else if (e.KeyChar == '/')
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 4;
e.Handled = true;
}
else if (e.KeyChar == '=')
{
e.Handled = true;
operand2.Real = getOperand.Real;
operand2.Imag = getOperand.Imag;
switch (flag1)
{
case 1:
operand1 = operand1 + operand2;
break;
case 2: operand1 = operand1 - operand2;
break;
case 3:
operand1 = operand1 * operand2;
break;
case 4:
if (operand2.Magnitude == 0)
{
textBox1.Clear();
textBox2.Clear();
MessageBox.Show("Cannot divide by a number whose magnitude is zero");
operand1 = new Complex();
operand2 = new Complex();
listBox1.ClearSelected();
}
else
operand1 = operand1 / operand2;
break;
}
string s = operand1.ToString();
if (flag == 1)
{
string[] s1 = s.Split(' ');
if (s1[1] == "-")
{
textBox1.Text = s1[0];
textBox2.Text = "-" + s1[3];
}
else
{
textBox1.Text = s1[0];
textBox2.Text = s1[3];
}
}
else if (flag == 2)
{
string[] s1 = s.Split('#');
textBox1.Text = s1[0].Trim();
textBox2.Text = s1[1].Trim();
}
listBox1.Items.Add(operand1);
}
}
second code:
private void win_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Add)
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 1;
e.Handled = true;
}
else if (e.Key == Key.Subtract)
{
if (textBox2.Text == "")
{
e.Handled = false;
}
else
{
e.Handled = true;
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 2;
}
}
else if (e.Key == Key.Multiply)
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 3;
e.Handled = true;
}
else if (e.Key == Key.Divide)
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 4;
e.Handled = true;
}
else if (e.Key == Key.Enter)
{
e.Handled = true;
operand2.Real = getOperand.Real;
operand2.Imag = getOperand.Imag;
switch (flag1)
{
case 1:
operand1 = operand1 + operand2;
break;
case 2: operand1 = operand1 - operand2;
break;
case 3:
operand1 = operand1 * operand2;
break;
case 4:
if (operand2.Magnitude == 0)
{
textBox1.Clear();
textBox2.Clear();
MessageBox.Show("Cannot divide by a number whose magnitude is zero");
operand1 = new Complex();
operand2 = new Complex();
listBox1.UnselectAll();
}
else
operand1 = operand1 / operand2;
break;
}
string s = operand1.ToString();
if (flag == 1)
{
string[] s1 = s.Split(' ');
if (s1[1] == "-")
{
textBox1.Text = s1[0];
textBox2.Text = "-" + s1[3];
}
else
{
textBox1.Text = s1[0];
textBox2.Text = s1[3];
}
}
else if (flag == 2)
{
string[] s1 = s.Split('#');
textBox1.Text = s1[0].Trim();
textBox2.Text = s1[1].Trim();
}
listBox1.Items.Add(operand1);
}
}
It's very similar - but you compare e.Key to the Key enumeration.
Register your event handler somewhere (such as the constructor, or window_loaded):
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
}
And then in the event handler:
void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Subtract)
{
// Do something
}
}
You're looking for the TextInput event, or perhaps PreviewTextInput.
The EventArgs type is TextCompositionEventArgs; I believe you want the Text property here, but I'm not at all sure of that.
<TextBox x:Name="txtbx" KeyDown="OnKeyDownHandler" Height="23" Width="250">
</TextBox>
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
txtbx.Text = "You Entered: " + txtbx.Text;
}
}