recognize which radio button is checked using enum as value - c#

I'm struggling with WinForms. I have a GroupBox which wraps three RadioButtons. I added them using the design view and inside the constructor I tag every button to corresponding enum value like
public MyApp()
{
radioBtnBasic.Tag = UserChoiceEnum.Basic;
radioBtnLite.Tag = UserChoiceEnum.Lite;
radioBtnStandard.Tag = UserChoiceEnum.Standard;
}
Inside my class I have property property of type Dictionary which uses this enum as a key, so I want when the user clicks on winform button to recognize which radio button is checked and to assign to that dictionary.
I've found how to fetch checked option
var choice = grpBox1.Controls.OfType<RadioButton>().FirstOrDefault(x => x.Checked);
Do I need to use switch statement to recognize which Enum is checked or is there some better way?

You get the UserChoiceEnum by:
RadioButton choice = grpBox1.Controls.OfType<RadioButton>().FirstOrDefault(x => x.Checked);
UserChoiceEnum userChoice = (UserChoiceEnum)choice.Tag;

If you set Tag you can simply get it back whenever you need. Note that you need to cast it to original type. Something like:
var choiceAsEnum = (UserChoiceEnum)choice.Tag;

created enum :
public enum SearchType
{
ReferenceData = 0,
Trade = 1,
}
Then use SelectedIndexChanged event of radioGroup control.
private void RadioTypes_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.RadioTypes.SelectedIndex < 0) return;
SearchType n = (SearchType)this.RadioTypes.SelectedIndex;
switch (n)
{
case SearchType.ReferenceData:
break;
case SearchType.Trade:
break;
}
}

Related

How to create a dynamic list of buttons on MainPage in Xamarin.Forms?

I'm creating an application to scan barcode tickets. When you start the app a list of available shows has to be shown on the screen. To get all the available shows I'm using a webservice which returns me a List<Event>. How do I create a list of buttons with each button representing a show/event from inside the xaml.cs? When clicking the button a new page will be shown where the user can scan the tickets from that show. I'm pretty new to Xamarin.Forms and I quite don't understand how to use the paging/content views. I already searched a lot but the closest to what I need was this: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/get-started-with-xaml?tabs=vswin
Unfortunatly it only shows how to add a certain amount of controls. And not a dynamicly generated amount.
Many thanks in advance!
In xaml insert a stacklayout where you want your buttons to appear. Remember you can also play whith its Orientation and Spacing properties. So:
<StackLayout x:Name="MyButtons"/>
Then in code-behind generate your dinamic buttons list. Put the code in constructor AFTER InitializeComponent(); or somewhere else:
var myList = new List<*Event or something*>(); //your list here
MyButtons.Children.Clear(); //just in case so you can call this code several times np..
foreach (var item in myList)
{
var btn = new Button()
{
Text = item.*your property*, //Whatever prop you wonna put as title;
StyleId = item.*your ID property* //use a property from event as id to be passed to handler
};
btn.Clicked += OnDynamicBtnClicked;
MyButtons.Children.Add(btn);
}
Add a handler:
private void OnDynamicBtnClicked(object sender, EventArgs e)
{
var myBtn = sender as Button;
// who called me?
var myId = myBtn.StyleId; //this was set during dynamic creation
//do you stuff upon is
switch (myId)
{
case "1": //or other value you might have set as id
//todo
break;
default:
//todo
break;
}
}

How to assign values for check boxes for a formula calculation which includes a text box in the formula

