combobox item selected To be fixed - c#

I had a databound combobox in my windows form I populate it by a function deptload() IN FORM LOAD
public void DeptcomboLoad()
{
DataTable dt = depttrans.getDeptName();
Cmb_Department.DataSource = dt;
Cmb_Department.DisplayMember = "DepartmentName"; //CHAR
Cmb_Department.ValueMember = "DepartmentPK"; //INT
}
Now when an employee of a department (say accounts DepartmentName="Accounts " , DepartmentPK=23 ) login I want the ComboBox text to be selected as "acounts "
and when I go to get the selected value of the ComboBox I should get 23
I tried
Cmb_Department.selectedtext="Accounts"
Cmb_Department.Text="Accounts"
but its not giving the selected value
Can anyone give a suggestion

Instead of trying to put a value INTO the combobox, try to GET the SelectedItem like this:
string txt= Cmb_Department.SelectedItem.Text
or just:
string txt= Cmb_Department.SelectedText

To change selected value of the combobox you can use
SelectedItem property or SelectedIndex.
Index must be exact number in your data sourse, and Item must be exact object from datasource

You can get it to select the right item by issuing something like this:
Cmb_Department.SelectedValue = 23;
Where 23 comes from some other variable, maybe on another object, maybe from a local variable, whatever works in your case.
Now, to get the selected value you can use this statement:
var val = Cmb_Department.SelectedValue;
To get the selected text (which would be the text associated with the value):
var text = ((DataRow)Cmb_Department.SelectedItem)["DepartmentName"];
The reason I'm prescribing the aforementioned is because the SelectedText property is volatile, and the Text property doesn't always work based on how the DropDownStyle is set.
However, some would probably argue to get the same as the aforementioned you could issue this statement:
var text = Cmb_Department.Text;

Related

Right way to set selected text of combobox in winforms?

I have a form that takes in an object in it's constructor and populates controls on the form from properties in that object. I am having an issue where I can't set a ComboBox's SelectedText property, or at least it isn't working how I expect it to.
public Form(ValueHoldingObject obj)
{
// yeah I know this is not a very clean way to populate the combobox, the issue
// isn't limited to the combobox so I don't think this is relevant
List<int> items = Repo.GetAllItems().Reverse();
foreach (int id in checkInPrizeIds.Take(100))
// Insert at beginning to put more recently used items at the top
combobox.Items.Insert(0, id);
combobox.DropDownHeight = 200;
combobox.SelectedText = obj.StringProperty;
}
When I am testing this form the text of the combobox isn't being populated. If I add a breakpoint on the line where I assign the text it DOES get assigned, so some event is firing (multiple focus change events probably) and making it work the way I want. Obviously I can't use a breakpoint as a fix in production code. Am I assigning this value incorrectly? Should I be using a different method to populate the values?
Further testing has reviled that it isn't just the combobox, all of my controls are only being populated correctly if I have the breakpoint.
In the constructor, you need to set the selected item, for example:
foreach ( var item in combobox.Items )
if ( (string)item == obj.StringProperty )
combobox.SelectedItem = item;
Or:
foreach ( var item in combobox.Items )
if ( (int)item == Convert.ToInt32(obj.StringProperty) )
combobox.SelectedItem = item;
It's confusing but despite its name, the property SelectedText is not really the selected item... because combo box items are objects and not strings: texts shown are a representation of the item objects using ToString().
Therefore setting the selected text will not guarantee to select an item and we can prefer setting the SelectedItem.
In addition to these considerations, you set the selected text property in the constructor after populating the combo box and that can cause problems because it is before the form and the control are drawn or something like that... that is to say perhaps before the ToString() methods are called on items to prepare the visual cache, so setting the selected text can't get a match with the list.
Setting the selected text selects an existing item if done in the form load or shown events.
private void Form_Load(object sender, EventArgs e)
{
combobox.SelectedText = obj.StringProperty;
}
ComboBox.SelectedText doesn't give me the SelectedText
ComboBox.SelectedText Property

