ListItem's value gets replaced by the text on DataBind - c#

I'm at a bit of a loss on this one and haven't been able to find anything helpful in my searches so I'm hopeful someone can help me out here.
I've got a RadioButtonList that I'm adding a List of dynamically created ListItems, where I set both the text and the value for each item. On DataBind for the RadioButtonList the Value for the ListItem gets replaced by the Text, which just doesn't seem to make sense to me.
I can see on the client side when I look in Firebug that the label and the value on the input are the same, and the value is nowhere to be seen.
Has anyone else had any experiences like this, or does anyone know where I might be going wrong?
var rbList = new List<ListItem>();
var radioButtonList = new RadioButtonList();
foreach(var object in objects) {
var li = new ListItem {Text = object.Name, Value = object.Guid};
rbList.Add(li);
}
radioButtonList.DataSource = rbList;
radioButtonList.DataBind();

Should you be using Databinding here? Can you not just add your ListItems to the radio button list directly?
I would imagine that the Databinding is getting confused about how to bind your list so is just using ToString on each of your elements which seems to just return the Text Property. This is then being used as both the Text and the Value.
You probably just want to create your items and add them straight to your Radio button control as follows:
var radioButtonList = new RadioButtonList();
foreach(var object in objects) {
var li = new ListItem {Text = object.Name, Value = object.Guid};
radioButtonList.Items.Add(li);
}

For those, whose are still struggling - do not forget to fill DataValueField, if control has it. Simply provide string name of your value property and you will be fine.
As Chris mentioned - Databinding was in fact confused and therefore DataValueField exists. My problem was with basic asp:DropDownList.

Related

Find string in combobox and show it

I thought this would be easy, but now I don´t know how to do it exactly.
In a WPF-application, i go from one window to another by clicking a contextmenu-item. My constructor for the new window looks like this:
public Bearbeitung(int loginid, String art)
On the Window, there´s a checkbox filled with a list. What I want is, that the default selected item in my checkbox is art.
Ok, I checked if the String is in the list, but now I don´t know how to set it to the selecteditem in the combobox.
How can I manage this?
EDIT: I already tried
combobox.SelectedItem = art;
...that doesn´t work!
EDIT2:
Here´s the code:
List<String> feld = new List<string>();
feld = agrep.GetFelder(loginid);
foreach (String s in feld)
{
cbFeld.Items.Add(s);
}
if (cbFeld.Items.Contains(art))
{
MessageBox.Show("It contains it");
cbFeld.SelectedItem = art;
}
The messagebox isn´t shown!
If the list items are just strings, you can simply do
myComboBox.SelectedItem = art;
If your ComboBox only contains strings you should be able to just set the SelectedItem
cb.SelectedItem = art;
If it does not only contain strings you might want to change that, e.g.
cb.ItemsSource = new string[] { "Item 1", "Item 2" };
If you have complex objects you will want to set the SelectedValue and SelectedValuePath instead.
try
cbFeld.Text = art;
this should work.
Ok, I just solve it. The problem was, that when I give the string to the other window, a blank has been added. Thanks to you all!

What is the correct way to change selection of a DropDownList?

I am having a problem to change a selected item in a drop-down.
The way I use is (a property in the code behind which sets the new selection):
public char Candy
{
set
{
var newSelection = ddlCandy.Items.FindByValue(value.ToString());
ddlCandy.ClearSelection();
newSelection.Selected = true;
}
}
Is this a recommended and proper way?
recommended approach is to simply assign the SelectedValue property with the Value you have and the DropDownList control will find and select the proper item for you, if any.
Safe way is fist Find the given item from DropDownList and set it as SelectedValue
ListItem oListItem = DropDownList1.Items.FindByValue("yourValue");
if(oListItem != null)
{
DropDownList1.SelectedValue = oListItem.Value;
}
if you directly assign SelectedValue it may through an exception if it is not exist in the list like bellow.
'DropDownList' has a SelectedValue which is invalid because it does
not exist in the list of items.
I usually prefer to use SelectedValue:
DropDownList1.SelectedValue = "Foo";

