Setting the SelectedIndex on ComboBox - c#

I am in a beginning C# class and I am having trouble figuring out why after the following code runs, the selected index is still -1 (i.e. the combobox at load is empty). It should be defaulting to selectedIndex = 1:
public string[,] GetArray()
{
//create array with conversion values
string[,] conversionInfo = { {"Miles","Kilometers", "1.6093"},
{"Kilometers","Miles", ".6214"},
{"Feet","Meters", ".3048"},
{"Meters","Feet","3.2808"},
{"Inches","Centimeters", "2.54"},
{"Centimeters","Inches",".3937"}};
return conversionInfo;
}
private void Form_Load(object sender, EventArgs e)
{
//get array to use
string[,] conversionChoices = GetArray();
//load conversion combo box with values
StringBuilder fillString = new StringBuilder();
for (int i = 0; i < conversionChoices.GetLength(0); i++)
{
for (int j = 0; j < conversionChoices.GetLength(1) - 1; j++)
{
fillString.Append(conversionChoices[i, j]);
if (j == 0)
{
fillString.Append(" to ");
}
}
cboConversion.Items.Add(fillString);
fillString.Clear();
}
//set default selected value for combobox
cboConversion.SelectedIndex = 0;
}
public void cboConversions_SelectedIndexChanged(object sender, EventArgs e)
{
LabelSet(cboConversion.SelectedIndex);
}
public void LabelSet(int selection)
{
//get array to use
string[,] labelChoices = GetArray();
//set labels to coorespond with selection
string from = labelChoices[selection, 0];
string to = labelChoices[selection, 1];
lblFrom.Text = from + ":";
lblTo.Text = to + ":";
}
This is a class assignment so I am not allowed to set anything using the designer, other than to link methods to event. Everything works correctly except for the default for the combobox.

Your code is completely correct, but you have one single fault in your mind. Consider, that you are loading the items into the ComboBox after you have initialized the control. At this point the control have no items, therefore the property "Text" is not setted automatically.
You have to differ between the SelectedIndex, which is the index of the item in the list of items, and the Text, which is the text, shown in the ComboBox. So think about when and how you should set the Text-property of the ComboBox.
Always set the Text-property to the first value of your item-list, after you changed it.
Greetings,

the answer of Mario can be interpreted also as:
put your code after the loading (example: on the shown event), in this way the control is initialized and has items.

Related

WPF Button click not properly comparing variable to array value

new to WPF so not sure if there is some sort of syntax that I am missing or what.
Course choice;
int totalCredits = 0;
int classesRegistered = 0;
string[] registeredCourses = new string[3];
private void button_Click(object sender, RoutedEventArgs e)
{
if (classesRegistered < 3)
{
choice = (Course)(this.comboBox.SelectedItem);
if ((!choice.Equals(registeredCourses[0]))
&& (!choice.Equals(registeredCourses[1]))
&& (!choice.Equals(registeredCourses[2])))
{
registeredCourses[classesRegistered] = choice.ToString();
this.listBox.Items.Add(registeredCourses[classesRegistered]);
classesRegistered = classesRegistered + 1;
}
}
}
So I don't want the choice to be added to the listbox if its already registered to one of the array's values. What is it I'm missing?
Your if statement is comparing a string to a Course object, you may change it to below:
if(!registeredCourses.Any(obj=> obj.Equals(choice.ToString())))

Feeding a override value from OnSelectionChangeCommitted DataGridViewComboBoxEditingControl to column object