How to get text from selected line in ListBox (c#)?

I want to get data from selected line in List Box. I use command:
string selected = ListBox1.SelectedItems[0].ToString();
But the result is:
ListVievItem: {here is correct value}
What should i do with this: "ListVievItem: {}"
string urItemText = ListBox1.SelectedItem.Text;
http://msdn.microsoft.com/fr-fr/library/system.windows.forms.listbox_properties(v=vs.80).aspx
EDIT As suggested by John Willemse, ListBox can't have ListViewItems so it seems like this question relates to ListView rather than to a ListBox so the code in the answer is changed accordingly.
When you call it like this listView1.SelectedItems[0].ToString(); you are actually calling the ToString() method of the ListViewItem object which gives the unwanted result (first prints the class name and then the value). Each ListViewItem object has Text property from which you can get its text.
string selected = listView1.SelectedItems[0].Text;
Try something like this:
string selected = ListBox1.SelectedItems[0].Text;
Did you Try just: ListBox1.SelectedItem.Value

ComboBox.SelectedText doesn't give me the SelectedText

I am building a String and the code looks like
String status = "The status of my combobox is " + comboBoxTest.SelectedText
I am using WinForm in VS2010
The result looks like
"The status of my combobox is "
I think you want to use
String status = "The status of my combobox is " + comboBoxTest.Text
SelectedText property from MSDN
Gets or sets the text that is selected in the editable portion of a
ComboBox.
while Text property from MSDN
Gets or sets the text associated with this control.
From the documentation:
You can use the SelectedText property to retrieve or change the currently selected text in a ComboBox control. However, you should be aware that the selection can change automatically because of user interaction. For example, if you retrieve the SelectedText value in a button Click event handler, the value will be an empty string. This is because the selection is automatically cleared when the input focus moves from the combo box to the button.
When the combo box loses focus, the selection point moves to the beginning of the text and any selected text becomes unselected. In this case, getting the SelectedText property retrieves an empty string, and setting the SelectedText property adds the specified value to the beginning of the text.
I face this problem 5 minutes before.
I think that a solution (with visual studio 2005) is:
myString = comboBoxTest.GetItemText(comboBoxTest.SelectedItem);
Forgive me if I am wrong.
I think you dont need SelectedText but you may need
String status = "The status of my combobox is " + comboBoxTest.Text;
To get selected item, you have to use SELECTEDITEM property of comboBox. And since this is an Object, if you wanna assign it to a string, you have to convert it to string, by using ToString() method:
string myItem = comboBox1.SelectedItem.ToString(); //this does the trick
Try this:
String status = "The status of my combobox is " + comboBoxTest.text;
Here's how I would approach the problem, assuming you want to change the text of say, a label
private void comboBoxtest_SelectedIndexChanged(object sender, EventArgs e)
{
var combotext = comboBoxtest.Text;
var status = "The status of my combo box is" + combotext;
label1.Text = status;
}
All of the previous answers explain what the OP 'should' do. I am explaining what the .SelectedText property is.
The .SelectedText property is not the text in the combobox. It is the text that is highlighted. It is the same as .SelectedText property for a textbox.
The following picture shows that the .SelectedText property would be equal to "ort".
If you bind your Combobox to something like KeyValuePair, with properties in the constructor like so...:
DataSource = dataSource,
DisplayMember = "Value",
ValueMember = "Key"
so dataSource is of type KeyValuePair...
You end up with having to do this...
string v = ((KeyValuePair)((ComboBox)c).SelectedItem).Value;
(I had a Dynamic form - where c was of type Control - so had to cast it to ComboBox)
If you just want to know the text in the ComboBox with the editable text box (or the ComboBoxStyle.DropDown style) you can use this:
string str = comboBox.SelectedItem != null ?
comboBox.GetItemText(comboBox.SelectedItem) : comboBox.Text;
or try this code
String status = "The status of my combobox is " + comboBoxTest.SelectedItem.ToString();

Set SelectedValue in DataGridViewComboBoxColumn or DataGridViewComboBoxCell

I would like to set a value to the ComboBox in the DataGridView. I already have changed the comboBoxItems, I just want to select one of them. Thank you in advance!!!
I already solved my problem... I'm gonna post the way I did and hoppefully someone will find this answer too.
dgrDetalle.DataSource = dataTable("select * from yourTable");
DataTable dtCombo = dataTableCombo("select COL_ID DETOC_COL_FK,COL_DESCRIPCION from yourTable2");
string[] strColumns = new string[] { "COL_DESCRIPCION" };
MultiColumnDictionary map = new MultiColumnDictionary(dtCombo, "DETOC_COL_FK", strColumns, 0);
dgrDetalle.Cols["DETOC_COL_FK"].DataMap = map;
As you can see the class that save my life is MultiColumnDictionary.
Note: The combobox items must be loaded in a different DatatTable than the DataTable that is gonna load directly in the grid.
As far as I know, the Comboboxes only actually exist as controls when they are being edited, and therefore don't have a selected item property.
You can simply set the Value property of the cell to the item you want selected, or alternitively, you can set a default value by setting the property:
DataGridViewColumn.DefaultCellStyle.NullValue.

How to get value from combobox in c#?

I can't get value from ComboBox in WinForms using C#.
I have a ComboBox populated with a list of values and I have set ValueMember and DisplayMember.
Now, I have to find the value of the selected ComboBox item and select the matched item in UI.
Here is what I mean:-
I loaded the ComboBox like this :-
var list = (from l in db.Loc
orderby l.LName ascending
select l).ToList();
list.Insert(0, new Loc { ID = "-1", Name = "--Select--" });
cmb1.BindingContext = new BindingContext();
cmb1.DataSource = list;
cmb1.DisplayMember = "Name";
cmb1.ValueMember = "ID";
Now on an event, I am trying to match value (ID) and select the item. It's easy if I match Text property:
cmb1.Text = data.Name;
But How to match the value?
Something like this:-
cmb1.Value = data.ID;
If you only know the ID of the item you can also use:
cmb1.SelectedValue = data.ID;
This should work:
cmb1.SelectedValue = data.ID;
Why would you like to assign you "matched" value to the ComboBox Value property?
As soon as you have correctly set DisplayMember and ValueMember and you DataSource implements both as properties the values will be autoamatically "matched", e.g. you can read the Value property in you event handler to get this "matched" value.
data must be in the list binded to the combobox, then:
cmb1.SelectedItem = data
or, if it's not (you retrieved another instance from somewhere):
cmb1.SelectedValue = data.ID
First of all: cmb1.Text = text; changes the text of the ComboBox to the specified value. It doesn't select the item with the text that matchs the specified value.
Use cmb1.SelectedValue = value; to select the item with the speciefied value.
You can get the index using Combo1.SelectedIndex property. You can get the item using either Combo1.SelectedItem or Combo1.Items[Combo1.SelectedIndex]

Categories

Resources