populate combobox with enum value - c#

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.

Related

Get values from database to textbox

I have a WinForm that have a DataGridView and a ComboBox, allowing users to select a subject (from the database).
cbxSubject.DataSource = dsSched.Tables["Schedules"];
cbxSubject.DisplayMember = "Subject";
...
The DataGridView looks something like this: http://i45.tinypic.com/18gmmu.png I added the DataGridView since I don't know any other way how to get those values from the database. I used a code, something like this, to get the values:
TextBox1.Text = DataGridView1.Rows[3].Cells[1].Value.ToString();
But then I realized that it won't work anymore if there are more than 2 subjects to choose from, because the code is set to get the value on the 3rd row and the 1st cell. So even when the user changed subject, the output value (w/c are then displayed in a TextBox) will still be the same. Are there any other ways to get those values? Please help, thanks.
You can add a comboxbox this way
DataGridViewComboBoxColumn subjectsCombo = new DataGridViewComboBoxColumn();
subjectsCombo.DataPropertyName = "SubjectID";
subjectsCombo.HeaderText = "Subjects";
subjectsCombo.DataSource = dsSched.Tables["Subjects"];
subjectsCombo.ValueMember = "SubjectID";
subjectsCombo.DisplayMember = "SubjectText";
cbxSubject.Columns.Add(subjectsCombo);
I would suggest that you DONT use constants. Rather that using 3 and 1, you need to write some code to find R and C from what the user selects. It should be event driven and you need to re-set the text box on change. I'm assuming you are using an on-change event, but you haven't actually given us that information yet.
here's some pseudocode to get where im going with this
public DataGridView1_SelectionChanged(object sender, ChangedEventArgs e)
{//this might not be the right event, I'll leave it up to you to do your own homework
int R = //Get the current Selected Row;
int C = //Get the current Selected Cell/column;
TextBox1.Text = dsSched.Tables["Schedules"].Rows[R].Cells[C];
///OR YOU COULD DO SOMETHING LIKE THIS
TextBox1.Text = ((DataGridView)sender).SelectedRows[0].Cells[1].Value;
}
//Please note, this is only pseudocode, I dont like doing peoples homework for them.
This should give you a more generic idea/algorithm that you would need. Keeping in mind that this might not even be the best way to go about doing this, but Its what I would recommend based solely on the information provided to us thus far. btw, what have you tried? and can you give us some larger code examples, there might be a rather more simple mistake being made that you haven't shown us so we cant tell you about it :-)
Considering that you still haven't actually asked the correct question, because we dont know WHY you are trying to do what you have stated you are doing, I can't get any more specific than this. GIGO, you have to ask the right question in order to get the right answer.
I'll try to get some of your doubts out of the way:
I added the DataGridView since I don't know any other way how to get
those values from the database
You already have a DataSet called "dsSched" filled with database values. So, no, you don't need the DataGridView. Just fill whatever you want directly from the DataSet:
string data = dsSched.Tables["Schedules"].Rows[3].Cells[1].Value.ToString();
then I realized that it won't work anymore if there are more than
2 subjects to choose from, because the code is set to get the value on
the 3rd row and the 1st cell.
Well, I'm not sure where you are running that piece of code (TextBox1.Text = Data...), but if you are running it on the SelectedIndexChanged event of the DataGridView, then you should get data from the exact row that the user selected (or something, again, I did not understood what you are trying to do).
One thing that I suspect is that you are under the impression that the code:
TextBox1.Text = DataGridView1.Rows[3].Cells[1].Value.ToString();
...is binding the textbox to the value in the row / cell. That's not how this works - the value is retrieved once when the code is run, and then again whenever the code is run again. So you should make sure the code is run when you have to get this value.
EDIT:
I mean, how do I get the value? Like, the PrimaryKey or something?
That's the question! I'm sorry, I was probably deviating. Just set the [ValueMember][1] to the string that describes the value column of the dataset.
cbxSubject.ValueMember = "Schedule ID";
Than you access it using [SelectedValue][2], like:
int selValue = (int)(cbxSubject.SelectedValue);

Can WPF handle Guids from LINQ to SQL?

I stumbled on a strange problem. In my WPF (.NET 4) window I have a simple combobox (DisplayMemberPath="Name" SelectedValuePath="Id"). When I load the window I set the combobox's ItemSource property to context.Currencies.ToList() using LINQ to SQL. The Currency table in SQL is simply [Id] [uniqueidentifier] NOT NULL PRIMARY KEY, [Name] char NOT NULL. In .NET this translates to Id = System.Guid, Name = System.String.
The problem I'm having is that the call to combobox.ItemsSource = context.Currencies.ToList(); throws a FormatException (Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)).
What I can't understand is why is this error thrown?
If I leave LINQ to SQL out of the picture, define a "test" class - public class Test { public Guid Id; public string Name; }, set the comobox.ItemsSource to a List<Test> which contains some entries, then everything works.
If I do this:
combobox.ItemsSource = context.Currencies.Select(c => new { c.Id.ToString(), c.Name }).ToList()
then everything works.
I tried setting the current thread's Culture and UICulture to "en-US" beforehand as well (just in case it's a culture problem, my default culture is "et-EE"), but that didn't help either.
I looked at the generated LINQ to SQL classes from the designer, but couldn't find any properties to alter which might have helped with this error.
Am I missing something here or is this really a bug in the .NET framework?ยด
PS! The Currency table contains valid entries (valid Guids).
As Thomas pointed out, I had a binding on SelectedValue and it turns out the binding also contained a FallbackValue = 1. After removing the fallback property everything works. The property was scrolled out of view, so indeed it was something I missed.

List<>.Find(delegate) issue

I have a multi-column combobox where the datasource is a List<> in my Select Class
Select selection = new Select();
RadComboBox1.DataSource = selection.GetAcctUtilCo(e.Text, 10).Skip(e.NumberOfItems);
I have a few DataTextFields. My DataValueField is the AcctID.
Once an account is selected, I need the datatextfield values to populate some fields in a gridview.
I am trying to use the .Find() method by AcctID to retreive the data without success:(
int AcctID = Convert.ToInt32(RadComboBox1.SelectedValue); // *
List<Select> mylist = RadComboBox1.DataSource as List<Select>;
mylist.Find(delegate(SelectTop act) { return act.AcctID == acctID; }); // ** exception here
Label lblAcctNo = (Label)grdAccts.HeaderRow.FindControl("lblAcctNo");
lblAcctNo.Text = mylist.AccountNum;
When I debug, I get 'Object reference not set to the instance of an object' on the indicated line.
AcctID is NOT null when I hover over it. However when I hover over mylist, it says null.
I'm new with the .Find method & I'm really not sure if the problem is with that or with using the datasource of the combobox as mylist source.
Can someone please help enlighten me
Your combo-box's data source is not a list. When you use "as" the result is null if you try to cast to an invalid type, instead of throwing an exception like a standard cast. Since you used the Skip function to create your data source you actually have an "IEnumerable<>".
The problem is caused by RadComboBox1.DataSource - it is not persisted between page requests.
In your code that sets RadComboBox1.DataSource, save a copy of the RadComboBox1.DataSource value in the viewstate. eg. ViewState["RadComboBox1"] = RadComboBox1.DataSource;
In the event that runs your above code, restore the RadComboBox1.DataSource by reading the value from the viewstate. eg. RadComboBox1.DataSource = ViewState["RadComboBox1"];
You should hopefully find the values then persist between requests. Good luck!

displaying enumeration values in a DataGridComboBox problem

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.

how to bind enum values to strings

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.

Categories

Resources