Set selected Menustrip item equal to ComboBox value and vice versa - c#

Basically I have a menustrip with 3 items. And another combobox with those exact same three items.
How do I set it so upon clicking an item on one list it sets the other list to the same value.
I hope I explained this clearly. Thanks.

If you want to set the ComboBox SelectedItem based on the MenuItem selection You can follow the below steps:
Step 1: You need to cast the sender object into ToolStripMenuItem in your ToolStripMenuItemClick Event handler.
Step 2: then assign the above casted one into ComboBox.FindString() method as an argument so that it returns the Matching Item index in the Combobox.
Step 3: now assign the returned Index value by the FindString() method to the ComboBox1.SelectedIndex property so that the exact item selected in MenuStrip willbe Selected in Combobox aswell.
Try This:
item1ToolStripMenuItem.Click += new System.EventHandler(ToolStripMenuItem_Click);
item2ToolStripMenuItem.Click += new System.EventHandler(ToolStripMenuItem_Click);
item3ToolStripMenuItem.Click += new System.EventHandler(ToolStripMenuItem_Click);
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
comboBox1.SelectedIndex = comboBox1.FindString(((ToolStripMenuItem)sender).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 reset the item select on ListView winform

I have a small project where I get some values from a txt and put inside of a ListView. I need to get the selected value when I click in some item, the first item that I ever select, works fine, but if I try to select again, I get an exception.
This is what I did..
Json = new StreamReader(openDialog.FileName).ReadToEnd();
var ParsedValue = JsonValue.Parse(Json);
Parsed = JsonConvert.DeserializeObject<List<Model>>(ParsedValue.ToString());
foreach (var item in Parsed)
{
var rows = new string[] { item.car, Convert.ToString(item.age )};
var items = new ListViewItem(rows)
{
Tag = item
};
ListViewCars.Items.Add(items);
}
The List view is Filled.
And to get the Item selected from the list :
private void cartsList_SelectedIndexChanged(object sender, EventArgs e)
{
ItemSelected = (Model)ListViewCars.SelectedItems[0].Tag;
}
I can only get the value that I select first when the program runs.
The exception :
System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index'
Check out the documentation on ListView.SelectedIndexChanged. Specifically, look at the Remarks section, which reads:
The SelectedIndices collection changes whenever the Selected property of a ListViewItem changes. The property change can occur programmatically or when the user selects an item or clears the selection of an item. When the user selects an item without pressing CTRL to perform a multiple selection, the control first clears the previous selection. In this case, this event occurs one time for each item that was previously selected and one time for the newly selected item.
I added the emphasis. This means that when you select the second item, the currently selected item is unselected and SelectedIndexChanged is triggered before the new item is selected. So when you try to get the first selected item with ListViewCars.SelectedItems[0].Tag you get that ArgumentOutOfRangeException because there are no selected items.
You need to add a check to the top of your event handler to make sure that there is at least one selected item before accessing SelectedItems[0].

Binding TextBox Text value to ComboBox.SelectedItem, and list from selected item of a ComboBox to another ComboBox

So I have a class "Worker" and a BindingList which is bound to a ComboBox.
workers = new BindingList<Worker>();
//// .. An "Add" button is somewhere there to add "Worker" objects to the list
//ComboBox Workers List
cbWorkersList.DataSource = workers;
cbWorkersList.DisplayMember = "Name";
I want to bind the "Text" field in a TextBox to the "Name" property of the selected "Worker" object, in the ComboBox.
Now I've done it by using the "cbWorkersList_SelectedIndexChanged" event handler, manually modifying txtWorkerName.Text property:
private void cbWorkersList_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbWorkersList.SelectedItem != null)
{
txtWorkerName.Text = workers[workers.IndexOf((Worker)cbWorkersList.SelectedItem)].Name;
}
}
I tried to bound the TextBox in this way:
InitializeComponent();
txtWorkerName.DataBindings.Add("Text", cbWorkersList, "Text");
But it is only updating the TextBox if I click on other item on the list, if I use arrow keys to change the selection, the TextBox text field is not changing.
Is there a way to truly bind them so that if a ComboBox item is selected, the text field will change accordingly?
While on this topic, I also have other 2 ComboBoxes, and I would like to bind 1 to a list which is inside the others' ComboBox object.
What I want is a solution with the following logic:
cbPositions.Items = ((<Shift>)cbShifts.SelcetedItem).PositionsList
when
cbPositions is a ComboBox which should be populated with "Position" objects.
And cbShifts is a ComboBox which is populated with "Shift" objects, where each "Shift" contains a list of Positions.
How can I bind them so every time I choose an other Shift from the list, the Positions ComboBox will be populated with the Position objects from the Shift.PositionList?
And also, I would like to know if it's possible to bind the "Items" of a ComboBox to a List (my workers list in this example), not with code, but in the designer(Application Settings or DataBindings)?