How to set selected value from Combobox?

I use combobox in c# windows form. I bound the item list as below:
var employmentStatus = new BindingList<KeyValuePair<string, string>>();
employmentStatus.Add(new KeyValuePair<string, string>("0", "[Select Status]"));
employmentStatus.Add(new KeyValuePair<string, string>("1", "Contract"));
employmentStatus.Add(new KeyValuePair<string, string>("2", "Part Time"));
employmentStatus.Add(new KeyValuePair<string, string>("3", "Permanent"));
employmentStatus.Add(new KeyValuePair<string, string>("4", "Probation"));
employmentStatus.Add(new KeyValuePair<string, string>("5", "Other"));
cmbEmployeeStatus.DataSource = employmentStatus;
cmbEmployeeStatus.ValueMember = "Key";
cmbEmployeeStatus.DisplayMember = "Value";
cmbEmployeeStatus.SelectedIndex = 0;
I save the selected value in database eg.1 or 2. Now I want to set selected value from database item like:
cmbEmployeeStatus.SelectedValue =employee.employmentstatus;
But combobox not selected with value. How can I do that?
Try this one.
cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);
In order to do the database style ComboBoxes manually trying to setup a relationship between a number (internal) and some text (visible), I've found you have to:
Store you items in a list (You are close - except the string,string - need int,string)
DataSource property to the list (You are good)
DataMember,DataValue (You are good)
Load default value (You are good)
Put in value from database (Your question)
Get value to put back in database (Your next question)
First things first. Change your KeyValuePair to so it looks like:
(0,"Select")
(1,"Option 1")
Now, when you run your sql "Select empstatus from employees where blah" and get back an integer, you need to set the combobox without wasting a bunch of time.
Simply: *** SelectedVALUE - not Item ****
cmbEmployeeStatus.SelectedValue = 3; //or
cmbEmployeeStatus.SelectedValue = intResultFromQuery;
This will work whether you have manually loaded the combobox with code values, as you did, or if you load the comboBox from a query.
If your foreign keys are integers, (which for what I do, they all are), life is easy. After the user makes the change to the comboBox, the value you will store in the database is SelectedValue. (Cast to int as needed.)
Here is my code to set the ComboBox to the value from the database:
if (t is DBInt) //Typical for ComboBox stuff
{
cb.SelectedValue = ((DBInt)t).value;
}
And to retrieve:
((DBInt)t).value = (int) cb.SelectedValue;
DBInt is a wrapper for an Integer, but this is part of my ORM that gives me manual control over databinding, and reduces code errors.
Why did I answer this so late? I was struggling with this also, as there seems to be no good info on the web about how to do this. I figured it out, and thought I'd be nice and post it for someone else to see.
In windows Appliation
we use like this
DDLChangeImpact.SelectedIndex = DDLChangeImpact.FindStringExact(ds.Tables[0].Rows[0]["tmchgimp"].ToString());
DDLRequestType.SelectedIndex = DDLRequestType.FindStringExact(ds.Tables[0].Rows[0]["rmtype"].ToString());
Use the SelectedIndex property for the respective employee status in the combo box.
Below will work in your case.
cmbEmployeeStatus.SelectedItem =employee.employmentstatus;
When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index. If the object does not exist in the list, the SelectedIndex property is left at its current value.
EDIT
I think setting the Selected Item as below is incorrect in your case.
cmbEmployeeStatus.SelectedItem =**employee.employmentstatus**;
Like below
var toBeSet = new KeyValuePair<string, string>("1", "Contract");
cmbEmployeeStatus.SelectedItem = toBeSet;
You should assign the correct name value pair.
cmbEmployeeStatus.Text = "text"
I suspect something is not right when you are saving to the db. Do i understand your steps as:
populate and bind
user selects and item, hit and save.. then you save in the db
now if you select another item it won't select?
got more code, especially when saving? where in your code are initializing and populating the bindinglist
A possible solution:
cmbEmployeeStatus.SelectedValue = cmbEmployeeStatus.Items.FindByText("text").Value;
try this
combobox.SelectedIndex = BindingSource.Item(9) where "9 = colum name 9 from table"
To set value in the ComboBox
cmbEmployeeStatus.Text="Something";
Try this:
KeyValuePair<string, string> pair = (KeyValuePair<string,string>)this.ComboBox.SelectedItem;