I am a new programmer learning to code in C# and I have an C# assignment to be finished and for that I need to make some formulas to calculate rent for tours and for that I decided to use text boxes and check boxes in C# but I cant figure out how to make a formula with the combination of check boxes and a text box.
private void button1_Click_1(object sender, EventArgs e)
{
checkBox1.Text = "50000";
checkBox2.Text = "250000";
checkBox3.Text = "2500";
checkBox4.Text = "10000";
checkBox5.Text = "1500";
if (checkBox1.CheckState == CheckState.Checked &&
checkBox2.CheckState == CheckState.Checked)
{
}
}
The type of control has little to do with creating a formula. To create the formula, you need to know all it's possible inputs and how they should be combined to produce the output. This could be done in a method, for example:
private int GetTotalValue(int vehiclePrice, int driverPrice, int rentDuration)
{
// This is where your formula would go
return (vehiclePrice + driverPrice) * rentDuration;
}
The trick then, is to convert the state of the form controls into values that you can plug into the method. One way to do this (not necessarily the best way, but probably easiest to understand when you're starting) is to check the value of each control and set the appropriate value in the Click event for your Submit button.
For the rent duration, we can use the int.TryParse method, which takes in a string and an "out" int parameter, and returns true if the string is a valid integer, or false if it's not. When it exits, if the conversion was successful, the out parameter will contain the int value.
For the other controls, we could use simple if / else if statements to determine which control was checked, and then set our value accordingly. In this example, we're using temporary variables inside the click event to store the value for each parameter to the method. If none of the required controls are checked, we can show a message to the user and wait for them to finish filling out the form.
In this example I used radio buttons (and used the opt prefix, which is a naming convention from a long time ago that I'm not sure still exists - they used to be called option buttons):
private void btnSubmit_Click(object sender, EventArgs e)
{
// Validate that rent textbox contains a number
int rentDuration;
if (!int.TryParse(txtRentDuration.Text, out rentDuration))
{
MessageBox.Show("Please enter a valid number for rent duration");
return;
}
// Determine vehicle price based on which option was selected
int vehiclePrice;
if (optToyotaPrado.Checked) vehiclePrice = 50000;
else if (optRollsRoyce.Checked) vehiclePrice = 250000;
else if (optSuzikiWagonR.Checked) vehiclePrice = 2500;
else if (optToyotaCorolla.Checked) vehiclePrice = 10000;
else
{
MessageBox.Show("Please select a vehicle");
return;
}
// Determine driver price
int driverPrice;
if (optWithDriver.Checked) driverPrice = 1500;
else if (optWithoutDriver.Checked) driverPrice = 0;
else
{
MessageBox.Show("Please select a driver option");
return;
}
// Finally set the text to the return value of our original method,
// passing in the appropriate values based on the user's selections
txtTotalValue.Text = GetTotalValue(vehiclePrice, driverPrice, rentDuration).ToString();
}
As Rufus said, I'd go with RadioButtons, instead of CheckBoxes. Set the Tag property of the RadioButtons to the vaule you want associated with them and then use a function like this to get the value of the checked item. Just pass in the GroupBox to the function and get back the value of the checked RadioButton.
private int GetGroupBoxValue(GroupBox gb)
{
int nReturn = 0;
foreach (Control ctl in gb.Controls)
{
if (ctl.GetType() == typeof(RadioButton))
{
if (((RadioButton)ctl).Checked)
{
nReturn = Convert.ToInt32(ctl.Tag);
break;
}
}
}
return nReturn;
}
Now all you have to do is use the excellent code Rufus provided for checking for an integer in the rentDuration TextBox and you're golden.

Using a ComboBox, UserControl and some forms to change language (for entire project)

Before I begin, I have researched and can't seem to find anything. Note I am very new to UserControl so this might be why it's proven difficult.
I have a combobox in Form1 which when selected allows the user to change between a choice of 21 languages. I have created a UserControl that contains labels, buttons and checkboxes - adds to a form called Print.
If a user selected French, how would I then implement the UserControl to change language for ALL forms in my project?
UserControl:
I have used a get and set method here for a button. When the language is changed in Form1, I want this button (all elements really) to change.
using System.Windows.Forms;
namespace Print
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public string LabelPreview
{
get
{
return Button_Preview.Text;
}
set
{
Button_Preview.Text = value;
}
}
}
}
Form1:
If string value English is selected in the combobox, call a method - here is where I would like to change language for other forms.
private void ComboBoxLang_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedItem = this.comboBoxLang.GetItemText(this.comboBoxLang.SelectedItem);
if (selectedItem == Language.English)
{
ToEnglish();
}
}
private void ToEnglish()
{
// Cannot actually implement the UserControl, It can't find the method above.
// When I've tried to implement UserControl in Print, it can't seem to find it either.
// I've tried:
// Print.UserControl1.(_LabelPreview doesn't show_);
// ^ It might be the completely wrong thing to do so excuse me.
}
I'm so confused... Do I program in Print (where the UserControl is added) or/and Form1?! I don't want the design to appear in Form1, but just want to let the other forms know what language has been selected.
Note: I have been using Unicode when translating*
How to trigger application-wide language change I described here on your other question Everytime ComboBox is changed (using SelectedIndexChanged) display message in other forms, if opened, of new value
Now, to set controls... One way of doing it is to create Database of phrases with StringId in one table and the StringId, LanguageId, StringValue in another. You would create StringManager object, which will have method GetLanguageSpecificString(stringId, languageId). When language change is triggered, your controls will call GetLanguageSpecificString fro each label you display, etc.
So your data will be like
Table DisplayLanguage
LanguageId Int
LanguageName nvarchar
LanguageCulture varchar
//1, English, us-En
//2, French, fr-Ca
Table DisplayString
StringId Int
//1
//2
//3
Table DisplayStringValue
DisplayStringValueId int
StringId int
LanguageId int
StringValue nvarchar
//1, 1, 1, Person Name
//2, 1, 2, Nome de Persona(or whateever)
Create cache using
"Select * from DisplayStringValue where LanguageId = 1"
And then use Linq or something to select for each control its data from cache because you don't want to hit DB with these for each control
"Select StringValue from DisplayStringValue where StringId = 1 and LanguageId = 1"
Now, combine my other answer with this and you will see that if in your form you have
LanguageChangeObserver.LanguageChanged += MyObserverHandler;
private void MyObserverHandler(languageId)
{
_formLanguage = languageId;
// set your controls
lblFirstName.Text = GetLanguageSpecificString(5, languageId);
lblLastName.Text = GetLanguageSpecificString(6, languageId);
// loop through userControls and pass to them language id
}
It would be good idea if your user controls would derive from the single base class that you create and which has already SetNewLanguage Method, so you could do
foreach (var c in form.controls)
{
MyControlBase currControl = c as MyControlBase;
if (currControl != null) currControl.SetNewLanguage(languageId);
}
So I've come up with a solution that works for me! I've copied across from the Printer.cs form where I have used a parameter to represent the language chosen, initiated strTextBox to equal label1 and included an if statement to see if the language is English (also working with UserControl to get the value of labels etc.).
Printer
public Printer(string strTextBox)
{
InitializeComponent();
label1.Text = strTextBox;
if (label1.Text == Language.English)
{
UserControl111.Label_Option_Multi = "Please select an option:"; //Simple test
}
}
Form1
private void Print_Click(object sender, EventArgs e)
{
string selectedItem = this.ComboBox_Lang.GetItemText(this.ComboBox_Lang.SelectedItem);
Printer p = new Printer(selectedItem);
p.Show();
}
UserControl
public string Label_Option_Multi
{
get
{
return Label_Option.Text;
}
set
{
Label_Option.Text = value;
}
}
As a result, if I select English in Form1.s then open up Printer.cs, the label displays English and translates accordingly.
You have to do it same way as for any other control. Imagine you have created your TextBox and now want all your textboxes in the project on each form to do something.
Obviously, you have to get a list of such controls somehow. One approach is to use Application.Forms to iterate through everything. Other is to register your control (add to a list) every time when it's created or shown or what_you_need and de-register (remove from a list) otherwise.