How can I get a listview item index when clicking on the item?

For example if I click on the first item it will be at index 0.
If I click on item 15 then the index should be 16.
I tried
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
int index = listView1
}
But I'm not sure if this is the right event or I should use the listView1_Click event ?
And the listView1 does not have any property SelectedIndex.
And last thing is I want to get the item text according to the index of the item I clicked on.
Assuming you want the index of the currently selected item you can do it like this :
int index = ListView1.FocusedItem.Index
Use ListView.SelectedIndices property:
List<int> selectedIndices = listView1.SelectedIndices.Cast<int>().ToList();
It returns collection of selected indices (because by default you can select several items in listview if you click on items with Ctrl or Shift key pressed). Also note that when you deselect all items, this collection will be empty and things like listView1.SelectedIndices[0] will throw IndexOutOfRange exception.
But if you will set MultiSelect property to false. Then this collection will always contain zero or one item. You can use Count property of SelectedIndicesCollection to check if item was selected:
if (listView1.SelectedIndices.Count > 0)
{
int selectedIndex = listView1.SelectedIndices[0];
}
You need to use the selected indices list you can also do this be item too.
listView1.SelectedIndices[0]
First you can get listview item object like below
ListViewItem lst=(ListViewItem)listView.SelectedItems[0];
from that object(lst) you can get the text like below
string text=lst.Content.ToString();
According to MSDN, there is still SelectedIndex. In my opinion your event is wrong, but you can still see it by .SelectedIndex. As it was mentioned before.
UPDATE: according to the comment, the link is fixed for the correct case.

Selecting default item from Combobox C#

I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox.
I'm trying something like that:
SelectPrint11.SelectedIndex=2;
but error is:
System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'
Edit:
In mylist are 3 items, Printer1, Printer2, Printer3. All are added in ComboBox Properties -> Items -> Collection
You can set using SelectedIndex
comboBox1.SelectedIndex= 1;
OR
SelectedItem
comboBox1.SelectedItem = "your value"; //
The latter won't throw an exception if the value is not available in the combobox
EDIT
If the value to be selected is not specific then you would be better off with this
comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
Remember that collections in C# are zero-based (in other words, the first item in a collection is at position zero). If you have two items in your list, and you want to select the last item, use SelectedIndex = 1.
private void comboBox_Loaded(object sender, RoutedEventArgs e)
{
Combobox.selectedIndex= your index;
}
OR if you want to display some value after comparing into combobox
foreach (var item in comboBox.Items)
{
if (item.ToString().ToLower().Equals("your item in lower"))
{
comboBox.SelectedValue = item;
}
}
I hope it will help, it works for me.
this is the correct form:
comboBox1.Text = comboBox1.Items[0].ToString();
U r welcome
This means that your selectedindex is out of the range of the array of items in the combobox. The array of items in your combo box is zero-based, so if you have 2 items, it's item 0 and item 1.
first, go to the form load where your comboBox is located,
then try this code
comboBox1.SelectedValue = 0; //shows the 1st item in your collection
ComboBox1.Text = ComboBox1.Items(0).ToString
This code is show you Combobox1 first item in Vb.net

Categories

Resources