C# Combobox and TabControl woes

enter code hereI have a TabControl on a Form and in the TabPages there are ComboBoxes.
When the form OnLoad, I populate the ListItems in the ComboBoxes and the attempt to set default values to string.Empty.
However, the ComboBox.SelectedText = string.Empty only works for the first TabPage. The other ComboBoxes ignore the command and take the default value as the first item in the list. Why is this so? How can I overcome it?
The ComboBoxes are all set up by this function
public static void PrepareComboBox(ComboBox combobox, FieldValueList list)
{
combobox.DropDownStyle = ComboBoxStyle.DropDown;
combobox.AutoCompleteSource = AutoCompleteSource.ListItems;
combobox.AutoCompleteMode = AutoCompleteMode.Suggest;
combobox.DataSource = list.DataSource;
combobox.DisplayMember = list.DisplayMember;
combobox.ValueMember = list.ValueMember;
combobox.Text = string.Empty;
combobox.SelectedText = string.Empty;
}
I found that the reason could be that the ComboBox is not "active" until they are at least shown once. You can see that when the TabPage is selected for the first time, it takes a slightly longer time to load. I suppose it is creating/initialising the child controls for the first time.
For that, I call tabControl.SelectTab() before modifying the value properties and it worked... although it feels like a hack.
This is due to databinding. Not much you can do about it, except prefix the datasource with an empty/dummy entry.

How do you bind a data field value to a combobox index?

This may have been already asked but I can't seem to find this specific question, so here goes...
I have a form in C# where every textbox is bound to a field in a row. Rows can be cycled through by some buttons on the bottom but all the data displayed at a time in the from is from one row. Any changes that are made get updated back to the database when the user clicks "update"
One field (class) is an enumeration (0,1,2) where only the value is stored in the database, but doesn't mean much to the user. I was asked to make this more obvious to the user, so I decided to go with a dropdown style combo box. Since the database didn't have any reference to what the values meant, I decided to use the DataBindings instead of DataSource so I could just use the index as the data bind, but it seems that SelectedItem or Value are not the way to do this.
Here is my goal:
1 exists in database, so "B" is selected in combo box.
User selects "C" and updates the database, 2 is now stored in the database.
Any thoughts on what I need to get this working?
I assume you have a BindingSource on your form to bind to the data. You can bind the SelectedIndex property of the ComboBox as follows:
comboBox.DataBindings.Add("SelectedIndex", bindingSource, "PropertyInTheDataSource");
Actually I was able to bind it to a custom Object. It's a little too much work for such a simple task. But you have complete control on Display/Value pairs. Anyway, I thought I'd share and you decide:
Create a new class (say CustomItem) with 2 fields:
Public int Value{get;set;}
public string Title {get;set;}
Then in you form:
var item1 = new CustomItem() { Title = "A", Value = 10 };
var item2 = new CustomItem() { Title = "B", Value = 20 };
var item3 = new CustomItem() { Title = "C", Value = 30 };
var lst = new List<CustomItem>();
lst.Add(item1);
lst.Add(item2);
lst.Add(item3);
comboBox1.DataSource = lst;
comboBox1.DisplayMember = "Title";
comboBox1.ValueMember = "Value";
Now You have a databound combobox in case you don't have BndingSource in your form.
Just remember to define your class's Title and Value as properties otherwise it wouldn't work.

Categories