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.
Related
I was making a puzzle where the player must push boulders to their corresponding buttons/pressure plate. I'm using booleans in a hard code for the prototype, but found myself having difficulties in what punctuation should I use between booleans? &&, and || didn't work.
Thank you for your willingness to help.
Please ignore the mess, what I need help with is the bottom public void OpenDoor in the 'if' statement, the one between trigger_1 and trigger_2 (what to replace the comma). Any advices to better the code are also appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerAllButtons : UsedOnceFieldButton
{
bool trigger_1 = false;
bool trigger_2 = false;
//bool trigger_3 = false;
//bool trigger_4 = false;
//bool trigger_5 = false;
//bool trigger_6 = false;
public string button_1 = "Button 1";
public string button_2 = "Button 2";
//public string button_3 = "Button 3";
//public string button_4 = "Button 4";
//public string button_5 = "Button 5";
//public string button_6 = "Button 6";
public string boulder_1 = "Boulder 1";
public string boulder_2 = "Boulder 2";
//public string boulder_3 = "Boulder 3";
//public string boulder_4 = "Boulder 4";
//public string boulder_5 = "Boulder 5";
//public string boulder_6 = "Boulder 6";
public void OnTriggerEnter(Collider other)
{
if (other.CompareTag(button_1) && other.CompareTag(boulder_1))
{
trigger_1 = true;
}
if (other.CompareTag(button_2) && other.CompareTag(boulder_2))
{
trigger_2 = true;
}
// if (other.CompareTag(button_3) && other.CompareTag(boulder_3))
// {
// trigger_3 = true;
// }
// if (other.CompareTag(button_4) && other.CompareTag(boulder_4))
// {
// trigger_4 = true;
// }
// if (other.CompareTag(button_5) && other.CompareTag(boulder_5))
// {
// trigger_5 = true;
// }
// if (other.CompareTag(button_6) && other.CompareTag(boulder_6))
// {
// trigger_6 = true;
// }
}
public void OpenDoor()
{
if (trigger_1 = true, trigger_2 = true) //&& (trigger_3 = true) && (trigger_4 = true) && (trigger_5 = true) && (trigger_6 = true))
{
UsedButton();
}
}
}
You are confusing assignment = and comparison == operator. Thats why you thought the boolean operators && and || did not work.
// this is wrong
// trigger_1 and trigger_2 get true ->assigned<- before && is evaluated
// thus the "if" is always true
if (trigger_1 = true && trigger_2 = true)
// should be like this
// trigger_1 and trigger_2 are only ->compared<- to true before && is evaluated
// this can give "if (false && true)" for example
if (trigger_1 == true && trigger_2 == true)
Same logic holds for other boolean operators (like ||). In the wrong if-statement you accidently changed the values of your bools.
Side note: it is really enough to write if (trigger_1 && trigger_2), they are bools anyway.
In my understanding you need to replace comma of open door with appropriate operator
there are two common operators OR || , AND &&
With OR operator if only one bool is true, the condition will return true, It only return False when both bool are false
With AND operator both bool need to be true in other for condition to return true.
I managed to create a TreeView method for NodeMouseClick and CursorChanged events.
private void Node_Selection_Action(object sender, TreeNodeMouseClickEventArgs e)
{
// my action code here...
}
private void TvwPanel_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
Node_Selection_Action(sender, e);
}
However, I am getting an error on e parameter when I applied the method to the CursorChanged:
private void TvwPanel_CursorChanged(object sender, EventArgs e)
{
Node_Selection_Action(sender, e); //error on `e` here
}
I supposed this is due to the parameter EventArgs that is not compatible with my method parameter TreeNodeMouseClickEventArgs.
Is there any workaround that I could use to trigger the CursorChanged event with my method?
UPDATE 1:
As requested, here's the bunch of code for the Node_Selection_Action method:
private void Node_Selection_Action(object sender, TreeNodeMouseClickEventArgs e)
{
TvwPanel.SelectedNode = e.Node;
if (Convert.ToString(e.Node.Tag) == "a") //profile Convert.ToInt16()
{
TsmNewPr.Enabled = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Enabled = true;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Enabled = true;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "b") //database
{
TsmNewPr.Visible = false;
TsmNewDb.Enabled = true;
// arbitrary control if database already exists. If exists disable, otherwise enable.
#region TsmNewDb.Enabled (true/false)
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement enc in profNode)
{
// get the attribute texts
var childrenTexts = enc.Elements("node").Attributes("text");
foreach (var childText in childrenTexts)
{
if (childText.Value != "Type" || childText.Value != "Name" || childText.Value != "Connection")
{
// enable TsmNewDb ContextMenu button if does not exists yet
TsmNewDb.Enabled = false;
}
}
// initialize the attribute tags to null
string TypeTag = null;
string NameTag = null;
string ConnTag = null;
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
TypeTag = childTag.Value;
}
else if (count == 1)
{
NameTag = childTag.Value;
}
else if (count == 2)
{
ConnTag = childTag.Value;
}
count++;
}
// check if database exists
if (db.Databases_Exists(ConnTag) == true)
{
// convert the password to "*" for display purposes
string s = ConnTag;
int start = s.LastIndexOf("pwd=") + "pwd=".Length;
int end = s.IndexOf(";", start);
string result = s.Substring(start, end - start);
s = s.Replace(result, "********");
ConnTag = s;
// transfer data FrmDatabase form to main form tabcontrol panel
LblDbTypeDef.Text = TypeTag;
LblDbNameDef.Text = NameTag;
LblDbConnDef.Text = ConnTag;
// make the main tabcontrol panel visible to true
TbcMain.SelectedIndex = 0;
TbcMain.Visible = true;
}
else
{
// make the main tabcontrol panel visible to false
TbcMain.SelectedIndex = 0;
TbcMain.Visible = false;
}
}
}
#endregion
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Enabled = true;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Enabled = true;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "c") //company file
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Enabled = true;
// arbitrary control if company file already exists. If exists, disable, otherwise enable.
#region TsmNewCo.Enabled (true/false)
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement enc in profNode)
{
// get the attribute texts
var childrenTexts = enc.Elements("node").Attributes("text");
foreach (var childText in childrenTexts)
{
if (childText.Value != "Company Name" || childText.Value != "File Path")
{
// enable TsmNewCo ContextMenu button if does not exists yet
TsmNewCo.Enabled = false;
}
}
// initialize the attribute tags to null
string CoFileTag = null;
string FilePathTag = null;
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
CoFileTag = childTag.Value;
}
else if (count == 1)
{
FilePathTag = childTag.Value;
}
count++;
}
// show db details on the right panel of the main form
if (CoFileTag != null || FilePathTag != null)
{
TbcMain.SelectedIndex = 1;
TbcMain.Visible = true;
LblCompanyFileDef.Text = CoFileTag;
LblFilePathDef.Text = FilePathTag;
}
else
{
TbcMain.SelectedIndex = 1;
TbcMain.Visible = false;
}
}
}
#endregion
TsmNewTk.Visible = false;
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Enabled = true;
TsmEditTk.Visible = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Enabled = true;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
}
else if (Convert.ToString(e.Node.Tag) == "d") //tasks
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Enabled = true;
#region Enable/Disable "New" if database and company file are not saved yet
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeDbSiblingName = TvwPanel.SelectedNode.PrevNode.PrevNode.Text;
selNodeCoSiblingName = TvwPanel.SelectedNode.PrevNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profile =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeParentName
select ep;
// inquire if database has child or db already, if not this node is disabled
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeDbSiblingName
select en;
if (profNode.Descendants().Count() == 0)
{
TsmNewTk.Enabled = false;
}
}
// inquire if company file has child or has file already, if not this node is disabled
foreach (XElement epi in profile)
{
IEnumerable<XElement> profNode =
from en in epi.Elements("node")
where (string)en.Attribute("text") == selNodeCoSiblingName
select en;
if (profNode.Descendants().Count() == 0)
{
TsmNewTk.Enabled = false;
}
else
{
foreach (XElement enc in profNode)
{
// get the attribute tags
var childrenTags = enc.Elements("node").Attributes("tag");
int count = 0;
// get company details for showing on the right panel of the main form specified below for task creation
foreach (var childTag in childrenTags)
{
if (count == 1)
{
qbFilePath = childTag.Value;
}
count++;
}
}
}
}
#endregion
TsmNewTkCred.Visible = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Enabled = false;
TsmEditTkCred.Visible = false;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Enabled = false;
TsmDeleteTkCred.Visible = false;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = false;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
// arbitrary control for showing up tasks summary
#region Extract data from Xml and show in the main form tabcontrol
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
if (Xml_Extract_Data_TaskSum(selNodeParentName, selNodeName) == true)
{
TbcMain.SelectedIndex = 2;
TbcMain.Visible = true;
}
else
{
TbcMain.SelectedIndex = 2;
TbcMain.Visible = false;
}
#endregion
}
else // for the task credentials
{
TsmNewPr.Visible = false;
TsmNewDb.Visible = false;
TsmNewCo.Visible = false;
TsmNewTk.Visible = false;
TsmNewTkCred.Enabled = false;
TsmNewLg.Visible = false;
TsmEditPr.Visible = false;
TsmEditDb.Visible = false;
TsmEditCo.Visible = false;
TsmEditTk.Visible = false;
TsmEditTkCred.Enabled = true;
TsmEditLg.Visible = false;
TsmDeletePr.Visible = false;
TsmDeleteDb.Visible = false;
TsmDeleteCo.Visible = false;
TsmDeleteTk.Visible = false;
TsmDeleteTkCred.Enabled = true;
TsmDeleteLg.Visible = false;
TsmRunTk.Enabled = true;
TsmRefreshLg.Enabled = false;
TsmHelpAll.Enabled = true;
// arbitrary control for showing up tasks details
#region Extract data from Xml and show in the main form tabcontrol
selNodeGrandParentName = TvwPanel.SelectedNode.Parent.Parent.Text;
selNodeDbSiblingName = TvwPanel.SelectedNode.Parent.PrevNode.PrevNode.Text;
selNodeCoSiblingName = TvwPanel.SelectedNode.Parent.PrevNode.Text;
selNodeParentName = TvwPanel.SelectedNode.Parent.Text;
selNodeName = TvwPanel.SelectedNode.Text;
Save_Treeview_To_Xml xcf = new Save_Treeview_To_Xml();
XElement xmlComplete = XElement.Load(xcf.xmlProfileComplete);
IEnumerable<XElement> profileTask =
from ep in xmlComplete.Elements("node")
where (string)ep.Attribute("text") == selNodeGrandParentName
select ep;
foreach (XElement ep in profileTask)
{
IEnumerable<XElement> profNodeTask =
from en in ep.Elements("node")
where (string)en.Attribute("text") == selNodeParentName
select en;
foreach (XElement ept in profNodeTask)
{
IEnumerable<XElement> profNodeTaskCred =
from en in ept.Elements("node")
where (string)en.Attribute("text") == selNodeName
select en;
foreach (XElement eptc in profNodeTaskCred)
{
// initialize the attribute tags to null
string ActionTag = null;
string TablesTag = null;
string FiltersTag = null;
string ScheduleTag = null;
// get the attribute tags
var childrenTags = eptc.Elements("node").Attributes("tag");
int count = 0;
// get db details for showing on the right panel of the main form specified below
foreach (var childTag in childrenTags)
{
if (count == 0)
{
ActionTag = childTag.Value;
}
else if (count == 1)
{
TablesTag = childTag.Value;
}
else if (count == 2)
{
FiltersTag = childTag.Value;
}
else if (count == 3)
{
ScheduleTag = childTag.Value;
}
count++;
}
// show db details on the right panel of the main form
if (ActionTag != null || FiltersTag != null || ScheduleTag != null)
{
LblActionDef.Text = ActionTag;
// TablesTag
string[] TablesTagArray = TablesTag.Split(','); //(new char[] { ',', ' ' });
LvwTables.Items.Clear();
foreach (string tt in TablesTagArray)
{
string table = tt.TrimStart();
ListViewItem lvi = new ListViewItem(table);
LvwTables.Items.Add(lvi);
}
// FiltersTag
// filter period
string filterPeriod;
int Pos1 = FiltersTag.IndexOf("Transactions: ") + "Transactions: ".Length;
int Pos2 = FiltersTag.IndexOf(" | Migration");
filterPeriod = FiltersTag.Substring(Pos1, Pos2 - Pos1);
LblFtrPeriodDef.Text = filterPeriod;
// migration type
string migrationType;
int Pos3 = FiltersTag.IndexOf("Type: ") + "Type: ".Length;
int Pos4 = FiltersTag.IndexOf(" | No");
migrationType = FiltersTag.Substring(Pos3, Pos4 - Pos3);
LblFtrMigTypeDef.Text = migrationType;
// no of record per query
string numberRecords;
int Pos5 = FiltersTag.IndexOf("Query: ") + "Query: ".Length;
numberRecords = FiltersTag.Substring(Pos5);
LblFtrRpqDef.Text = numberRecords;
// filter head
if (filterPeriod == "All" && migrationType == "Overwrite" && numberRecords == "0")
{
LblFiltersDef.Text = "Default";
}
else
{
LblFiltersDef.Text = "Custom";
}
LblSchedDef.Text = ScheduleTag;
TbcMain.SelectedIndex = 3;
TbcMain.Visible = true;
}
else
{
TbcMain.SelectedIndex = 3;
TbcMain.Visible = false;
}
}
}
}
// capture the db credentials for task running
Capture_DB_Credentials_for_NodeMouseClick_And_Task_Saving(selNodeGrandParentName, selNodeDbSiblingName, selNodeCoSiblingName);
#endregion
}
if (e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X, e.Y);
TreeNode ClickNode = TvwPanel.GetNodeAt(ClickPoint);
if (ClickNode == null) return;
// Convert from Tree coordinates to Screen coordinates
Point ScreenPoint = TvwPanel.PointToScreen(ClickPoint);
// Convert from Screen coordinates to Form coordinates
Point FormPoint = this.PointToClient(ScreenPoint);
CmsPanel.Show(this, FormPoint);
}
}
In the Node_Selection_Action method, the last if statement block:
if (e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X, e.Y);
TreeNode ClickNode = TvwPanel.GetNodeAt(ClickPoint);
if (ClickNode == null) return;
// Convert from Tree coordinates to Screen coordinates
Point ScreenPoint = TvwPanel.PointToScreen(ClickPoint);
// Convert from Screen coordinates to Form coordinates
Point FormPoint = this.PointToClient(ScreenPoint);
CmsPanel.Show(this, FormPoint);
}
is the only block of code that needs the TreeNodeMouseClickEventArgs properties. If you really need to pass this type of argument to the method then create one:
// Still no idea what is the relation, however...
private void TvwPanel_CursorChanged(object sender, EventArgs e)
{
var s = sender as TreeView;
var p = s.PointToClient(Cursor.Position);
var ht = s.HitTest(p);
if (ht.Node != null)
{
var args = new TreeNodeMouseClickEventArgs(ht.Node, MouseButtons, 1, p.X, p.Y);
Node_Selection_Action(s, args);
}
}
Unless I'm missing an access to the sender param in your code, you can omit it to simplify the method signature:
private void Node_Selection_Action(TreeNodeMouseClickEventArgs e) { }
Also, you can determine which mouse button is pressed anywhere in your code through the Control.MouseButtons property. The Control.MousePosition property gets the cursor's position in screen coordinates. So, maybe these two properties are all what you need.
Maybe the mentioned above last if block is in the wrong method and moving it into a new method or elsewhere in the context could be better.
Hope that helps.
I am having a problem with all properties of each item in a List<ButtonTemplateModel> get values of the last added item. Does anyone know why?
public Task<IViewComponentResult> InvokeAsync(EpisodeVM EpisodeBtnConfig)
{
Dictionary<string,string> stageType = Helpers.EpisodeCommandButtonSettings.stageType;
Dictionary<string, string> actionBtnClass = Helpers.EpisodeCommandButtonSettings.actionBtnColor;
List<ButtonTemplateModel> cmdButtonVMList = new();
string rawID;
if (EpisodeBtnConfig.EpisodeID > 0)
{
rawID = EpisodeBtnConfig.PINFK;
EpisodeBtnConfig.PINFK = rawID.Substring(rawID.Length - 4, 4);
}
/* iterate 8 stage types */
foreach (KeyValuePair<string, string> entry in stageType)
{
ButtonTemplateModel cmdBtnTemplateVM = new()
{
ActionVM = EpisodeBtnConfig.ActionButtonVM,
Title = entry.Value,
Stage = entry.Key,
TextNode = entry.Key,
ActionBtnCssClass = actionBtnClass[entry.Key],
ShowThisButton = true,
DisableThisButton = false
};
switch (cmdBtnTemplateVM.Stage)
{
case "PeopleList":
cmdBtnTemplateVM.TextNode = "Back to People List";
if (EpisodeBtnConfig.ActionButtonVM.HostingPage == "Question")
{
cmdBtnTemplateVM.ActionVM.ControllerName = "PeopleList";
cmdBtnTemplateVM.ActionVM.ActionName = "Index";
cmdBtnTemplateVM.ActionVM.PeopleListID = string.Empty;
cmdBtnTemplateVM.ActionVM.EpisodeID = -1;
}
else
cmdBtnTemplateVM.ShowThisButton = false;
break;
case "Full":
cmdBtnTemplateVM.TextNode = "IRF-PAI";
break;
case "Followup":
cmdBtnTemplateVM.TextNode = "Follow Up";
break;
}
if (EpisodeBtnConfig.ActionButtonVM.EpisodeID == -1 && (cmdBtnTemplateVM.Stage != "PeopleList" && cmdBtnTemplateVM.Stage != "Base"))
cmdBtnTemplateVM.DisableThisButton = true;
if (EpisodeBtnConfig.ActionButtonVM.EpisodeID != -1 && cmdBtnTemplateVM.Stage != "New")
cmdBtnTemplateVM.Title = cmdBtnTemplateVM.Title.Replace("Create new", "Edit existing");
cmdButtonVMList.Add(cmdBtnTemplateVM);
}
string viewName = "StageCommandBtn";
return Task.FromResult<IViewComponentResult>(View(viewName, cmdButtonVMList));
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.
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.