In my project there is an UI which contains a combobox and the combobox will list some communication protocol, such as TCP/IP, FTP and so on
I want to use an enum to present the communication protocols, maybe like this:
public enum CommuProtocol
{
TCPIP = 0,
FTP,
MPI,
Other
}
so, how to bind the enum value to the text in combobox. For example, from the text selected in combobox I can easily know the corresponding enum value and vice versa. And I hope that will be easy to be extended in the future.
The text maybe not the same with the enum value, etc, TCP/IP vs TCPIP...
Thanks!
Well, either you make a function which translates the values into strings or you ToString the value:
CommuProtocol prot = CommuProtocol.FTP;
string name = prot.ToString();
You can use the name of the enum member to get a proper value with the parse member of Enum:
CommuProtocol prot = System.Enum.Parse(CommuProtocol, "FTP");
However, since the names of the members might not be suitable for display it's possible that you'll end up making a method that translates the names anyway.
You should go with Enum.GetValues() method. Here is an example: How do you bind an Enum to a DropDownList control in ASP.NET?
This gets asked a lot. See the answers here.
Related
I'm trying to display a list of all Deliveries with the status Dispatched. However, its only returning the number value of the status as opposed to the actual string value. I think this is because I have used Enum to store my status values?
I wish to display the word Dispatched instead of the number value that it represents in the Enum.
I'm developing in ASP.Net MVC and I'm using the query builder in VS2013.
I'm not sure how to approach this, can anyone please suggest an easy to understand solution using SQL.
Let me know if any additional code is required, and thank you in advance!
Here's the Query I want but it doesn't work:
SELECT Delivery.[Status],
COUNT(Delivery.DeliveryID) AS Dispatched_Status
FROM Delivery
WHERE Delivery.[Status] = 'Dispatched'
GROUP BY Delivery.[Status];
Here's the Query that does work but returns a number value. I tried it this way because Enum stores the string value as a number:
SELECT Delivery.[Status],
COUNT(Delivery.DeliveryID) AS Dispatched_Status
FROM Delivery
WHERE Delivery.[Status] = '1'
GROUP BY Delivery.[Status];
P.S I'm aware that status is a reserved word - will be following the correct naming conventions in future.
Delivery Table Definion
It sounds like you just need to add a lookup table in you DB. Something like
CREATE TABLE [dbo].[StatusLookup](
[StatusID] [int] NOT NULL,
[StatusName] [varchar](64) NOT NULL,
[StatusDescription] [varchar](max),
)
INSERT INTO [dbo].[StatusLookup]([StatusID],[StatusName],[StatusDescription]
VALUES(1, 'Dispatched', 'A dispatched record')
...
Note you'll have to manually do this and make sure to populate it with values that match up with your enum.
Then your query would be
SELECT StatusLookup.[StatusName],
COUNT(Delivery.DeliveryID) AS Dispatched_Status
FROM Delivery
JOIN StatusLookup ON Delivery.Status = StatusLookup.StatusID
WHERE StatusLookup.[StatusName] = 'Dispatched'
GROUP BY StatusLookup.[StatusName];
Enums are stored as integers by default.
You can add a separate varchar or nvarchar field to your database table to hold the description of the enum, and populate it using something like the below:
string selectedEnumDescription = Enum.GetName(typeof(DeliveryStatusEnum), Delivery.Status)
The exact implementation depends on how you are saving your records, and what the actual properties and enum names are.
You can then just select the description column in your SQL query.
Either that or you could store the actual enum values and descriptions within a separate table and do a join.
You can store enum in database as a number, usually a small number - the exact type depends on your database. When you read it - you convert a number to enum and work in your code with the enum. When you need to display it, you can call a ToString() method on that enum, for example
public enum Foo
{
A,
B
}
public class Program
{
public static void Main()
{
Console.WriteLine(Foo.A.ToString()); // Prints A
}
}
See it working
You can also use description attribute and print that, see examples here and here
I have a ComboBox and a TextBox on a WPF form. My code behind is in C#. The ComboBox contains strings that correspond to the type of email address the user is entering into the TextBox.
I want the strings to correspond to 8 character keys that will be serialized into Json with the user entered email address as the value.
The only thing I can think of is something like
if this.ComboBox.SelectedItem == "Some String"
JsonObject thingToSerialize = new JsonObject(){key = 'smestrng', value = TextBox.Text}
I really want to bind a List<string> to the ComboBox items and have those strings associated with the 8 character keys. Something where I could write a few lines that searches the list, finds the string, and then gets the corresponding 8 character key.
I hope I'm not over-complicating this. I could hack something together using a bunch of if statements, but I am sure I will hate myself in 8 months when I realize I have to scale this up and rewrite it completely. I'm not sure if there are going to be three or four keys or 75 keys.
When writing WPF, it's always best to structure your data correctly. By that, I mean that if you want to have an e-mail address linked with a key of some sort, then create a simple class that has two properties; EmailAddress and Key. Of course, you might also want to add more properties, such as Name, etc.
Then you can data bind a collection of these class instances to your ComboBox.ItemsSource property and set the DisplayMemberPath property to display the EmailAddress property value, while still containing the other values too. Finally, add a property of the type of your class named SelectedItem and data bind this to the ComboBox.SelectedItem property:
<ComboBox ItemsSource="{Binding YourCollection}" DisplayMemberPath="EmailAddress"
SelectedItem="{Binding SelectedItem}" />
Then you could do something like this:
JsonObject thingToSerialize = new JsonObject() { key = SelectedItem.Key, value =
SelectedItem.EmailAddress };
On form load (edit action) I want to combobox be selected with appropriate value. These value is of type LangEnum.
I tried with comboBoxLanguage.SelectedValue = book.Language; but combo is always populated with default value (first from enum list).
update:
book.Language is declared as
public enum EnumLang { English = 1, German = 2, Other = 3 };
I tried both with
comboBoxLang.SelectedItem = (Book.EnumLang)book.Language;
and with
comboBoxLang.SelectedItem = book.Language;
and nothing works (default first value (English) is always set) and worth to mention is that on debug mode book.Language is set To German or Other but English is selected on combobox.
That looks right to me!
I am doing the same thing, are you sure that book.Language string is an EXACT match to one of the items in the list?
And is the list populated BEFORE you are trying to SelectedValue?
Better try:
comboBoxLanguage.SelectedItem = book.Language;
// or even
comboBoxLanguage.Text = book.Language.ToString(); //should work
You might want to set the ValueMember property to get or set the SelectedValue.
Works fine for me using SelectedItem:
comboBoxLanguage.SelectedItem = book.Language;
You didn't tell what kind of variable book is: is it of type LangEnum? Or is it a class with a Language property? (in this last case: what is the type of the Language property?)
If book is of type LangEnum you can use the SelectedItem property as others have said. (Check this SO question if you need more informations of the differences between the two combobox properties)
Otherwise you'll probably need a cast:
comboBoxLanguage.SelectedItem = (LangEnum)book.Language;
Moreover, if you are populating your combobox inside a WinForm event, you should also care about the order in which they are fired. Take a look at this SO question form more infos.
So I have 70 "nodes" which are all textboxes in WPF and I'm trying to change the value in the textbox from a function call.
I have a function called:
private void changeNode(int row, int column, int cost)
{
int nodeNumber= row * 10 + column;
call node"nodeNumber".Text = Convert.String(cost);
//example node0.Text = Convert.String(cost);
}
I determine what node I want to change then call nodeX.Text to change it however I want X to be a variable that I can rather than having to create 70 cases where I call the appropriate textbox.
I saw a couple of ways of doing this with reflection however it seemed to only work if the function had no parameters and also was within the function not a textbox in XAML.
Let me know if there is a simple way to convert say a string "node37" to call node37.Text = cost or something like that.
Sounds like your approach is wrong. Why do you have a set of strings which represent the names of the textboxes? You should instead have in-memory references to TextBox objects. If you have more than one, and you don't know how many there will be, then use an array of TextBox objects instead. You can index into the array with the number that represents the textbox you're looking to interact with.
Avoid the use of reflection, it is completely unnecessary here.
I assume you have put names for all your textboxes (you can do this dynamically if you haven't). Then you can use the answers for this question to find the appropriate control by name.
Are all your textboxes children of the same canvas or other control? Loop through the children and add the controls to a dictionary. Parse the name to get the number and use that as the key.
It is always better to use List when you are dealing with Data. Create an ObservableCollection with the DataObjects which you want to load, and now deal with the Data object rather than actual Controls.
In WPF, if you follow the rules, you should not point to the actual object. Check the sample application here :
http://www.abhisheksur.com/2010/08/woring-with-icollectionviewsource-in.html
I think you will get the approach.
I have a dll that has a class called Series. This class has a field which is an enumeration of DataTypes. I am binding the datagrid to a list of objects of this class, and I am able to display the enumeration values in a combobox fashion
However, the values' names don't make a lot of sense. For example, I want to display 'prc' as 'price' and still represent the correct object value.
this is what I currently do
this.seriesDataTypeColumn.Items.AddRange(new object[] {
MuDBLayer.DataType.mv,
MuDBLayer.DataType.vol,
MuDBLayer.DataType.num,
MuDBLayer.DataType.prc,
MuDBLayer.DataType.Composite});
mv, vol, num and prc are displayed in the datagridcomboboxes.
I wanna display
money value, volume, number, and price instead
any ideas?
Description attribute cannot be localized. Do take a look at this reply.
Can my enums have friendly names?
Take a look at https://msmvps.com/blogs/deborahk/archive/2009/07/10/enum-binding-to-the-description-attribute.aspx or http://blogs.freshlogicstudios.com/Posts/View.aspx?Id=388f7d39-0b90-43bc-b03a-c1f605dfb499. You can add a Description attribute to your enums to display a more friendly value.
You might also find some more information in this related question How to bind a custom Enum description to a DataGrid.