Using threestate checkbox to determine 3 states of a field - c#

Currently we call a web service to check if user has permission to use the chat room and we receive a 0 or a 1. I want to add to also be able to receive a 2, which will indicate it is enabled and authorized now
so I want to use three state check boxes, fully filled will mean he is authorized and also currently enabled (logged in), check will mean he is authorized but not enabled now, unchecked will mean he doesn't have permission for this chat room.
Here is some code I currently use. FYI I took over this project from our developer and I'm kind of new to this, if you can give me an example even just for authtac1 then I'll figure out how to do all others, and also do I need to add a new field ActiveTac1 like I have AuthTac1? Thanks for your help.
public partial class IMeditor : Form
{
private IMuser imu;
private IMui IMui;
private IMdata IMdata;
public IMeditor(IMui IMui, IMuser U, string Member)
{
InitializeComponent();
this.IMui= IMui;
imu = U;
if (imu.UID == 0)
{
Add.Text = "Add";
imu.MemberNick= Member;
}
else
Add.Text = "Update";
IMdata = new IMdata();
MemberHandle.Text = imu.MemberHandle;
IM.Text = imu.IM;
AuthChat.Checked = imu.AuthChat == 1;
AuthTac1.Checked = imu.AuthTac1 == 1;
AuthTac2.Checked = imu.AuthTac2 == 1;
AuthTac3.Checked = imu.AuthTac3 == 1;
AuthTac4.Checked = imu.AuthTac4 == 1;
switch (imu.Transport.ToLower()) {
case "aim": Transport.SelectedIndex = 0; break;
case "gtalk": Transport.SelectedIndex = 1; break;
case "msn": Transport.SelectedIndex = 2; break;
case "yahoo": Transport.SelectedIndex = 3; break;
}
private void Add_Click(object sender, EventArgs e)
{
IMdata.AddIM(IMui.Username, IMui.Password, imu.UID, MemberHandle.Text, Transport.Text, IM.Text,
AuthChat.Checked ? 1 : 0, 0,
AuthTac1.Checked ? 1 : 0, AuthTac2.Checked ? 1 : 0, AuthTac3.Checked ? 1 : 0,
AuthTac4.Checked ? 1 : 0);
Close();
}
last question, to make sure I didnt screw up anything else
#competemt_tech this is what I ended up using (thanks so so much for your help, and our developer who was able to assist me)
To know how to set the checkboxes when i get the data from the webservice I used
AuthChat.CheckState = GetCheckStateFromAuthCode(imu.AuthChat, imu.Enabled);
AuthTac1.CheckState = GetCheckStateFromAuthCode(imu.AuthTac1, imu.Tac1Enabled);
AuthTac2.CheckState = GetCheckStateFromAuthCode(imu.AuthTac2, imu.Tac2Enabled);
AuthTac3.CheckState = GetCheckStateFromAuthCode(imu.AuthTac3, imu.Tac3Enabled);
and then I used:
private CheckState GetCheckStateFromAuthCode(int AuthCode, int Enabled)
{
switch (AuthCode + Enabled)
{
case 0:
return CheckState.Unchecked; // Unauthorized
case 1:
return CheckState.Checked; // Authorized, not enabled
case 2:
return CheckState.Indeterminate; // Authorized and enabled
default:
return CheckState.Unchecked;
}
}
and after I make changes, to send back to the webservice I used:
imu.AuthChat, imu.Enabled = GetAuthCodeFromCheckState(AuthChat.CheckState),
imu.AuthTac1, imu.Tac1Enabled = GetAuthCodeFromCheckState(AuthTac1.CheckState),
imu.AuthTac2, imu.Tac2Enabled = GetAuthCodeFromCheckState(AuthTac2.CheckState),
imu.AuthTac3, imu.Tac3Enabled = GetAuthCodeFromCheckState(AuthTac3.CheckState),
and then I used:
private int GetAuthCodeFromCheckState(CheckState checkState)
{
switch (checkState)
{
case CheckState.Unchecked: // Unauthorized
return 0;
case CheckState.Indeterminate: // Authorized, not enabled
return 1;
case CheckState.Checked: // Authorized and enabled
return 2;
default:
return 0;
}
}

Based on your code, it appears that you are using WinForms, not WPF, correct?
If this is the case, then you will want to use the CheckState property of the checkbox and not Checked, since it supports three values:
Unchecked = 0
Checked = 1
Indeterminate = 2
Update
In order to address your requirements, you would have code similar to the following:
First, create a function that will generate the correct checkstate base on the authcode:
private CheckState GetCheckStateFromAuthCode(int AuthCode)
{
switch (AuthCode)
{
case 0:
// Unauthorized
return CheckState.Unchecked;
case 1:
// Authorized, not enabled
return CheckState.Indeterminate;
case 2:
// Authorized and enabled
return CheckState.Checked;
default:
throw new ArgumentException("Unrecognized AuthCode value " + AuthCode.ToString());
}
}
Then, use this code to set the state of your checkboxes:
AuthChat.CheckState = GetCheckStateFromAuthCode(imu.AuthChat);
AuthTac1.CheckState = GetCheckStateFromAuthCode(imu.AuthTac1);
etc.
Update 2
In order to retrieve the authcode from the checkstate:
First, create a function that will generate the correct checkstate base on the authcode:
private int GetAuthCodeFromCheckState(CheckState checkState)
{
switch (checkState)
{
case CheckState.Unchecked:
// Unauthorized
return 0;
case CheckState.Indeterminate:
// Authorized, not enabled
return 1;
case CheckState.Checked:
// Authorized and enabled
return 2;
default:
throw new ArgumentException("Unrecognized checkState value " + checkState.ToString());
}
}
Then, use this code to set the auth code from your checkboxes:
imu.AuthChat = GetAuthCodeFromCheckState(AuthChat.CheckState);
imu.AuthTac1 = GetAuthCodeFromCheckState(AuthTac1.CheckState);
etc.

Related

Case/Switch statement not executing part of the code in C#

I have written a Switch/Case statement. The purpose of this statement is to check whether a specific checkbox is selected or not. If the checkbox is selected, the case statements get the true value and the name of the checkbox. For example, if I select Ford in the XAML front end interface, a label gets updated and it adds the value of 10 and if it is unselected, it subtracts 10 as to get the value back. However, I'm just getting the value subtracted. Even when I select the checkbox, I end up with -10, -20 etc values.
I can't figure out where I am going wrong with this.
public static int storage = 0;
public static void StorageRequired(string carName, bool state)
{
switch (carName)
{
case "Ford":
if (state)
{
storage += 10;
}
else
{
storage -= 10;
}
return;
case "Honda":
if (state)
{
storage += 10;
}
else
{
storage -= 10;
}
return;
case "McLaren":
if (state)
{
storage += 10;
}
else
{
storage -= 10;
}
return;
case "Mercedes":
if (state)
{
storage += 10;
}
else
{
storage -= 10;
}
return;
default:
storage = 0;
return;
}
}
Now I have a some checkboxes such as Ford, Honda etc, one for each case. And I am calling them StorageRequired method like this:
private void Single_Checked(object sender, RoutedEventArgs e)
{
if (InstallFord?.IsChecked == true)
{
InstallAE.IsChecked = true;
CarConfigs.StorageRequired("Ford", true);
}
if (InstallFord?.IsChecked == false)
{
InstallAE.IsChecked = false;
CarConfigs.StorageRequired("Ford", false);
}
if (InstallHonda?.IsChecked == true)
{
CarConfigs.StorageRequired("Honda", true);
}
if (InstallHonda?.IsChecked == false)
{
CarConfigs.StorageRequired("Honda", false);
}
if (InstallMcLaren?.IsChecked == true)
{
CarConfigs.StorageRequired("McLaren", true);
}
if (InstallMcLaren?.IsChecked == false)
{
CarConfigs.StorageRequired("McLaren", false);
}
if (InstallMercedesvisitor?.IsChecked == true)
{
CarConfigs.StorageRequired("Mercedes", true);
}
if (InstallMercedesvisitor?.IsChecked == true)
{
CarConfigs.StorageRequired("Mercedes", false);
}
lblRequiredSpace.Content = $"Required space: {CarConfigs.storage} Mb";
}
The problem is that when I click and check a checkbox, for instance Ford, I get -10 instead of 10. And then when I uncheck it again, I get -20. I'd really appreciate some help in figuring out where I am going wrong here. Basically, I should get 10 added if I am checking any of the cars and similarly, 10 subtracted to get back to original value if that car is unchecked.
Note: 10 is just arbitrary here to make things simple.
Here is your problem. Never put return in a switch case, you should use break; instead of return.
I am not really sure what CarConfigs.GetSpaceConsumed is, So I will assume that its a number. So if you are getting a number you should (You don't have to but I reccomend) use return functions.
So this should probably work, however I made the storage to be local variable so it will return number from the switch statement and the whole function in this case would a return function.
public static int StorageRequired(string carName, bool state)
{
int storage = 0;
switch (carName)
{
case "Ford":
if (state){
storage += 10;
}else{
storage -= 10;
}
break;
case "Honda":
if (state){
storage += 10;
}else{
storage -= 10;
}
break;
case "McLaren":
if (state){
storage += 10;
}else{
storage -= 10;
}
break;
case "Mercedes":
if (state){
storage += 10;
}else{
storage -= 10;
}
break;
}
return storage;
}

Best approach to add keyboard "Shortcuts/Hotkeys" to control my application

I'm working on a desktop application in which I want to allow the user to control it's functionalities via Keyboard, also allow him to change the default controllers to a custom controllers according to his point of view.
My question is, what is the best approach to tackle this problem and provide an appropriate solution to this problem?
You can use a Dictionary to bound each key to an action
My approach here is to use a Dictionary where the Key is actual Keybord Keys and value is an int? representing one of your function that can be bound to a custom input.
Dictionnary<Keys, int?> shortcutDictionnary = new Dictionary<Keys, int?>();
// Add a new Keys
shortcutDictionary.Add(Keys.A, 1);
// Change a Keys value (change shortcut bounded to it)
shortcutDictionary[Keys.A] = 4;
To match those int? with these functions you only have to use a switch :
int? num = null;
if (this.shortcutDictionary.TryGetValue(keyPressed, out num))
{
switch (num)
{
case 1:
attack();
break;
case 2:
defend();
break;
case 3:
hide();
break;
case 4:
dance();
break;
default:
Console.WriteLine("Key not bounded");
break;
}
}
I also in my code below use an enum instead of direct use of Keys for my Dictionary. This way, I can choose which Keys can be bounded and which one can't.
My code made from a Winform app, as an exemple I only used 4 Keys (A,B,C,D) which can be bound and one to easily change bound (L), but I'm sure you can figure out how to change bound easily with any other method. Also as I'm working with a WindowsForm, I had to set KeyPreview = true.
Here's my code :
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Project
{
public enum UsableKeys
{
A = Keys.A,
B = Keys.B,
C = Keys.C,
D = Keys.D,
}
public partial class Form1 : Form
{
Dictionary<UsableKeys, int?> shortcutDictionary = new Dictionary<UsableKeys, int?>();
public Form1()
{
InitializeComponent();
foreach (UsableKeys key in Enum.GetValues(typeof(UsableKeys)))
{
// You may add default shortcut here
this.shortcutDictionary.Add(key, null);
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
UsableKeys keyPressed = (UsableKeys)e.KeyCode;
if (this.shortcutDictionary.ContainsKey(keyPressed))
{
executeAction(keyPressed);
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.KeyCode == Keys.L)
{
switch (this.shortcutDictionary[UsableKeys.A])
{
case 1:
this.shortcutDictionary[UsableKeys.A] = 4;
this.shortcutDictionary[UsableKeys.B] = 3;
this.shortcutDictionary[UsableKeys.C] = 2;
this.shortcutDictionary[UsableKeys.D] = 1;
break;
case null:
this.shortcutDictionary[UsableKeys.A] = 1;
this.shortcutDictionary[UsableKeys.B] = 2;
this.shortcutDictionary[UsableKeys.C] = 3;
this.shortcutDictionary[UsableKeys.D] = 4;
break;
case 4:
this.shortcutDictionary[UsableKeys.A] = null;
this.shortcutDictionary[UsableKeys.B] = null;
this.shortcutDictionary[UsableKeys.C] = null;
this.shortcutDictionary[UsableKeys.D] = null;
break;
}
e.Handled = true;
e.SuppressKeyPress = true;
}
}
private void executeAction(UsableKeys keyPressed)
{
int? num = null;
if (this.shortcutDictionary.TryGetValue(keyPressed, out num))
{
switch (num)
{
case 1:
attack();
break;
case 2:
defend();
break;
case 3:
hide();
break;
case 4:
dance();
break;
default:
Console.WriteLine("Key not bounded");
break;
}
}
}
private void attack()
{
Console.WriteLine("Player swing his word");
}
private void defend()
{
Console.WriteLine("Player raise his shield");
}
private void hide()
{
Console.WriteLine("Player sneak around");
}
private void dance()
{
Console.WriteLine("Player start to dance");
}
}
}
With this code, output will be like :
// Press A, B, C or D
"Key not bounded"
// Press L
// Press A
"Player swing his word"
// Press B
"Player raise his shield"
// Press C
"Player sneak around"
// Press D
"Player start to dance"
// Press L
// Press A
"Player start to dance"
// Press B
"Player sneak around"
// Press C
"Player raise his shield"
// Press D
"Player swing his sword"
// Press L
// Press A, B, C or D
"Key not bounded"
Exemple to change key binding in run time :
// Create a new Dictionary for shortcuts
Dictionary<UsableKeys, int?> shortcutDictionary = new Dictionary<UsableKeys, int?>();
// Add a pair key/value that bind A to attack()
shortcutDictionary.Add(UsableKey.A, 1);
// Add a pair Key/value that bind B to defend()
shortcutDictionary.Add(UsableKey.B, 2);
// Now, if you press A, attack() will be called
shortcutDictionary[UsableKey.A] = 2;
// Now if you press A or B, defend() will be called
shortcutDictionary[UsableKey.B] = null;
// Now B isn't bind to any function, so only A is binded to defend();
With this method, you can't bind multiple functions to one Keys while you can bind multiple Keys to one function (If you want to inverse that, just swap key/value of Dictionary and adjust the code to match this).
I don't know if it's the optimal way to do this, but it isn't spaghetti code and it works well.

Radiobuttons, how to replace all those if statements

Several places in my program, the RadioButton matching the selected item has to be checked, and I have a lot of if statements like so:
DataRowView TempRow = (DataRowView)ScheduleDataGrid.SelectedItem;
if (Convert.ToString(TempRow["Bio"]) == "Bio1")
{
BioRB1.IsChecked = true;
}
if (Convert.ToString(TempRow["Bio"]) == "Bio2")
{
BioRB2.IsChecked = true;
}
if (Convert.ToString(TempRow["Bio"]) == "Bio3")
and so on... I want to replace all this with something short and smart.
I tried using the number of the bio to relate to the button like so:
string bioselected = Convert.ToString(TempRow["Bio"]);
int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1));
BioRB[i].IsChecked = true;
but doing a BioRB[i] doesn't work, it ignores the [i] and says BioRB does not exist. Any other suggestions?
BioRB[i] is not doing anything like what you think it's doing. All variable references (controls included) have to be well-defined at compile time - you can't refer to a control's name by building a string that matches the name.**
Try creating a list of your radio buttons. Then you can index into the list:
List<RadioButton> radioButtons = new List<RadioButton>()
{
BioRB1,
BioRB2
};
string bioselected = Convert.ToString(TempRow["Bio"]);
int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1));
radioButtons[i].IsChecked = true;
** Technically you can do this via reflection, but it's far more complex than what you've tried.
Maybe this will look better:
string caseSwitch = Convert.ToString(TempRow["Bio"]);
switch (caseSwitch)
{
case "Bio1":
BioRB1.IsChecked = true;
break;
case "Bio2":
BioRB2.IsChecked = true;
break;
case "Bio3":
BioRB3.IsChecked = true;
break;
default:
Console.WriteLine("Default case...is optional");
break;
}
Also, try doing what Alybaba726 said and use CellContentClick or something like this:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if(e.ColumnIndex == dgv.Columns["Bio"].Index)
{
string bioSelected = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
switch (bioSelected)
{
case "Bio1":
BioRB1.IsChecked = true;
break;
case "Bio2":
BioRB2.IsChecked = true;
break;
case "Bio3":
BioRB3.IsChecked = true;
break;
default:
Console.WriteLine("Default case...this is optional");
break;
}
}
}

