I have a checkbox with event like this:
protected void cbRating1WithoutExceptionP1_CheckedChanged(object sender, EventArgs e)
{
if (cbRating1WithoutExceptionP1.Checked == true)
{
cbRating1WithExceptionP1.Checked = false;
cbRating1WithExceptionP1.Enabled = false;
}
else
{
cbRating1WithExceptionP1.Enabled = true;
}
}
How to call that event from server side?
foreach (string oWithException in oWithExceptions)
{
switch (oWithException.Trim())
{
case "P1":
cbRating2WithExceptionP1.Checked = true;
cbRating1WithoutExceptionP1_CheckedChanged(new object, new EventArgs);
break;
case "P2":
cbRating2WithExceptionP2.Checked = true;
break;
case "P3":
cbRating2WithExceptionP3.Checked = true;
break;
case "P4":
cbRating2WithExceptionP4.Checked = true;
break;
case "P5":
cbRating2WithExceptionP5.Checked = true;
break;
case "NOT_ALLOWED":
cbRating2WithExceptionNotAllowed.Checked = true;
cbRating2WithExceptionP1.Checked = false;
cbRating2WithExceptionP1.Enabled = false;
cbRating2WithExceptionP2.Checked = false;
cbRating2WithExceptionP2.Enabled = false;
cbRating2WithExceptionP3.Checked = false;
cbRating2WithExceptionP3.Enabled = false;
cbRating2WithExceptionP4.Checked = false;
cbRating2WithExceptionP4.Enabled = false;
cbRating2WithExceptionP5.Checked = false;
cbRating2WithExceptionP5.Enabled = false;
break;
}
}
}
Like this:
cbRating1WithoutExceptionP1_CheckedChanged(new object, new EventArgs);
Is that possible to call the event from server side without create a function?
You Like This if You wants to Only Call Your method:
cbRating1WithoutExceptionP1_CheckedChanged(null, EventArgs.Empty);
Related
So, I'm losing my mind over a bug in my software.
I have this code, I use it 2 times in my software, the other function similar (with a different name) works normally. But this one is inverted...
I mean by that : Instead of enabling the controls when the groupbox.text contains "INC", it disable them.
Any idea on what is going on?
`private void Enable_disableSTM()
{
if (STM_groupBox.Text.Contains("INC"))
{
STM_radioButton_appel.Enabled = true;
STM_radioButton_autre.Enabled = true;
STM_radioButton_resolution.Enabled = true;
STM_Textbox_SR.Enabled = true;
STM_textBox_remarque.Enabled = true;
STM_Dropdown_Sendto.Enabled = true;
STM_pictureBox_Boutonenvoyer.Enabled = true;
}
else
{
STM_radioButton_appel.Enabled = false;
STM_radioButton_autre.Enabled = false;
STM_radioButton_resolution.Enabled = false;
STM_Textbox_SR.Enabled = false;
STM_textBox_remarque.Enabled = false;
STM_Dropdown_Sendto.Enabled = false;
STM_pictureBox_Boutonenvoyer.Enabled = false;
}
} `
Edit :
Like I said, in my software I have this other function that is working fine. I tried also to change my IF to STM_Textbox_reademail.Text != "" and it's still not working correctly. It's inverted. Enabling when it should not and Disabling too.
`if (SQ_TextBox_reademail.Text != "")
{
SQ_radioButton_appel.Enabled = true;
SQ_radioButton_autre.Enabled = true;
SQ_radioButton_resolution.Enabled = true;
SQ_Textbox_SR.Enabled = true;
SQ_textBox_remarque.Enabled = true;
SQ_Dropdown_Sendto.Enabled = true;
SQ_pictureBox_Boutonenvoyer.Enabled = true;
}
else
{
SQ_radioButton_appel.Enabled = false;
SQ_radioButton_autre.Enabled = false;
SQ_radioButton_resolution.Enabled = false;
SQ_Textbox_SR.Enabled = false;
SQ_textBox_remarque.Enabled = false;
SQ_Dropdown_Sendto.Enabled = false;
SQ_pictureBox_Boutonenvoyer.Enabled = false;
} `
Edit 2 : Okay... I figured out something that works. I'm calling my function at a different place now and it's working. Still does not make sense why I can call the other one at the same place and it works but this one doesn't... but hey... now it works! thanks all!
Your problem is that you are checking if a string contains the "INC" word in a case sensitive way the solution is changing the if statement to check in the string the inc word ignoring the case :
private void Enable_disableSTM()
{
if (STM_groupBox.Text.IndexOf("INC", StringComparison.OrdinalIgnoreCase) >= 0;)
{
STM_radioButton_appel.Enabled = true;
STM_radioButton_autre.Enabled = true;
STM_radioButton_resolution.Enabled = true;
STM_Textbox_SR.Enabled = true;
STM_textBox_remarque.Enabled = true;
STM_Dropdown_Sendto.Enabled = true;
STM_pictureBox_Boutonenvoyer.Enabled = true;
}
else
{
STM_radioButton_appel.Enabled = false;
STM_radioButton_autre.Enabled = false;
STM_radioButton_resolution.Enabled = false;
STM_Textbox_SR.Enabled = false;
STM_textBox_remarque.Enabled = false;
STM_Dropdown_Sendto.Enabled = false;
STM_pictureBox_Boutonenvoyer.Enabled = false;
}
}
Okay... I figured out something that works. I'm calling my function at a different place now and it's working. Still does not make sense why I can call the other one at the same place and it works but this one doesn't... but hey... now it works! thanks all!
I am working on project in C# windows form application.
In this project main Form contain subform for communication of serial port. SubForm "Connect" have two buttons Connect and Close. Also 5 comboboxes to select baudrate, Com name,parity, stopbits and databits.
When I click on Connect button after selecting all settings from comboboxes. port gets connected and connect button becomes Disconnect. And I will close the Connect form
Now my problem is that when I reopen the form, without clicking on Disconnect button when i Close the form , the Comport will disconnected. I don't want that ComPort close.
Please help me to solve this bug. I don't know where I did mistake. Thanks in advance.
Connect Class Code
public partial class Connect : Form
{
public bool Connect_Status = false;
public Connect()
{
InitializeComponent();
COM_List();
}
private void COM_List()
{
for (int i = 0; i < CommPortManager.Instance.GetCommList().Count; i++)
{
cb_CommPort.Items.Add(CommPortManager.Instance.GetCommList()[i]);
}
}
private void btn_Connect_Click(object sender, EventArgs e)
{
if (btn_Connect.Text == "Connect")
{
CommPortManager.Instance.PortName = cb_CommPort.Text;
CommPortManager.Instance.BaudRate = cb_BaudRate.Text;
CommPortManager.Instance.Parity = cb_Parity.Text;
CommPortManager.Instance.StopBits = cb_StopBits.Text;
CommPortManager.Instance.DataBits = cb_DataBits.Text;
if ((cb_CommPort.Text == "") || (cb_BaudRate.Text == "") || (cb_Parity.Text == "") || (cb_DataBits.Text == "") || (cb_StopBits.Text == ""))
{
if (cb_CommPort.Text == "")
{
MessageBox.Show("Please select COM Port and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (cb_BaudRate.Text == "")
{
MessageBox.Show("Please select BaudRate and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (cb_Parity.Text == "")
{
MessageBox.Show("Please select Parity and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (cb_DataBits.Text == "")
{
MessageBox.Show("Please select DataBits and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if(cb_StopBits.Text == "")
{
MessageBox.Show("Please select StopBits and then Connect", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Connect_Status = false;
}
else
{
if (CommPortManager.Instance.COM_Open() == false)
{
MessageBox.Show("Could not open the COM port. Most likely it is already in use, has been removed, or is unavailable.", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
Connect_Status = false;
}
else
{
//CommPortManager.Instance.COM_Close();
Connect_Status = true;
btn_Connect.Text = "Disconnect";
cb_CommPort.Enabled = false;
cb_BaudRate.Enabled = false;
cb_DataBits.Enabled = false;
cb_Parity.Enabled = false;
cb_StopBits.Enabled = false;
btn_Connect.BackColor = System.Drawing.Color.Salmon;
}
}
}
else
{
CommPortManager.Instance.COM_Close();
btn_Connect.Text = "Connect";
Connect_Status = false;
cb_CommPort.Enabled = true;
cb_BaudRate.Enabled = true;
cb_DataBits.Enabled = true;
cb_Parity.Enabled = true;
cb_StopBits.Enabled = true;
btn_Connect.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
this.Close();
}
private void Connect_Load(object sender, EventArgs e)
{
//code here to setup the value;
cb_CommPort.Text = CommPortManager.Instance.PortName;
cb_BaudRate.Text = CommPortManager.Instance.BaudRate;
cb_Parity.Text = CommPortManager.Instance.Parity;
cb_StopBits.Text = CommPortManager.Instance.StopBits;
cb_DataBits.Text = CommPortManager.Instance.DataBits;
if (CommPortManager.Instance.IsOpen == true)
{
btn_Connect.Text = "Disconnect";
btn_Connect.BackColor = System.Drawing.Color.Salmon;
cb_CommPort.Enabled = false;
cb_BaudRate.Enabled = false;
cb_DataBits.Enabled = false;
cb_Parity.Enabled = false;
cb_StopBits.Enabled = false;
}
else
{
btn_Connect.Text = "Connect";
Connect_Status = false;
cb_CommPort.Enabled = true;
cb_BaudRate.Enabled = true;
cb_DataBits.Enabled = true;
cb_Parity.Enabled = true;
cb_StopBits.Enabled = true;
btn_Connect.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
}
I suspect that the form load event. you need to set the connection status true when its open
private void Connect_Load(object sender, EventArgs e)
{
//code here to setup the value;
cb_CommPort.Text = CommPortManager.Instance.PortName;
cb_BaudRate.Text = CommPortManager.Instance.BaudRate;
cb_Parity.Text = CommPortManager.Instance.Parity;
cb_StopBits.Text = CommPortManager.Instance.StopBits;
cb_DataBits.Text = CommPortManager.Instance.DataBits;
if (CommPortManager.Instance.IsOpen == true)
{
Connect_Status = true;
btn_Connect.Text = "Disconnect";
btn_Connect.BackColor = System.Drawing.Color.Salmon;
cb_CommPort.Enabled = false;
cb_BaudRate.Enabled = false;
cb_DataBits.Enabled = false;
cb_Parity.Enabled = false;
cb_StopBits.Enabled = false;
}
else
{
btn_Connect.Text = "Connect";
Connect_Status = false;
cb_CommPort.Enabled = true;
cb_BaudRate.Enabled = true;
cb_DataBits.Enabled = true;
cb_Parity.Enabled = true;
cb_StopBits.Enabled = true;
btn_Connect.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
It looks like that if you press Connect it changes your btn_Connect.Text to
Disconnect (if the port is open)
now the button text is "Disconnect" and if (btn_Connect.Text == "Connect") is now false and the else is called which does CommPortManager.Instance.COM_Close();
As title, how to release thread is required in multiple thread ?
Ex : I have 5 thread is waiting. I only want thread position 3 is released
I use autoresetevent/manualresetevent/monitor.wait and monitor.pulse but all release thread follow FIFO
help me !!!
UPDATED:
This is form1:
private BackgroundWorker[] threadArray;
public static ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
private void btn_Start_Scraping_Click(object sender, EventArgs e)
{
threadArray = new BackgroundWorker[listView_Site.Items.Count];
for (var f = 0; f < listView_Site.Items.Count; f++)
{
threadArray[f] = new BackgroundWorker();
threadArray[f].DoWork += new DoWorkEventHandler(BackgroundWorkerFilesDoWork);
threadArray[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerFilesRunWorkerCompleted);
threadArray[f].ProgressChanged += new ProgressChangedEventHandler(BackgroundWorkerFilesProgressChanged);
threadArray[f].WorkerReportsProgress = true;
threadArray[f].WorkerSupportsCancellation = true;
threadArray[f].RunWorkerAsync(listView_Site.Items[f].Tag.ToString());
}
}
private void BackgroundWorkerFilesDoWork(object sender, DoWorkEventArgs e)
{
....// all above code is fine
requestCaptcha = (HttpWebRequest)WebRequest.Create(uriCaptchaPage);
requestCaptcha.Pipelined = true;
requestCaptcha.KeepAlive = true;
requestCaptcha.AllowAutoRedirect = false;
//request.Proxy = null;
requestCaptcha.Timeout = 60000;
requestCaptcha.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
requestCaptcha.CookieContainer = sessionID;
request.ServicePoint.Expect100Continue = false;
requestCaptcha.Method = "GET";
requestCaptcha.Referer = uriloginPage.AbsoluteUri;
//get response.
responseCaptcha = (HttpWebResponse)requestCaptcha.GetResponse();
Stream imagestream = responseCaptcha.GetResponseStream();
if (imagestream != null)
{
Image image = Image.FromStream(imagestream);
if (Directory.Exists(Application.StartupPath + "\\Captcha") == false)
{
Directory.CreateDirectory(Application.StartupPath + "\\Captcha");
}
switch (responseCaptcha.ContentType)
{
case "image/jpeg":
{
saveLocation += ".jpg";
if (File.Exists(saveLocation))
{
File.Delete(saveLocation);
}
image.Save(saveLocation,ImageFormat.Jpeg);
break;
}
case "image/gif":
{
saveLocation += ".gif";
if (File.Exists(saveLocation))
{
File.Delete(saveLocation);
}
image.Save(saveLocation, ImageFormat.Gif);
break;
}
case "image/png":
{
saveLocation += ".png";
if (File.Exists(saveLocation))
{
File.Delete(saveLocation);
}
image.Save(saveLocation, ImageFormat.Png);
break;
}
}
//show form2 to enter captcha
lock (_lockObj)
{
if (Application.OpenForms.OfType<frmCaptchaQuestion>().Any() == false)
{
DoOnUIThread(delegate()
{
_formCaptchaQuestion.CreatePanelCaptcha(uriloginPage, saveLocation,idHomePage);
_formCaptchaQuestion.Show();
});
}
else
{
DoOnUIThread(() => _formCaptchaQuestion.CreatePanelCaptcha(uriloginPage, saveLocation,idHomePage));
}
}
//wait and get captcha from form2 and only run thread is required
//this is my problem <<<<========================================
lock (_lockObj)
{
//_manualResetEvent.WaitOne(30000);
//_manualResetEvent.Reset();
//if (clsValueStatic.CaptchaText != null)
//{
// foreach (var id in clsValueStatic.CaptchaText)
// {
while (!_go)
{
Monitor.Wait(_lockObj);
}
// }
//}
}
requestCaptcha = (HttpWebRequest)WebRequest.Create(uriActionLoginPage);
requestCaptcha.Pipelined = true;
requestCaptcha.KeepAlive = true;
requestCaptcha.AllowAutoRedirect = false;
//request.Proxy = null;
requestCaptcha.Timeout = 60000;
requestCaptcha.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
requestCaptcha.CookieContainer = sessionID;
request.ServicePoint.Expect100Continue = false;
requestCaptcha.Method = "GET";
}
Form2:
private void textBoxCaptcha_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textBox = sender as TextBoxX;
if (textBox != null)
{
clsValueStatic.CaptchaText = textBox.Text.Trim();
textBox.Parent.Parent.Dispose();
frmScrapingAnalysis._manualResetEvent.Set();
}
}
}
PS : Form1 have 1 button to start multiple backgroundworker and show form2 then all backgroundworker wait to get text captcha of textbox from form2
my way want when user enter text of backgroundworker is shown on form2 then only the backgroundworker is released. All other backgroundworker still wait
I have a windows form that involes filling out textboxes with information and then clicking connect. I have error messages that pops up if any of the textboxes are empty but when I hit OK the program just continues and I end up getting run-time errors because there's insufficient information, and the program crashes. What I want is for the program to go back to the point before I hit "Connect" whenever any textbox is not filled out correctly.
This is the code:
private void cmdConnect_Click(object sender, EventArgs e)
{
if (cmdConnect.Text == "Connect")
{
if (txtGroup.Text == "")
{
txtGroup.Text = "_Group01";
}
if (txtItemID.Text == "")
{
MessageBox.Show("Please enter ItemID.", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
switch (cboServer.Text)
{
case "":
MessageBox.Show("Please select and OPC server", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case "RSLinx Remote OPC Server":
if (txtMachine.Text == "")
{
MessageBox.Show("Please enter a machine name for remote connection", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
else
{
oOpcServer.Connect(cboServer.Text, txtMachine.Text);
}
break;
case "RSLinx OPC Server":
oOpcServer.Connect(cboServer.Text);
break;
default:
if (txtMachine.Text == "")
{
oOpcServer.Connect(cboServer.Text);
}
else
{
oOpcServer.Connect(cboServer.Text, txtMachine.Text);
}
break;
}
oOpcGroup = oOpcServer.OPCGroups.Add(txtGroup.Text);
oOpcGroup.IsSubscribed = true;
oOpcGroup.IsActive = false;
oOpcGroup.UpdateRate = 1000;
ClHandle = 1;
oOpcGroup.OPCItems.DefaultAccessPath = txtAccessPath.Text;
oOpcGroup.OPCItems.AddItem(txtItemID.Text, ClHandle);
cmdItemWrite.Enabled = true;
cmdItemRead.Enabled = true;
cmdSyncWrite.Enabled = true;
cmdSyncRead.Enabled = true;
cmdAsyncWrite.Enabled = true;
cmdAsyncRead.Enabled = true;
cmdAdvise.Enabled = true;
txtSubValue.Enabled = true;
cboServer.Enabled = false;
txtMachine.Enabled = false;
txtGroup.Enabled = false;
txtAccessPath.Enabled = false;
txtItemID.Enabled = false;
cmdConnect.Text = "Disconnect";
}
else
{
oOpcServer.OPCGroups.RemoveAll();
oOpcGroup = null;
oOpcServer.Disconnect();
cmdConnect.Text = "Connect";
cmdItemWrite.Enabled = false;
cmdItemRead.Enabled = false;
cmdSyncWrite.Enabled = false;
cmdSyncRead.Enabled = false;
cmdAsyncWrite.Enabled = false;
cmdAsyncRead.Enabled = false;
cmdAdvise.Enabled = false;
txtSubValue.Enabled = false;
cboServer.Enabled = true;
txtMachine.Enabled = true;
txtGroup.Enabled = true;
txtAccessPath.Enabled = true;
txtItemID.Enabled = true;
}
oOpcGroup.DataChange += new RsiOPCAuto.DIOPCGroupEvent_DataChangeEventHandler(oOpcGroup_DataChange);
}
Adding a return statment after each message box would do the trick and cause the method to exit without doing the work at end.
Simplest solution, as Dervall mentioned is adding return statements after each MessageBox.Show call. But more elegant solution is using validation and error provider to highlight incorrect input data prior to executing connect logic.
Anyway, here is some thoughts on refactoring your code.
private void cmdConnect_Click(object sender, EventArgs e)
{
if (cmdConnect.Text == "Disconnect")
{
Disconnect();
SetControlsToDisconnectedState();
return;
}
if (String.IsNullOrWhiteSpace(txtGroup.Text))
txtGroup.Text = "_Group01";
if (String.IsNullOrWhiteSpace(txtItemID.Text))
{
ShowErrorMessage("Connect Error", "Please enter ItemID.");
return;
}
if (String.IsNullOrWhiteSpace(cboServer.Text))
{
ShowErrorMessage("Connect Error", "Please select and OPC server");
return;
}
Connect(cboServer.Text, txtMachine.Text);
DoSomethingWithGroup(txtGroup.Text, txtAccessPath.Text, txtItemID.Text);
SetControlsToConnectedState();
}
What changed:
It's more readable, when you verify which text on button, then which it don't have
Method ShowErrorMessage does exactly what it says
Verify text with IsNullOrWhiteSpace because it could be full of white spaces
Control state changing moved to separate code
Connecting/Disconnecting now separated from UI
Here other methods:
private void ShowErrorMessage(string title, string message)
{
MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void SetControlsToConnectedState()
{
UpdateControls(true);
}
private void SetControlsToDisconnectedState()
{
UpdateControls(false);
}
private void UpdateControls(bool isConnected)
{
cmdConnect.Text = isConnected ? "Disconnect" : "Connect";
cmdItemWrite.Enabled = isConnected;
cmdItemRead.Enabled = isConnected;
cmdSyncWrite.Enabled = isConnected;
cmdSyncRead.Enabled = isConnected;
cmdAsyncWrite.Enabled = isConnected;
cmdAsyncRead.Enabled = isConnected;
cmdAdvise.Enabled = isConnected;
txtSubValue.Enabled = isConnected;
cboServer.Enabled = !isConnected;
txtMachine.Enabled = !isConnected;
txtGroup.Enabled = !isConnected;
txtAccessPath.Enabled = !isConnected;
txtItemID.Enabled = !isConnected;
}
private void Disconnect()
{
oOpcServer.OPCGroups.RemoveAll();
oOpcGroup = null;
oOpcServer.Disconnect();
}
private void Connect(string serverName, string machineName)
{
switch (serverName)
{
case "RSLinx Remote OPC Server":
if (String.IsNullOrWhiteSpace(machineName))
{
ShowErrorMessage("Connect Error", "Please enter a machine name for remote connection");
return;
}
oOpcServer.Connect(serverName, machineName);
break;
case "RSLinx OPC Server":
oOpcServer.Connect(serverName);
break;
default:
if (String.IsNullOrWhiteSpace(machineName))
oOpcServer.Connect(serverName);
else
oOpcServer.Connect(serverName, machineName);
break;
}
}
private void DoSomethingWithGroup(string groupName, string accessPath, string itemID)
{
oOpcGroup = oOpcServer.OPCGroups.Add(groupName);
oOpcGroup.IsSubscribed = true;
oOpcGroup.IsActive = false;
oOpcGroup.UpdateRate = 1000;
ClHandle = 1;
oOpcGroup.OPCItems.DefaultAccessPath = accessPath;
oOpcGroup.OPCItems.AddItem(itemID, ClHandle);
oOpcGroup.DataChange += new RsiOPCAuto.DIOPCGroupEvent_DataChangeEventHandler(oOpcGroup_DataChange);
}
how can i optimized this code? i dont like to have case statement, is there a way i can improve this code?
protected void ddlFilterResultBy_SelectedIndexChanged(object sender, EventArgs e)
{
string selVal = ddlFilterResultBy.SelectedValue.ToString().ToLower();
switch (selVal)
{
case "date":
pnlDate.Visible = true;
pnlSubject.Visible = false;
pnlofficer.Visible = false;
pnlCIA.Visible = false;
pnlMedia.Visible = false;
pnlStatus.Visible = false;
break;
case "subject":
pnlDate.Visible = false;
pnlSubject.Visible = true;
pnlofficer.Visible = false;
pnlCIA.Visible = false;
pnlMedia.Visible = false;
pnlStatus.Visible = false;
break;
case "officer":
pnlDate.Visible = false;
pnlSubject.Visible = false;
pnlofficer.Visible = true;
pnlCIA.Visible = false;
pnlMedia.Visible = false;
pnlStatus.Visible = false;
break;
case "status":
pnlDate.Visible = false;
pnlSubject.Visible = false;
pnlofficer.Visible = false;
pnlCIA.Visible = false;
pnlMedia.Visible = false;
pnlStatus.Visible = true;
break;
default:
pnlDate.Visible = false;
pnlSubject.Visible = false;
pnlofficer.Visible = false;
pnlCIA.Visible = false;
pnlMedia.Visible = false;
pnlStatus.Visible = false;
break;
}
}
Easy enough. You're only ever making one item visible depending on the case option, so just set the visibility as follows:
pnlDate.Visible = (selVal == "date");
pnlSubject.Visible = (selVal == "subject");
pnlofficer.Visible = (selVal == "officer");
pnlCIA.Visible = false;
pnlMedia.Visible = false;
pnlStatus.Visible = (selVal == "status");
This is better than setting everything to visible = false; and then only showing the item you need as this contains it all into just 6 lines of code for the actual visibility setting.
Another way:
// set everything to false
Dictionary<string, type> d = new Dictionary<string, type>()
{
{"date", pnlDate},
{"subject", plnSubject},
{"officer", plnOfficer},
{"status", plnStatus}
};
d[selVal].Visible = true;
protected void ddlFilterResultBy_SelectedIndexChanged(object sender, EventArgs e)
{
string selVal = ddlFilterResultBy.SelectedValue.ToString().ToLower();
pnlDate.Visible = false;
pnlSubject.Visible = false;
pnlofficer.Visible = false;
pnlCIA.Visible = false;
pnlMedia.Visible = false;
pnlStatus.Visible = false;
switch (selVal)
{
case "date":
pnlDate.Visible = true;
break;
case "subject":
pnlSubject.Visible = true;
break;
case "officer":
pnlofficer.Visible = true;
break;
case "status":
pnlStatus.Visible = true;
break;
}
}
You could do this:
protected void ddlFilterResultBy_SelectedIndexChanged(object sender, EventArgs e) {
string selVal = ddlFilterResultBy.SelectedValue.ToString().ToLower();
pnlDate.Visible = (selVal == "date");
pnlSubject.Visible = (selVal == "subject");
pnlofficer.Visible = (selVal == "officer");
pnlCIA.Visible = (selVal == "cia");
pnlMedia.Visible = (selVal == "media");
pnlStatus.Visible = (selVal == "status");
}
Or this one, while less readable, would be more accurate:
protected void ddlFilterResultBy_SelectedIndexChanged(object sender, EventArgs e) {
string selVal = ddlFilterResultBy.SelectedValue.ToString();
pnlDate.Visible = String.Equals(selVal, "date", StringComparison.OrdinalIgnoreCase);
pnlSubject.Visible = String.Equals(selVal, "subject", StringComparison.OrdinalIgnoreCase);
pnlofficer.Visible = String.Equals(selVal, "officer", StringComparison.OrdinalIgnoreCase);
pnlCIA.Visible = String.Equals(selVal, "cia", StringComparison.OrdinalIgnoreCase);
pnlMedia.Visible = String.Equals(selVal, "media", StringComparison.OrdinalIgnoreCase);
pnlStatus.Visible = String.Equals(selVal, "status", StringComparison.OrdinalIgnoreCase);
}
There is a difference between optimization and improving readability.
So I guess you are looking at improving readability more as optimization is not really needed here. There is no algo here which you can tune to make this faster by a significant time .
Answer 1 and 2 will be my choice of improving readability
I think you need a tabcontrol here..
Just hide the tabs if you don't like those, and page index via code.
The advantage is that you'll be able to edit and view the GUI at designtime.
It'll be a lot easier to maintain.