Implement a c# windows forms Autocomplete textbox with multiple suggested columns

I am attempting to implement a Windows Forms control in C# that resembles a textbox. When the user types 3 or more characters, a search will be performed against a datasource. There will be multiple fields returned (see the class structure below as one possible definition).
public class MyStructure
{
public int Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 {get; set; }
}
My requirements are to display an autocomplete list containing multiple columns (Note: this can be a string that contains padded fields from the list that are concatenated together). When the user either types all characters, hits the down arrow to select an item, or hits the enter key the value in the textbox will take the ValueMember of the list (where the DisplayMember of the list would be the whole data source). Every keystroke that the user enters that is not an up or down arrow or the enter key will perform another search and refresh the list.
I have seen how to implement a textbox with a single column in an auto-suggest, but cannot find a relatively "simple" example of how to do this for multiple columns. Should the control be a textbox or a combobox that is somehow styled to resemble a textbox (if this is possible) or a user control?
Should the event to monitor keystrokes be the TextEntered or the KeyPress event? Can I reset the AutoCompleteStringCollection without having the contents entered affected (I keep losing my input or my place in the input in any attempts)?
Can anyone provide examples of how to do this in framework 4.0 or above or point me to an example?
EDIT 1:
After much searching, I have found that essentially I need to implement a ContextMenuStrip on the TextBox (anything else and other controls below the user control will be overlapped). My problem is that I cannot determine how to handle the Key press events such as Tab and Enter. In addition, I need to handle if the user continues typing (in this event, I want to switch focus back to the textbox and add the key). Below is my code:
private void textBox1_TextChanged(object sender, EventArgs e)
{
ContextMenuStrip menuStrip;
string szMenuItem = string.Empty;
// This would actually be a call to a web service
List<MStarDeal> deals = DealInfo.Where(i => i.Value1.StartsWith(textBox1.Text.ToUpper()) || i.Value2.StartsWith(textBox1.Text.ToUpper()) || i.Value3.StartsWith(textBox1.Text.ToUpper()))
.Select(i => i).ToList();
if (textBox1.Text.Length >= 3 && !bSelected)
{
menuStrip = new System.Windows.Forms.ContextMenuStrip();
foreach (MStarDeal item in deals)
{
szMenuItem = item.Value1.PadRight(15) + item.Value2.PadRight(20) + item.Value3.PadRight(80);
ToolStripItem tsItem = new ToolStripMenuItem();
tsItem.Text = szMenuItem;
tsItem.Name = item.Value1;
tsItem.MouseUp += tsItem_MouseUp;
menuStrip.Items.Add(tsItem);
}
textBox1.ContextMenuStrip = menuStrip;
textBox1.ContextMenuStrip.Show(textBox1, new Point(0, 20));
}
else if (bSelected)
{
bSelected = false;
}
}
void tsItem_MouseUp(object sender, EventArgs e)
{
bSelected = true;
textBox1.Text = ((ToolStripMenuItem)sender).Name;
}
Thanks,
Lee
I think I understand your question. How about using the TextChanged() event instead of KeyPress? As far as the columns, a flowLayoutPanel will render columns if you set it up to flow in the right direction and make its size appropriate to the width of the two columns combined.

