So I have this code. What it does is to show the selected usercontrol when user tap a button. If that particular usercontrol is already visible, tapping its button will hide it.
The code is rather repetitive, any suggestion how can I make it more succinct?
private void changeControl(TextControl control)
{
switch (control)
{
case TextControl.TextBox:
if (IsRadTextBoxVisible == true)
{
IsRadTextBoxVisible = false;
}
else
{
IsRadTextBoxVisible = true;
}
IsCountriesListBoxVisible = false;
IsSliderFontSizeVisible = false;
IsSliderFontRotateVisible = false;
break;
case TextControl.Font:
if (IsCountriesListBoxVisible == true)
{
IsCountriesListBoxVisible = false;
}
else
{
IsCountriesListBoxVisible = true;
}
IsRadTextBoxVisible = false;
IsSliderFontSizeVisible = false;
IsSliderFontRotateVisible = false;
break;
case TextControl.Size:
if (IsSliderFontSizeVisible == true)
{
IsSliderFontSizeVisible = false;
}
else
{
IsSliderFontSizeVisible = true;
}
IsRadTextBoxVisible = false;
IsCountriesListBoxVisible = false;
IsSliderFontRotateVisible = false;
break;
case TextControl.Rotate:
if (IsSliderFontRotateVisible == true)
{
IsSliderFontRotateVisible = false;
}
else
{
IsSliderFontRotateVisible = true;
}
IsRadTextBoxVisible = false;
IsCountriesListBoxVisible = false;
IsSliderFontSizeVisible = false;
break;
default:
break;
}
}
var stateRad= IsRadTextBoxVisible;
var stateSlider = IsSliderFontRotateVisible;
var ........
var ........
IsCountriesListBoxVisible = false;
IsSliderFontSizeVisible = false;
IsSliderFontRotateVisible = false;
IsRadTextBoxVisible = false
switch (control)
{
case TextControl.TextBox:
IsRadTextBoxVisible = !stateRad
break;
case TextControl.Font:
IsCountriesListBoxVisible = !statexxx
break;
case TextControl.Size:
IsSliderFontSizeVisible = !statexxx
break;
case TextControl.Rotate:
IsSliderFontRotateVisible = !statexxx
break;
default:
break;
}
private void changeControl(TextControl control)
{
IsRadTextBoxVisible = control == TextControl.TextBox ? !IsRadTextBoxVisible : false;
IsCountriesListBoxVisible = control == TextControl.Font ? !IsCountriesListBoxVisible : false;
IsSliderFontSizeVisible = control == TextControl.Size ? !IsSliderFontSizeVisible : false;
IsSliderFontRotateVisible = control == TextControl.Rotate ? !IsSliderFontRotateVisible : false;
}
What it does:
control == TextControl.TextBox
returns either true or false.
Now, ternary operator ?: executes code after ? if expression before ? returned true,
or code after : if expression before ? returned false
In this case, if control matches, we're executing code after ?, which in this case toggles the property.
If we control doesn't match, we're executing code after :, which sets the property to false.
I such cases i would not use switch-case, becuase you can't make complex boolean-operations. Maybe you can make your code more efficent with some if-else statements. Switch-Cases are some times very limited and would not use them.
Related
I got a little problem. I got a if statement which says if Session isn't equal 3, then do something, and if that isn't true, then do something else. My problem is just, that it isn't working proberly.
I've already tried:
1)
if (Session["userrank"] != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
2)
if (Session["userrank"].ToString() != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
3)
if ((string)Session["userrank"] != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
4)
if (((string)Session["userrank"]) != "3")
{
pnlAdmin.Visible = false;
}
else
{
pnlAdmin.Visible = true;
}
but none of them seems to work. And i have already checked if there's a Session called userrank that is getting the result 3.
sorry for the "stupid" question. I'm kind of new to C# & ASP.net.
Best Regards,
Anton
Your code sets pnlAdmin.Visible = false; if whatever is in Session["userrank"] is not 3.
It sets pnlAdmin.Visible = true; if whatever is in Session["userrank"] is 3.
You said it is 3; therefore, the panel should be visible. And that seems to be what is happening.
I am pasting my code snippet below. Could some body suggest a better and effecient way of writing this. I would like minimum code to be written and avoid repetition.
private void SetControlVisibility()
{
if (DropDownList1.SelectedItem.Text.Equals("GetAssetsBasicById") || DropDownList1.SelectedItem.Text.Equals("GetAssetDetailsByIds"))
{
Label2.Text = "(Please enter asset ids for e.g. 1,2)";
chkExcludeMAPFunds.Visible = false;
chkPublishXML.Visible = true;
}
else if (DropDownList1.SelectedItem.Text.Equals("GetAssetsBasicBySedols") || DropDownList1.SelectedItem.Text.Equals("GetAssetDetailsBySedols"))
{
Label2.Text = "(Please enter sedols for e.g. B1YW440,0003496)";
chkExcludeMAPFunds.Visible = false;
chkPublishXML.Visible = true;
}
else if (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportByIds"))
{
Label2.Text = "(Please enter asset ids for e.g. 1:100)";
chkExcludeMAPFunds.Visible = true;
chkPublishXML.Visible = false;
}
else if (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportBySedol"))
{
Label2.Text = "(Please enter sedols for e.g. B1YW440:100)";
chkExcludeMAPFunds.Visible = true;
chkPublishXML.Visible = false;
}
}
You could use a dictionary to avoid both nested if's and switch/cases:
private readonly Dictionary<string, Tuple<string, bool, bool>> _dropDownMap = new Dictionary<string, Tuple<string, bool, bool>>
{
{"GetAssetsBasicById", new Tuple<string, bool, bool>("(Please enter asset ids for e.g. 1,2)", false, true) },
{"GetAssetDetailsByIds", new Tuple<string, bool, bool>("(Please enter asset ids for e.g. 1,2)", false, true) },
...
};
private void SetControlVisibility()
{
var mapping = _dropDownMap[DropDownList1.SelectedItem.Text];
if (mapping != null)
{
Label2.Text = mapping.Item1;
chkExcludeMAPFunds.Visible = mapping.Item2;
chkPublishXML.Visible = mapping.Item3;
}
}
If you favour readability over small code, then the Tuple could be replaced by an explicit VO class:
private class DropDownMappings
{
public DropDownMappings(label, excludeMAPFundsVisible, publishXMLVisible)
{
Label2Text = label;
ExcludeMAPFundsVisible = excludeMAPFundsVisible;
PublishXMLVisible = publishXMLVisible;
}
public string Label2Text { get; set; }
public bool ExcludeMAPFundsVisible { get; set; }
public bool PublishXMLVisible { get; set; }
}
private readonly Dictionary<string, DropDownMappings> _dropDownMap = new Dictionary<string, DropDownMappings>
{
{"GetAssetsBasicById", new DropDownMappings("(Please enter asset ids for e.g. 1,2)", false, true) },
{"GetAssetDetailsByIds", new DropDownMappings("(Please enter asset ids for e.g. 1,2)", false, true) },
...
};
private void SetControlVisibility()
{
var mapping = _dropDownMap[DropDownList1.SelectedItem.Text];
if (mapping != null)
{
Label2.Text = mapping.Label2Text;
chkExcludeMAPFunds.Visible = mapping.ExcludeMAPFundsVisible;
chkPublishXML.Visible = mapping.PublishXMLVisible;
}
}
Alternate code with switch:
private void SetControlVisibility()
{
if (DropDownList1.SelectedItem != null)
{
switch (DropDownList1.SelectedItem.Text)
{
case "GetAssetsBasicById":
case "GetAssetDetailsByIds":
Label2.Text = "(Please enter asset ids for e.g. 1,2)";
chkExcludeMAPFunds.Visible = false;
chkPublishXML.Visible = true;
break;
case "GetAssetsBasicBySedols":
case "GetAssetDetailsBySedols":
Label2.Text = "(Please enter sedols for e.g. B1YW440,0003496)";
chkExcludeMAPFunds.Visible = false;
chkPublishXML.Visible = true;
break;
case "GetInvestmentReportByIds":
Label2.Text = "(Please enter asset ids for e.g. 1:100)";
chkExcludeMAPFunds.Visible = true;
chkPublishXML.Visible = false;
break;
case "GetInvestmentReportBySedol":
Label2.Text = "(Please enter sedols for e.g. B1YW440:100)";
chkExcludeMAPFunds.Visible = true;
chkPublishXML.Visible = false;
break;
default:
// we do it wrong :(
throw new NotSupportedException();
}
}
}
Another solution is using Item's Tag property with predefined enum values.
My alternate code:
private void SetControlVisibility()
{
string resultText;
bool b = false;
switch (DropDownList1.SelectedItem.Text)
{
case "GetAssetsBasicById":
case "GetAssetDetailsByIds":
b = true;
resultText = "(Please enter asset ids for e.g. 1,2)";
break;
case "GetAssetsBasicBySedols":
case "GetAssetDetailsBySedols":
b = true;
resultText = "(Please enter sedols for e.g. B1YW440,0003496)";
break;
case "GetInvestmentReportByIds":
resultText = "(Please enter asset ids for e.g. 1:100)";
break;
case "GetInvestmentReportBySedol":
resultText = "(Please enter sedols for e.g. B1YW440:100)";
break;
default: return;
}
chkExcludeMAPFunds.Visible = !b;
chkPublishXML.Visible = b;
Label2.Text = resultText;
}
First, taking the chks out of the if and using the ?: operator will shorthand their notation.
Then, due to having only one statement inside each if - else if, brackets can be erased.
if (DropDownList1.SelectedItem.Text.Equals("GetAssetsBasicById") || DropDownList1.SelectedItem.Text.Equals("GetAssetDetailsByIds"))
Label2.Text = "(Please enter asset ids for e.g. 1,2)";
else if (DropDownList1.SelectedItem.Text.Equals("GetAssetsBasicBySedols") || DropDownList1.SelectedItem.Text.Equals("GetAssetDetailsBySedols"))
Label2.Text = "(Please enter sedols for e.g. B1YW440,0003496)";
else if (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportByIds"))
Label2.Text = "(Please enter asset ids for e.g. 1:100)";
else if (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportBySedol"))
Label2.Text = "(Please enter sedols for e.g. B1YW440:100)";
chkExcludeMAPFunds.Visible = (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportByIds") || DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportBySedol") ? true : false;
chkPublishXML.Visible = (DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportByIds") || DropDownList1.SelectedItem.Text.Equals("GetInvestmentReportBySedol") ? false : true;
This way, we have got rid of many lines.
how can i do so if my username are Anton, then show, if not then dont show.
I already tried the following thing.
if(Session["username"] == "Anton")
{
btnNew.Visible = true;
}
else
{
btnNew.Visible = false;
}
if(!string.IsNullOrEmpty((string)Session["username"]) && (string)Session["username"] == "Anton")
{
btnNew.Visible = true;
}
else
{
btnNew.Visible = false;
}
i am trying to make a program in c#, in which the values of check boxes are retrieved from csv file.I have 4 check boxes and all of them are true or false according to the conditions in csv file. My question is i am using
if (strProg[a] == "JC")
{
chkJogging.Checked = true;
chkCycling.Checked = true;
}
else if(strProg[a] =="C")
{
chkCycling == true
}
else if(strProg[a] == "WK")
{
chkWeightLoss.Checked = true;
chkKoxing.Checked = true
}
else
{
chkBoxing.Checked = false;
chkJogging.Checked = false;
chkCycling.Checked = false;
chkWeightLoss.Checked = false
}
But for some reason the last one 'else' loop is not working. Thanks.
Don't use IF-ELSE This way.
read this : SWITCH-CASE
try this :
switch (strProg[a])
{
case "JC":
chkJogging.Checked = true;
chkCycling.Checked = true;
break;
case "C":
chkCycling.Checked = true;
break;
case "WK":
chkWeightLoss.Checked = true;
chkKoxing.Checked = true;
break;
default:
chkBoxing.Checked = false;
chkJogging.Checked = false;
chkCycling.Checked = false;
chkWeightLoss.Checked = false;
break;
}
you are missing '.Checked' here, so my guess is probably your code is breakin at this point.
else if(strProg[a] =="C")
{
chkCycling == true
}
try to change it with
else if(strProg[a] =="C")
{
chkCycling.Checked == true
}
and see if it works.
I have an if else tree that is going to grow as I add additional items for it to maintain and I'm looking at the best way to write it for maintainability I'm starting with this code
private void ControlSelect()
{
if (PostingType == PostingTypes.Loads && !IsMultiPost)
{
singleLoadControl.Visible = true;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
}
else if (PostingType == PostingTypes.Trucks && !IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = true;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
}
else if (PostingType == PostingTypes.Loads && IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = true;
}
else if (PostingType == PostingTypes.Trucks && IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = true;
multiLoadControl.Visible = false;
}
}
and thinking of re-factoring it to something like this
private void ControlSelect()
{
List<UserControl> controlList = GetControlList();
string visableControl = singleLoadControl.ID;
if (PostingType == PostingTypes.Loads && !IsMultiPost)
{
visableControl = singleLoadControl.ID;
}
else if (PostingType == PostingTypes.Trucks && !IsMultiPost)
{
visableControl = singleTruckControl.ID;
}
else if (PostingType == PostingTypes.Loads && IsMultiPost)
{
visableControl = multiLoadControl.ID;
}
else if (PostingType == PostingTypes.Trucks && IsMultiPost)
{
visableControl = multiTruckControl.ID;
}
foreach (UserControl userControl in controlList)
{
userControl.Visible = (userControl.ID == visableControl);
}
}
private List<UserControl> GetControlList()
{
List<UserControl> controlList = new List<UserControl>
{
singleLoadControl,
multiTruckControl,
singleTruckControl,
multiLoadControl
};
return controlList;
}
I take a performance hit but I can manage all of my controls is a single place
my other thought was to make each selected control block it own method, something like this
private void SetSingleLoadControlAsSelected()
{
singleLoadControl.Visible = true;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
}
I don't take a performance hit but I'm maintaining the controls in multiple location
I'm leaning for option one just because I like maintainability aspect of it.
what about
singleLoadControl.Visible =
PostingType == PostingTypes.Loads && !IsMultiPost;
singleTruckControl.Visible =
PostingType == PostingTypes.Trucks && !IsMultiPost;
multiTruckControl.Visible =
PostingType == PostingTypes.Loads && IsMultiPost;
multiLoadControl.Visible =
PostingType == PostingTypes.Trucks && IsMultiPost;
if you want capability to make multiple controls visible (or add more enumerated values) decorate the enum with [Flags] attribute as follows:
[Flags]
public enum PostTyp { None=0, IsMultiPost = 1, Loads = 2, Trucks = 4 }
and modify Code as follows:
singleLoadControl.Visible =
((PostingType & (PostTyp.Loads | ~PostTyp.MultiCast))
== PostingType );
singleTruckControl.Visible =
((PostingType & (PostTyp.Trucks | ~PostTyp.MultiCast))
== PostingType );
multiTruckControl.Visible =
((PostingType & (PostTyp.Loads | PostTyp.MultiCast))
== PostingType );
multiLoadControl.Visible =
((PostingType & (PostTyp.Trucks | PostTyp.MultiCast))
== PostingType );
As you appear to be using an enumeration, I would recommend a switch with a default case to cope with unknown values. I believe this approach makes intentions clearer than doing all the checking in the assignment.
switch (PostingType)
{
case PostingTypes.Loads:
singleLoadControl.Visible = !IsMultiPost;
multiTruckControl.Visible = IsMultiPost;
singleTruckControl.Visible = false;
multiTruckLoadControl.Visible = false;
break;
case PostingTypes.Trucks:
singleLoadControl.Visible = false;
multiTruckControl.Visible = false;
singleTruckControl.Visible = !IsMultiPost;
multiLoadControl.Visible = IsMultiPost;
break;
default:
throw InvalidOperationException("Unknown enumeration value.");
}
What about this:
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
if (PostingType == PostingTypes.Loads && !IsMultiPost)
{
singleLoadControl.Visible = true;
}
else if (PostingType == PostingTypes.Trucks && !IsMultiPost)
{
singleTruckControl.Visible = true;
}
else if (PostingType == PostingTypes.Loads && IsMultiPost)
{
multiLoadControl.Visible = true;
}
else if (PostingType == PostingTypes.Trucks && IsMultiPost)
{
multiTruckControl.Visible = true;
}
If it would be otherwise sensible (for example, if these are already domain-specific custom controls), you could encapsulate the logic inside the controls themselves (Replace Conditional with Polymorphism). Perhaps create an interface like this:
public interface IPostingControl {
void SetVisibility(PostingType postingType, bool isMultiPost);
}
Then each control would be responsible for its own visibility rules:
public class SingleLoadControl: UserControl, IPostingControl {
// ... rest of the implementation
public void SetVisibility(PostingType postingType, bool isMultiPost) {
this.Visible = postingType == PostingType.Load && !isMultiPost);
}
}
Finally, in your page, just iterate over your IPostingControls and call SetVisibility(postingType, isMultiPost).
If you are expecting to be adding a lot of different parameters, you could create a multi-dimensional array of objects
Arr[0][0] = singleLoadControl
Arr[0][1] = singleTruckControl
Arr[1][0] = multiLoadControl
Arr[1][1] = multiTruckControl
This is pretty scary, but makes for simpler if statements. If you're going to have loads of references to the controls anyhow, I'd rather use a code-based representation of what those loads are. Such an array can be wrapped in a class to let you access the elements using something more like:
ControlClassInstance.single.truck
You'd have code like this:
p1 = IsMultiPost ? ControlClassInstance.multi : ControlClassInstance.single
p2 = p1[PostingType] //(this call would mean adding an indexer)
This kind of solution is way too sophisticated unless you expect things to get complicated...and might be poor then, too.
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
singleLoadControl.Visible = (PostingType == PostingTypes.Loads && !IsMultiPost);
singleTruckControl.Visible = (PostingType == PostingTypes.Trucks && !IsMultiPost);
multiLoadControl.Visible = (PostingType == PostingTypes.Loads && IsMultiPost);
multiTruckControl.Visible = (PostingType == PostingTypes.Trucks && IsMultiPost);
Have you considered the State Pattern?
private void ControlSelect()
{
if (PostingType == PostingTypes.Loads && !IsMultiPost)
{
singleLoadControl.Visible = true;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
return;
}
if (PostingType == PostingTypes.Trucks && !IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = true;
multiTruckControl.Visible = false;
multiLoadControl.Visible = false;
return;
}
if (PostingType == PostingTypes.Loads && IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = false;
multiLoadControl.Visible = true;
return;
}
if (PostingType == PostingTypes.Trucks && IsMultiPost)
{
singleLoadControl.Visible = false;
singleTruckControl.Visible = false;
multiTruckControl.Visible = true;
multiLoadControl.Visible = false;
return;
}
}