Input string was not in a correct format - trying to insert string value to int typed datagridview cell

I'm trying to fill in a telerik radDataGridView (the same problem happens with a normal dataGridView as well).
one of the columns in my db table is named [updateType].
the 'type' is described in an enum:
public enum TypeEnum
{
INSERT = 0,
UPDATE_OR_INSERT = 1,
UPDATE = 2,
DELETE_OR_INSERT = 3
};
i'm filling the dataGridView (dgv) in the Load event:
private void Form1_Load(object sender, EventArgs e)
{
this.table1TableAdapter.Fill(this.tempdbDataSet.Table1);
for (int i = 0; i < dgv.RowCount; i++)
{
switch ((int)dgv.Rows[i].Cells[2].Value)
{
case (int)TypeEnum.INSERT:
dgv.Rows[i].Cells[2].Value = "INSERT";
break;
case (int)TypeEnum.UPDATE_OR_INSERT:
dgv.Rows[i].Cells[2].Value = "UPDATE/INSERT";
break;
case (int)TypeEnum.UPDATE:
dgv.Rows[i].Cells[2].Value = "UPDATE";
break;
case (int)TypeEnum.DELETE_OR_INSERT:
dgv.Rows[i].Cells[2].Value = "INSERT/DELETE";
break;
default:
break;
}
}
}
but it fails, when trying to fill in a string value to an int typed gridview cell,
throwing an exception Input string was not in a correct format.
thanks to anyone who can solve this.
Try
switch ((int)dgv.Rows[i].Cells[2].Value)
{
case (int)TableUpdateModeEnum.INSERT:
dgv.Rows[i].Cells[2].Value = (int)TypeEnum.INSERT;
break;
...
...
}
I've solved my problem in a different way.
instead of filling the datagridview with a table adapter,
i've built it step by step.
for example:
//---
for (int i = 0; i < dataset.Tables[0].Rows.Count; i++)
dgv.Rows.Add(dataset.Tables[0].Rows[i].ItemArray[0].ToString(),
dataset.Tables[0].Rows[i].ItemArray[1].ToString(),
GetEnumString((int)dataset.Tables[0].Rows[i].ItemArray[2]));
//---
private string GetEnumString(int n)
{
switch (n)
{
case (int)TypeEnum.INSERT:
return "INSERT";
case (int)TypeEnum.UPDATE:
return "UPDATE";
case (int)TypeEnum.UPDATE_OR_INSERT:
return "UPDATE/INSERT";
case (int)TypeEnum.DELETE_OR_INSERT:
return "INSERT/DELETE";
default: return "";
}
}
}
public enum TableUpdateModeEnum
{
INSERT = 0,
UPDATE_OR_INSERT = 1,
UPDATE = 2,
DELETE_OR_INSERT = 3
};
thank you anyway!