So I have this and I know it is wrong:
protected override void OnSelectionChangeCommitted(EventArgs e)
{
if (SelectedIndex == 0)
{
GENIO_Viewer.FullColourPaletteForm dlgColour = new GENIO_Viewer.FullColourPaletteForm();
if(dlgColour.ShowDialog() == DialogResult.OK)
{
bool bFound = false;
for(int i = 1; i < Items.Count; i++)
{
ComboboxColourItem ocbItem = (ComboboxColourItem)Items[i];
if(ocbItem.Index == dlgColour.iSelectedColour)
{
SelectedIndex = i;
bFound = true;
break;
// We can just select this one
}
}
if(!bFound)
{
// Add it
ComboboxColourItem ocbItem = ComboboxColourItem.Create((ushort)dlgColour.iSelectedColour);
Items.Add(ocbItem);
SelectedIndex = Items.Count - 1;
}
}
}
base.OnSelectionChangeCommitted(e);
}
This handler is part of my DataGridViewComboBoxEditingControl. But it is the wrong place to add new Items.
I can't workout how to get access to the owning Column as that is where I need to add the Item, otherwise I get exceptions.
I have looked here: https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcomboboxeditingcontrol(v=vs.110).aspx
But i can't see a property I can use to get the column object.
How do we do this from the editing control?
Further explaination:
The list combo items are added by the "column" object. Thus we have a set of 15 colours to choose from. Now I have added a genric colour tot he top of the list.
So, the user invokes the edit, droplist displays, and they pick item 0. We intercept this with the aforementioned handler. Since they picked item 0, we show a popup dialogue to let them choose a different colour.
When they have chosen, we must now either find it or add it to the the mandatory list of items for the column. Make sense now?
I tried to use the DataGridView Notify object but for some reason it is not showing in the list of available functions.
I don't use a DataSource. I populate like this in the columns constructor:
private void InitialiseComboItems()
{
List<ushort> listColours = new List<ushort>();
listColours.Add(0);
listColours.Add(1);
listColours.Add(2);
listColours.Add(3);
listColours.Add(4);
listColours.Add(5);
listColours.Add(6);
listColours.Add(7);
listColours.Add(8);
listColours.Add(9);
listColours.Add(250);
listColours.Add(251);
listColours.Add(252);
listColours.Add(253);
listColours.Add(254);
listColours.Add(255);
this.Items.Clear();
foreach (ushort iColourIndex in listColours)
this.Items.Add(ComboboxColourItem.Create(iColourIndex));
}
I also have a helper method:
public ComboboxColourItem InsertColour(ushort iColourIndex)
{
ComboboxColourItem ocbItem = ComboboxColourItem.Create(iColourIndex);
bool bAppend = true;
if (Items.Count > 16)
{
// There are other colours, need to find right index
for(int i = 16; i < Items.Count; i++)
{
if(ocbItem.Index < ((ComboboxColourItem)Items[i]).Index)
{
bAppend = false;
Items.Insert(i, ocbItem);
break;
}
}
}
if (bAppend)
Items.Add(ocbItem);
return ocbItem;
}
You can use EditingControlDataGridView to find the DataGridView which owns the editing control. Then you can use CurrentCell property of grid to find the current cell and using ColumnIndex you will find the column index. Then using Columns collection, you can get the column at that index:
var c = this.EditingControlDataGridView
.Columns[this.EditingControlDataGridView.CurrentCell.ColumnIndex]
as DataGridViewComboBoxColumn;
if (c != null)
c.Items.Add("Something");

C# - No update in listview

I have a little problem, I'm trying update my listView(listClients)
private ListView initializeLstView()
{
var lstView = new ListView();
var lstViewItem = new ListViewItem();
for (uint i = 0; i < 18; ++i)
{
lstViewItem = lstView.Items.Add("Free");
lstViewItem.SubItems.Add("Free");
}
return (lstView);
}
private ListView setNamesToLstView()
{
var lstView = initializeLstView();
try
{
for (uint i = 0; i < 18; ++i)
{
lstView.Items[(int)i].Text = clients.GetName(i);
lstView.Items[(int)i].SubItems[1].Text = "{" + i.ToString() + "}";
}
lstView.Update();
}
catch (Exception a)
{
Interaction.MsgBox(a.ToString());
}
return (lstView);
}
private void btnRefreshClients_Click(object sender, EventArgs e)
{
listClients = setNamesToLstView(); // Here, no update
}
But here, my listView contains nothing, no update / no refresh, why ?
How can I resolve this ?
The problem is you are adding items to another list view.
listClients is a member variable which points to a ListView which you previously added to Controls collection of your form. When you want to add items to that list view, you should add items exactly to that object using listClients.Items.Add(...).
But currently you have created a ListView in the method and added items to it and at last returned it and assigned it to listClients. It doesn't make your new created list view be shown on your form. It makes listClients variable only points to new created control, Whilst you are seeing the previous created ListView.

Retrieve items from a combo box

Currently I have a comboBox that reads information from outlook, and stores a list as values that can be selected for the comboBox.
I would like to be able to set the text of a button to the values stored in this comboBox.
I have an array of buttons that stores the buttons to be changed. Below is the code, so that on a click, the values from the comboBox will be displayed as the text labels in the buttons, the ?? is where I am stuck.
private void Mmaptsks_Click(object sender, EventArgs e)
{
int count = cmb.Items.Count;
for (int i = 0; i < count; i++)
{
buttonArray[i].Visible = true;
buttonArray[i].Text = ??;
}
}
Thanks,
Tom
You can try:
buttonArray[i].Text = cmb.Items[i].ToString();
Or if your combo items are not string then you can:
buttonArray[i].Text = (cmb.Items[i] as YourType).SomeProperty;

display a particular number from dropdownlist

Is there a way in dropdownlist to show the desired number on pageload?
eg.
I have a dropdownlist control
I am using a for loop to populate it
for (int i = 1; i <= 100; i++)
{
DropDownList1.Items.Add(i.ToString());
}
Now this displays 1 on page load ... but I want to display 7..
How do I do that?
If you mean that it is the default selected value, you would just need to set a default selected value in the page load, after the list has been populated. Make sure only to do this when it is not a postback or you will overwrite any user selections.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.SelectedValue = "7"
}
}
Would set it inside your for loop. Would also store the default somewhere outside the code (db, config) so if it changes you don't have to redeploy.
if(!IsPostBack)
{
for (int i = 1; i <= 100; i++)
{
var newItem = new ListItem(i.ToString());
newItem.Selected = (i == 7);
DropDownList1.Items.Add(newItem);
}
}
After your for loop
DropDownList1.Items.FindByText("7").Selected = true;
Use the SelectedItem or SelectedIndex property.

Categories

Resources