How to get the devexpress lookupedit display text from the corresponding edit value

Hai all,
I want to get lookupedit display text when am giving correspond edit value.
example:
if am giving
LookupEdit1.Editvalue="3";
then it should show display text of Editvalue="3"
please help
//code
cmbChemical.Properties.DataSource = _lab.selectChemicals();
cmbChemical.Properties.DisplayMember = "labitem_Name";
cmbChemical.Properties.ValueMember = "labItem_ID";
cmbChemical.Properties.BestFitMode = BestFitMode.BestFit;
cmbChemical.Properties.SearchMode = SearchMode.AutoComplete;
cmbChemical.Properties.Columns.Add(new LookUpColumnInfo("labitem_Name", 100, "Chemicals"));
cmbChemical.Properties.AutoSearchColumnIndex = 1;
You can't, at least not in the way you're trying. The LookUpEdit, as the name implies, looks up its values in a DataSource, eg. a collection of objects. Therefore, to display the value 3 you need to have a list of objects that contains this value and set it as a DataSource for the control.
List<string> values = new List<string>();
values.Add("3");
lookUpEdit.Properties.DataSource = values;
lookUpEdit.EditValue = "3";
Maybe if you specify what are you trying to do, we can help you achieve that.
I think you don't have to specify display member or value member to get your needed behaviour. Following code give me a form with the lookupedit correctly showing "4", and i can choose other values from the list too.
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors;
public class Form1 : Form
{
public Form1()
{
var lookUpEdit1 = new LookUpEdit();
Controls.Add(lookUpEdit1);
var source = new List<string>();
for (var i = 0; i < 10;i++ )
source.Add(i.ToString());
lookUpEdit1.Properties.DataSource = source;
lookUpEdit1.EditValue = "4";
}
}
Maybe you get wrong results because you set display member and value member of the control.
This code worked for me.
private void lookUpEdit1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
MessageBox.Show((e.OriginalSource as SLTextBox).Text);
}
}

Categories

Resources