I'm a big fan of simplifying code to enable extensibility. I have tried to simplify this piece of code but I just keep getting stuck. Does anyone know how I can simplify this code as it contains a lot of ugly if if if's. The reason for the over complications is the amount of variables being passed in to the method. These are all required.
Thanks
private void SetVisibility(int AuctionID, int BidStatus, int LoginErrorCode, int IsHome, bool IsGetMoreTokens)
{
this._dealBidPlacedControl.Visible = false;
this._dealBidControl.Visible = false;
this._loginReg.Visible = false;
this._deals.Visible = false;
if (AuctionID > 0)
{
if (LoginErrorCode == 0)
{
if (BidStatus > 0)
{
this._dealBidPlacedControl.Visible = true;
}
else
{
this._dealBidControl.Visible = true;
}
}
else
{
this._loginReg.LoginErrorType = LoginErrorCode;
this._loginReg.Visible = true;
this._deals.Visible = true;
}
}
else
{
this._loginReg.Visible = true;
this._deals.Visible = true;
}
if (IsGetMoreTokens)
{
this._getMoreTokens.Visible = true;
this._loginReg.Visible = false;
this._deals.Visible = false;
}
// set the hidden field which can be used to set visibility if included in a tab control or anything
// by the parent site
if (this.AuctionID > 0 || BidStatus > 0 || IsHome > 0 || LoginErrorCode > 0 || IsGetMoreTokens)
this._visibilityStatus.Value = "1";
}
You can use boolean expressions, like this:
this._dealBidPlacedControl.Visible = AuctionId > 0 && LoginErrorCode == 0 && BidStatus > 0;
this._dealBidControl.Visible = AuctionId > 0 && LoginErrorCode == 0 && BidStatus <= 0;
this._loginReg.Visible = AuctionID > 0 && LoginErrorCode != 0;
this._deals.Visible = LoginErrorCode != 0 && !IsGetMoreTokens;
Also, you can use enums or booleans instead of ids and codes. HasAuction is clearer than AuctionId > 0.
You could try to simplify your code with directly setting the boolean values instead of creating if-statements and assigning true:
_dealBidPlacedControl.Visible = AuctionID > 0 && LoginErrorCode == 0 && BidStatus > 0
Example:
bool hasAuction = AuctionID > 0;
bool hasLoginError = LoginErrorCode != null;
bool hasBidStatus = BidStatus > 0;
this._dealBidPlacedControl.Visible = hasAction && !hasLoginError && hasBidStatus;
this._dealBidControl.Visible = hasAction && !hasLoginError && !hasBidStatus;
this._loginReg.Visible = this._deals.Visible = !hasAction || hasLoginError;
if (hasAuction && hasLoginError)
{
this._loginReg.LoginErrorType = LoginErrorCode;
}
if (IsGetMoreTokens)
{
this._getMoreTokens.Visible = true;
this._loginReg.Visible = false;
this._deals.Visible = false;
}
// set the hidden field which can be used to set visibility if included in a tab control or anything
// by the parent site
if (this.AuctionID > 0 || BidStatus > 0 || IsHome > 0 || LoginErrorCode > 0 || IsGetMoreTokens)
this._visibilityStatus.Value = "1";
How about taking it the other way around?
private void SetVisibility(int AuctionID, int BidStatus, int LoginErrorCode, int IsHome, bool IsGetMoreTokens)
{
this._dealBidPlacedControl.Visible = AuctionID > 0 && LoginErrorCode == 0 && BidStatus > 0;
this._dealBidControl.Visible = AuctionID > 0 && LoginErrorCode == 0 && BidStatus <= 0;
this._loginReg.Visible = AuctionID > 0 && LoginErrorCode != 0;
this._deals.Visible = AuctionID > 0 && LoginErrorCode != 0;
etc.
}
You could even box all the parameters to an auxiliary class:
class VisibilityParameters
{
public int AuctionID;
public int BidStatus;
...
}
so that your method becomes easier to extend in future:
private void SetVisibility( VisibilityParamteres parameters )
{
}
This gives you the chance to extract boolean expressions out of the method body:
private void SetVisibility( VisibilityParameters parameters )
{
this._dealBidPlacedControl.Visible = DealBidPlaceVisible( parameters );
etc.
}
private bool DealBidPlaceVisible( VisibilityParameters parameters )
{
return parameters.AuctionID > 0 && parameters.LoginErrorCode == 0 && parameters.BidStatus > 0
}
Personally I like to move the code which control the appearance closer to the control. Avoding cluttering the code with lots of gui logic, like this:
private void SetVisibility(int AuctionID, int BidStatus, int LoginErrorCode, int IsHome, bool IsGetMoreTokens)
{
this._dealBidPlacedControl.Visible = AuctionID > 0 && LoginErrorCode == 0 && BidStatus > 0;
this._dealBidControl.Visible = AuctionID > 0 && LoginErrorCode == 0 && BidStatus <= 0;
this._loginReg.LoginErrorType = LoginErrorCode;
this._loginReg.Visible = !IsGetMoreTokens && LoginErrorCode != 0;
this._deals.Visible = !IsGetMoreTokens && LoginErrorCode != 0;
this._getMoreTokens.Visible = IsGetMoreTokens;
// set the hidden field which can be used to set visibility if included in a tab control or anything
// by the parent site
if (this.AuctionID > 0 || BidStatus > 0 || IsHome > 0 || LoginErrorCode > 0 || IsGetMoreTokens)
this._visibilityStatus.Value = "1";
}
And if you have an expensive operation you could always cache it in a local variable, but this is how I would do it.
if (AuctionID > 0 && LoginErrorCode == 0 && BidStatus > 0)
{
this._dealBidPlacedControl.Visible = true;
}
else if (AuctionID > 0 && LoginErrorCode == 0 && AuctionID <= 0)
{
this._dealBidControl.Visible = true;
}
else if (AuctionID > 0 && LoginErrorCode != 0)
{
this._loginReg.LoginErrorType = LoginErrorCode;
this._loginReg.Visible = true;
this._deals.Visible = true;
}
else if(AuctionID <= 0)
{
this._loginReg.Visible = true;
this._deals.Visible = true;
}
Related
I am trying to make a string calculator, it works fine with two numbers but I always encounter a problem when evaluating multiple operations:
7*2+4=
Also can you help me with my multiplication and division code. I don't understand why it prints 0 even with just two numbers(7*5)
using System;
using System.Text.RegularExpressions;
namespace Sariling_Calcu
{
class Program
{
private static string exp;
private static int[] i = new int[1000];
private static char[] oper = new char[10];
private static int cntr2;
private static int result;
private static int pluscount;
private static int subcount;
private static int mulcount;
private static int divcount;
static void getNum()
{
string[] strNum = (Regex.Split(exp, #"\D+"));
for (int cntr = 0; cntr < exp.Length; cntr++)
{
foreach (string item in strNum)
{
if (!string.IsNullOrEmpty(item))
{
i[cntr] = int.Parse(item);
cntr += 1;
}
}
}
}
static void counter()
{
for (int cntr = 0; cntr < exp.Length; cntr++)
{
if (exp[cntr] == '+')
{
pluscount++;
}
else if (exp[cntr] == '-')
{
subcount++;
}
else if (exp[cntr] == '*')
{
mulcount++;
}
else if (exp[cntr] == '/')
{
divcount--;
}
}
}
static void oprtr()
{
for (int cntr = 0; cntr < exp.Length; cntr++)
{
if (exp[cntr] != '1'
&& exp[cntr] != '2'
&& exp[cntr] != '3'
&& exp[cntr] != '4'
&& exp[cntr] != '5'
&& exp[cntr] != '6'
&& exp[cntr] != '7'
&& exp[cntr] != '8'
&& exp[cntr] != '9')
{
if (exp[cntr] == '+')
{
result += i[cntr2];
cntr2 += 1;
pluscount--;
if (pluscount == 0 && subcount == 0 && mulcount==0 && divcount==0)
{
cntr2 += 3;
result += i[cntr2];
}
}
else if (exp[cntr] == '-')
{
result -= i[cntr2];
cntr2 += 1;
subcount--;
result = -result;
if (pluscount == 0 && subcount == 0 && mulcount == 0 && divcount == 0)
{
cntr2 += 3;
result -= i[cntr2];
}
}
else if (exp[cntr] == '*')
{
if (result == 0)
{
result += 1;
}
result *= i[cntr2];
cntr2 += 1;
mulcount--;
if (pluscount == 0 && subcount == 0 && mulcount == 0 && divcount == 0)
{
cntr2 += 3;
result *= i[cntr2];
}
}
else if (exp[cntr] == '/')
{
if (result == 0)
{
result += 1;
}
result /= i[cntr2];
cntr2 += 1;
divcount--;
if (pluscount == 0 && subcount == 0 && mulcount == 0 && divcount == 0)
{
cntr2 += 3;
result /= i[cntr2];
}
}
}
}
}
static void Main(string[] args)
{
Console.Write("Expression: ");
exp = Console.ReadLine();
counter();
getNum();
oprtr();
Console.Write("Answer: \n" + result);
Console.ReadLine();
}
}
}
you could use LINQ to reduce your code to a few lines but looks like its a school assignment where you would have to go with Arrays and loops.
I have tried to refine your code a bit and did a few fixes, change getNum(), counter() and oprtr() methods as below and let me know if it works, then I would add some comments in the code to explain changes I made.
static void getNum()
{
string[] strNum = (Regex.Split(exp, #"\D+"));
for (int cntr = 0; cntr < strNum.Length; cntr++)
{
if (!string.IsNullOrEmpty(strNum[cntr]))
{
i[cntr] = int.Parse(strNum[cntr]);
}
}
}
static void counter()
{
cntr2 = 0;
for (int cntr = 0; cntr < exp.Length; cntr++)
{
if (exp[cntr] == '+')
{
oper[cntr2] = '+';
cntr2++;
}
else if (exp[cntr] == '-')
{
oper[cntr2] = '-';
cntr2++;
}
else if (exp[cntr] == '*')
{
oper[cntr2] = '*';
cntr2++;
}
else if (exp[cntr] == '/')
{
oper[cntr2] = '/';
cntr2++;
}
}
}
static void oprtr()
{
result = i[0];
cntr2 = 1;
for (int cntr = 0; cntr < oper.Length; cntr++)
{
if (oper[cntr] == '+')
{
result += i[cntr2];
}
else if (oper[cntr] == '-')
{
result -= i[cntr2];
}
else if (oper[cntr] == '*')
{
result *= i[cntr2];
}
else if (oper[cntr] == '/')
{
if (i[cntr2] == 0)
{
throw new DivideByZeroException();
}
result /= i[cntr2];
}
cntr2 += 1;
}
}
I'm working on a method that compares a collection of objects (since the object supports all types), if they are all the same, it returns true, but if one or more differs, it returns false.
This is what I have:
public static bool Compare(bool compareTypes = false, params object[] values)
{
if (!compareTypes)
{
if (values is null || values.Length == 0) return false;
else if (values.Length == 1) return true;
else return values[0] == values[1];
}
else
{
if (values is null || values.Length == 0) return false;
else if (values.Length == 1) return true;
else return values[0].GetType() == values[1].GetType();
}
}
And it works fine as long as the number of objects is 2.
My problem is that I want the method to compare the value or the type of all parameters that are passed regardless of the amount
This is what I want my method to do
Compare (false, "Hello", "Hello") //True
Compare(false, "Hello", "Bye") //False
Compare(true, 0, 1) //True
Compare(true, "Hi", 20) //False
Compare(false, "LOL", "LOL", "LOL", "LOL") //True
Compare(false, "LOL", "LOL", "LOL", "lol") //False
If you are ok with the logic that works for 2 objects why not just compare all objects in a same way with a loop?
public static bool Compare(bool compareTypes = false, params object[] values)
{
if (!compareTypes)
{
if (values == null || values.Length == 0)
{
return false;
}
else if (values.Length == 1)
{
return true;
}
else if (values.Length == 2){
return values[0] == values[1];
}
else
{
bool result = true;
for(int i = 0; i < values.Length - 1; i++)
{
if(values[i] != values[i+1])
{
result = false;
break;
}
}
return result;
}
}
else
{
if (values == null || values.Length == 0)
{
return false;
}
else if (values.Length == 1)
{
return true;
}
else if (values.Length == 2)
{
return values[0].GetType() == values[1].GetType();
}
else
{
bool result = true;
for(int i = 0; i < values.Length - 1; i++)
{
if(values[i].GetType() != values[i+1].GetType())
{
result = false;
break;
}
}
return result;
}
}
}
Here is a running example with your test cases : https://dotnetfiddle.net/uDA5Mb
You can also use recursive and simplify your code with that way.
public static bool Compare(bool compareTypes = false, params object[] values)
{
if (values is null || values.Length == 0)
return false;
else if (values.Length == 1)
return true;
else if (values.Lenght == 2)
if (!compareTypes)
return values[0] == values[1];
else
return values[0].GetType() == values[1].GetType();
else
{
for(int i = 0; i < values.Lenght - 1; i++)
if(!Compare(compareTypes, values[i], values[i+1]))
return false;
return true;
}
}
Very simple.
I want to change the int speed value, but it doesn't work. Can someone help me? If you too have too few information, pls ask me.
This is my code:
if (Input.GetKeyDown (KeyCode.W)) {
sprint1 = true;
} else if (Input.GetKeyUp(KeyCode.W)){
sprint1 = false;
}
if (Input.GetKeyDown(KeyCode.LeftShift)){
sprint2 = true;
} else if (Input.GetKeyUp(KeyCode.LeftShift)){
sprint2 = false;
}
if (sprint2 == false && Input.GetKeyUp(KeyCode.W) && Input.GetKeyUp(KeyCode.A) && Input.GetKeyUp(KeyCode.S) && Input.GetKeyUp(KeyCode.D)){
speed = 0;
} if (sprint2==false && (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.D))){
speed = 4;
}if (sprint1 == true && sprint2 == true && Scoped==true) {
speed = 8;
}
if (sprint2 == false && Input.GetKeyUp(KeyCode.W) && Input.GetKeyUp(KeyCode.A) && Input.GetKeyUp(KeyCode.S) && Input.GetKeyUp(KeyCode.D)){
speed = 0;
}
You will never enter in this particular case except if, during the exact same frame, you release W, A, S and D. Look at the Input.GetKeyUp documentation:
Returns true during the frame the user releases the key identified by the key KeyCode enum parameter.
You should organise it this way instead:
// If you are sprinting, set the speed to 8
if (sprint1 == true && sprint2 == true && Scoped==true) {
speed = 8;
}
// Else if one of those keys has been touched during this frame, set the speed to 4
else if (sprint2==false && (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D))){
speed = 4;
}
// Else, just set the speed to 0
else
speed = 0;
If a key isn't down, it's up. No need to check for both. Anyway, this is the way I interpret your if.
sprint1 = Input.GetKeyDown(KeyCode.W);
sprint2 = Input.GetKeyDown(KeyCode.LeftShift);
if (sprint2)
{
if (sprint1 && Scoped)
speed = 8;
else
speed = 4; // do you want speed 0 or 4 if either of these others are false
}
else
{
if (sprint1
|| Input.GetKeyDown(KeyCode.A)
|| Input.GetKeyDown(KeyCode.S)
|| Input.GetKeyDown(KeyCode.D))
speed = 4;
else
speed = 0;
}
What I think would work better, if I'm interpreting your desire, is
sprint1 = Input.GetKeyDown(KeyCode.W);
sprint2 = Input.GetKeyDown(KeyCode.LeftShift);
if (sprint1 && sprint2 && Scoped)
speed = 8;
else if (sprint1
|| Input.GetKeyDown(KeyCode.A)
|| Input.GetKeyDown(KeyCode.S)
|| Input.GetKeyDown(KeyCode.D))
speed = 4;
else
speed = 0;
Here is a way of doing it so you don't have to make all these unnecessary flags for sprint.
if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.LeftShift) && Scoped)
speed = 8;
else if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.S))
speed = 4;
else
speed = 0;
I have fixed my own issue.
Thanks for all your comments, but I wanna show you my solution:
if (Input.GetKey (KeyCode.W)) {
sprint1 = true;
} else {
sprint1 = false;
}
if (Input.GetKey (KeyCode.LeftShift)) {
sprint2 = true;
} else {
sprint2 = false;
}
if (sprint2 == false && sprint1==false && !(Input.GetKey (KeyCode.A)) && !(Input.GetKey (KeyCode.S)) && !(Input.GetKey (KeyCode.D))){
speed = 0;
} if ((sprint1==true && sprint2==false) || Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.S) || Input.GetKey (KeyCode.D)){
speed = 4;
}if (sprint1 == true && sprint2 == true && Scoped==true) {
speed = 8;
}
I am using a data table to store some data. After the for loop check the length of the data table, the data table clears itself. There is no data in it. Can you advise why is it so ? This is part part of a report that is using the DevExpress reporting engine to create the reports.
DataTable ResultList = new DataTable();
ResultList.Columns.Add("range");
ResultList.Columns.Add("bpfrom");
ResultList.Columns.Add("bpto");
ResultList.Columns.Add("qualMemb");
ResultList.Columns.Add("qualTurn");
ResultList.Columns.Add("qualTurnPercent");
ResultList.Columns.Add("grMemb");
ResultList.Columns.Add("grTurn");
ResultList.Columns.Add("grTurnPercent");
ResultList.Columns.Add("totalamt");
ResultList.Columns.Add("giftlevel");
string[] fromrangelist = fromrange.Split(',');
string[] torangelist = torange.Split(',');
int j;
if (fromrange == "")
{
DataRow dr = ResultList.NewRow();
dr["range"] = 1;
dr["bpfrom"] = 0;
dr["bpto"] = 100000000; //biggest value
dr["giftlevel"] = "ALL";
ResultList.Rows.Add(dr);
}
else
{
for (j = 0; j < fromrangelist.Length; j++)
{
DataRow dr = ResultList.NewRow();
dr["range"] = j + 1;
dr["bpfrom"] = Convert.ToDecimal(fromrangelist[j]);
dr["bpto"] = Convert.ToDecimal(torangelist[j]);
dr["giftlevel"] = "level:" + (j + 1).ToString() + "(" + fromrangelist[j] + "-" + torangelist[j] + ")";
ResultList.Rows.Add(dr);
}
}
//Get ALL Total spend
decimal TotalSpend = Math.Round((from table1 in context.mmsspddtls
where table1.mmsspdcpcd.Equals(cpcd) && table1.mmsspdbrcd.Equals(brcd)
&& table1.mmsspdtxdt >= fromtxdate && table1.mmsspdtxdt <= totxdate
&& (table1.mmsspdtxty.Equals(null) || table1.mmsspdtxty.Equals("") || table1.mmsspdtxty.Equals("PS") || table1.mmsspdtxty.Equals("PE") || table1.mmsspdtxty.Equals("PR"))
&& (table1.mmsspdplna.Equals('1') || table1.mmsspdplna.Equals('5') || table1.mmsspdplna.Equals('P') || table1.mmsspdplna.Equals('T') || table1.mmsspdplna.Equals('A') || table1.mmsspdplna.Equals('L'))
&& !table1.mmsspdstfg.Equals('V')
select new
{
totalamt = table1.mmsspdpram
}).Sum(s => s.totalamt), 2);
for (int i = 0; i < ResultList.Rows.Count; i++)
{
decimal fromvalue = Convert.ToDecimal(ResultList.Rows[i]["bpfrom"]);
decimal tovalue = Convert.ToDecimal(ResultList.Rows[i]["bpto"]);
ResultList.Rows[i]["totalamt"] = TotalSpend;
//Member Query that match the range
var MemberQuery = (from table1 in context.mmscrdlogs
where table1.mmscdlcpcd.Equals(cpcd) && table1.mmscdlbrcd.Equals(brcd)
&& table1.mmscdlstst.Equals('N') && table1.mmscdlbpis >= fromvalue && table1.mmscdlbpis <= tovalue
&& table1.mmscdleddt >= fromexpiredate && table1.mmscdleddt <= toexpiredate
select new
{
spendfr = fromvalue,
spendto = tovalue,
membercode = table1.mmscdlmbcd
}).Distinct();
//Count of member in the range
ResultList.Rows[i]["qualMemb"] = MemberQuery.Count();
//member total spend in the range
decimal qualTurn = 0;
var qualQuery = (from table1 in context.mmsspddtls
from table2 in MemberQuery.Where(s => s.membercode == table1.mmsspdmbcd)
where table1.mmsspdcpcd.Equals(cpcd) && table1.mmsspdbrcd.Equals(brcd)
&& table1.mmsspdtxdt >= fromtxdate && table1.mmsspdtxdt <= totxdate
&& (table1.mmsspdtxty.Equals(null) || table1.mmsspdtxty.Equals("") || table1.mmsspdtxty.Equals("PS") || table1.mmsspdtxty.Equals("PE") || table1.mmsspdtxty.Equals("PR"))
&& (table1.mmsspdplna.Equals('1') || table1.mmsspdplna.Equals('5') || table1.mmsspdplna.Equals('P') || table1.mmsspdplna.Equals('T') || table1.mmsspdplna.Equals('A') || table1.mmsspdplna.Equals('L'))
&& !table1.mmsspdstfg.Equals('V')
select new
{
totalamt = table1.mmsspdpram
});
if(qualQuery.Count() > 0)
{
qualTurn = Math.Round(qualQuery.Sum(s => s.totalamt), 2);
}
ResultList.Rows[i]["qualTurn"] = qualTurn;
//member total spend% with total in the range
if (qualTurn == 0)
ResultList.Rows[i]["qualTurnPercent"] = 0;
else
ResultList.Rows[i]["qualTurnPercent"] = Math.Round((qualTurn / TotalSpend) * 100, 2);
var MemberQueryGR = (from table1 in context.mmsspddtls
from table2 in context.pxppludpxes.Where(s => s.pxppdxcpcd.Equals(table1.mmsspdcpcd) && s.pxppdxbrcd.Equals(table1.mmsspdbrcd) && s.pxppdxplcd.Equals(table1.mmsspdplcd))
from table3 in context.mmssyspars.Where(s => s.mmssypcpcd.Equals(table1.mmsspdcpcd) && s.mmssypbrcd.Equals(table1.mmsspdbrcd))
where table1.mmsspdcpcd.Equals(cpcd) && table1.mmsspdbrcd.Equals(brcd)
&& table2.pxppdxpx01 / (table3.mmssypbpmt / table3.mmssyppont) >= fromvalue
&& table2.pxppdxpx01 / (table3.mmssypbpmt / table3.mmssyppont) <= tovalue
&& table1.mmsspdtxty.Equals("GR") && table1.mmsspdplna.Equals('2')
&& table1.mmsspdtxdt >= fromtxdate && table1.mmsspdtxdt <= totxdate
select new
{
spendfr = fromvalue,
spendto = tovalue,
membercode = table1.mmsspdmbcd
}).Distinct();
//Count of GR member in the range
ResultList.Rows[i]["grMemb"] = MemberQueryGR.Count();
//GR member total spend in the range
decimal grTurn = 0;
if (MemberQueryGR.Count() > 0)
{
var grQuery = (from table1 in context.mmsspddtls
from table2 in MemberQueryGR.Where(s => s.membercode == table1.mmsspdmbcd)
where table1.mmsspdcpcd.Equals(cpcd) && table1.mmsspdbrcd.Equals(brcd)
&& table1.mmsspdtxdt >= fromtxdate && table1.mmsspdtxdt <= totxdate
&& (table1.mmsspdtxty.Equals(null) || table1.mmsspdtxty.Equals("") || table1.mmsspdtxty.Equals("PS") || table1.mmsspdtxty.Equals("PE") || table1.mmsspdtxty.Equals("PR"))
&& (table1.mmsspdplna.Equals('1') || table1.mmsspdplna.Equals('5') || table1.mmsspdplna.Equals('P') || table1.mmsspdplna.Equals('T') || table1.mmsspdplna.Equals('A') || table1.mmsspdplna.Equals('L'))
&& !table1.mmsspdstfg.Equals('V')
select new
{
totalamt = table1.mmsspdpram
});
if(grQuery.Count() > 0)
{
grTurn = Math.Round(grQuery.Sum(s => s.totalamt), 2);
}
}
ResultList.Rows[i]["grTurn"] = grTurn;
//member total spend% with total in the range
if (grTurn == 0)
ResultList.Rows[i]["grTurnPercent"] = 0;
else
ResultList.Rows[i]["grTurnPercent"] = Math.Round((grTurn / TotalSpend) * 100, 2);
}
DataSource = ResultList;
}
Please advise. Thanks
i have code that its working but its not as i would like.
in runtime i create many new textbox/labels so i had to use 10 ifs to check each "future" textbox have textlength = 0 and != null
i would like to use repeat structure like for or while, dont know if its possible.
For example, if i create more textbox/labels will be impossible have really big code.
See my code:
private void cadeiaapagarcampos(TextBox _text, EventArgs e)
{
if (_text.Text == "")
{
Label lblAcessorio2 = (Label)gpbCategoria.Controls.Find("lblAcessorio2", false).FirstOrDefault();
TextBox txtAcessorio2 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio2", false).FirstOrDefault();
Label lblAcessorio3 = (Label)gpbCategoria.Controls.Find("lblAcessorio3", false).FirstOrDefault();
TextBox txtAcessorio3 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio3", false).FirstOrDefault();
Label lblAcessorio4 = (Label)gpbCategoria.Controls.Find("lblAcessorio4", false).FirstOrDefault();
TextBox txtAcessorio4 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio4", false).FirstOrDefault();
Label lblAcessorio5 = (Label)gpbCategoria.Controls.Find("lblAcessorio5", false).FirstOrDefault();
TextBox txtAcessorio5 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio5", false).FirstOrDefault();
Label lblAcessorio6 = (Label)gpbCategoria.Controls.Find("lblAcessorio6", false).FirstOrDefault();
TextBox txtAcessorio6 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio6", false).FirstOrDefault();
Label lblAcessorio7 = (Label)gpbCategoria.Controls.Find("lblAcessorio7", false).FirstOrDefault();
TextBox txtAcessorio7 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio7", false).FirstOrDefault();
Label lblAcessorio8 = (Label)gpbCategoria.Controls.Find("lblAcessorio8", false).FirstOrDefault();
TextBox txtAcessorio8 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio8", false).FirstOrDefault();
Label lblAcessorio9 = (Label)gpbCategoria.Controls.Find("lblAcessorio9", false).FirstOrDefault();
TextBox txtAcessorio9 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio9", false).FirstOrDefault();
Label lblAcessorio10 = (Label)gpbCategoria.Controls.Find("lblAcessorio10", false).FirstOrDefault();
TextBox txtAcessorio10 = (TextBox)gpbCategoria.Controls.Find("txtAcessorio10", false).FirstOrDefault();
if (txtAcessorio2 != null && txtAcessorio2.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio2);
gpbCategoria.Controls.Remove(lblAcessorio2);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio3 != null && txtAcessorio3.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio3);
gpbCategoria.Controls.Remove(lblAcessorio3);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio4 != null && txtAcessorio4.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio4);
gpbCategoria.Controls.Remove(lblAcessorio4);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio5 != null && txtAcessorio5.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio5);
gpbCategoria.Controls.Remove(lblAcessorio5);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio6 != null && txtAcessorio6.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio6);
gpbCategoria.Controls.Remove(lblAcessorio6);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio7 != null && txtAcessorio7.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio7);
gpbCategoria.Controls.Remove(lblAcessorio7);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio8 != null && txtAcessorio8.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio8);
gpbCategoria.Controls.Remove(lblAcessorio8);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
if (txtAcessorio9 != null && txtAcessorio9.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio9);
gpbCategoria.Controls.Remove(lblAcessorio9);
btnSalvar.Focus();
if (test != 1)
{
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
}
}
Would something like this be what you are looking for? If you have more labels just update iAcessorioContar and it will automatically check them as well as long as you name the labels incrementally.
private void cadeiaapagarcampos(TextBox _text, EventArgs e)
{
if (_text.Text == "")
{
int iAcessorioContar = 10;
for (int iContador = 2; iContador <= iAcessorioContar; iContador++) {
Label lblAcessorio = (Label)gpbCategoria.Controls.Find("lblAcessorio"+iContador, false).FirstOrDefault();
TextBox txtAcessorio = (TextBox)gpbCategoria.Controls.Find("txtAcessorio"+iContador, false).FirstOrDefault();
if (txtAcessorio != null && txtAcessorio.TextLength == 0)
{
gpbCategoria.Controls.Remove(txtAcessorio);
gpbCategoria.Controls.Remove(lblAcessorio);
btnSalvar.Focus();
if (test != 1) {
n--;
t++;
if (n >= 1 && n <= 10)
{
testeapagar();
test = 1;
}
}
}
}
}
}
You could add the controls in pairs (label and textbox) to a list when you create them so you do not have to search the controls collection which can cost a lot of time.
You can then simply loop the list.