How to convert radio button list value to bit in asp.net

This is code for inserting value to database but Radio button list value is not converted and inserting failed.
using (SathsurEntities se = new SathsurEntities())
{
tbl_Events user = new tbl_Events();
user.Event_name = txtEventName.Text;
user.Event_date = Convert.ToDateTime(txtEventDate.Text);
user.Image_url = lblimg.Text;
user.Is_free_entry = Convert.ToBoolean(rblEntry.SelectedValue);
user.Booking_url = txtBooking.Text;
se.AddTotbl_Events(user);
se.SaveChanges();
Response.Write("Event Added Successfuly!");
}
a simple answer,
private bool value=true;
if (rblEntry.SelectedValue == "1")
{
value = true;
}
else if (rblEntry.SelectedValue == "2")
{
value = false;
}
user.Is_free_entry = value;
user.Is_free_entry = rblEntry.SelectedValue == "1";
OR
user.Is_free_entry = rblEntry.SelectedValue != "2";
If you can guarantee that all you ever get is either 1 or 2, then these are identical. If you want to try and catch other values, then the first (== "1") emphasizes that you ONLY get true when the value is 1 and you get false for all other values. The second (== "2") says you ONLY get false if the value is 2 and you get true for all other values. Thus, you can set a default on what to do if you get odd values. If you want to detect odd values and throw an exception or do other error handling, then you'll want to go with Vikas Rana's suggestion, but with an additional else
If you are only want to have two value , should have 'true' and 'false', it's enough .
if you have more value or more type ,you can use the type of byte or int ....
the you should use the if ... else ... or switch ... case ...
<asp:RadioButtonList ID="rblList" runat="server">
<asp:ListItem Text="True" Value="True" Selected="True"></asp:ListItem>
<asp:ListItem Text="False" Value="False"></asp:ListItem>
</asp:RadioButtonList>
var a = Convert.ToBoolean(rblList.SelectedValue);
or
var a = Convert.ToInt16(rblList.SelectedValue);
var retValue = string.Empty;
switch (a)
{
case 0:
//"you want have"
break;
case 1:
//"you want have"
break;
case 2:
//"you want have"
break;
default:
//"you want have"
break;
}
or
if (a == 0)
{
//"you want have"
}
else if (a == 1)
{
//"you want have"
}
else if (a == 2)
{
//"you want have"
}
else
{
//"you want have"
}
this is where you might use an extension method along the lines of this:
public static class BooleanExtensions
{
public static bool ToBool(this string value)
{
bool result = false;
switch (value.ToLower().Trim())
{
case "y":
case "yes":
case "1":
result = true;
break;
case "n":
case "no":
case "0":
result = false;
break;
}
return result;
}
}
usage:
var value="0";
Console.Write(value.ToBool());
Should output false.
to use in your project, include that class above. You would use this in your code example like so
using (SathsurEntities se = new SathsurEntities())
{
tbl_Events user = new tbl_Events();
user.Event_name = txtEventName.Text;
user.Event_date = Convert.ToDateTime(txtEventDate.Text);
user.Image_url = lblimg.Text;
user.Is_free_entry = rblEntry.SelectedValue.ToBoolean();
user.Booking_url = txtBooking.Text;
se.AddTotbl_Events(user);
se.SaveChanges();
Response.Write("Event Added Successfuly!");
}

Categories

Resources