Default load in combobox - c#

If I want to load for example a default country when the combobox shows up ("Country: Lebanon"), how do I do so?
I am using VS2008 (C#). Thank you.

Add some items to the Combobox...it is just a sample, you can run a loop also to add items.
combobox1.Items.Add("USA");
combobox1.Items.Add("England");
combobox1.Items.Add("Kenya");
combobox1.Items.Add("South Africa");
Now your Combobox has four items. To select a specific country try this:
combobox1.Text = "USA";
To select a on the index basis, try this:
combobox1.SelectedIndex = 0; // For USA
Hope it helps.

You can use another method to add items in comboBox:
comboBox1.Items.Insert(0, "Egypt");
//the first item is the item index and the second is the item object.

You would usually just set myCombo.SelectedValue = "Whatever value" as soon as the form is loaded.

Use one of SelectedValue, SelectedIndex, SelectedItem or SelectedText properties of the ComboBox control.

You could try this:
myCombo.SelectedIndex = lebanonsIndex;

You can set it by using IndexOf in the Items collection
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("Lebanon");// case sensitive

This could work. Copy this code in your app.config file within appsettings.
< add key="DefaultCountry" value="Lebanon" />
and copy this at ur win form where you want to view it.
combobox1.Text = System.Configuration.ConfigurationManager.AppSettings["DefaultCountry"].ToString();.<add key="DefaultCountry" value="Lebanon"/>

You can set selected index in Form load event
If Lebanon is first in comboboxItem selectedIndex = 0;
Example:
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 0;
}

Related

Combobox returns null when value is typed

Sorry if it has some obvious solution, but I am trying to solve it for hours but could not find a solution.
I use several ComboBoxes in my WindowsFormsApplication to relate ids with names. The problem is that when a user select an item from the combobox list, it works fine, but when he types an item, the SelectedValue property of the combobox is null.
To simulate the problem, I created a from with one button and a combobox.
In my actual application, I populate the comboboxes with data from tables in a sqlserver database, but for simplicity, here I populate it with a list:
public Form1()
{
InitializeComponent();
List<KeyValuePair<short,short>> l = new List<KeyValuePair<short,short>>();
l.Add(new KeyValuePair<short,short>(1,10));
l.Add(new KeyValuePair<short,short>(2,20));
l.Add(new KeyValuePair<short,short>(3,30));
this.comboBox1.DataSource = l;
this.comboBox1.DisplayMember = "Value";
this.comboBox1.ValueMember = "Key";
}
private void button1_Click(object sender, EventArgs e)
{
if (this.comboBox1.SelectedValue == null)
MessageBox.Show("NULL");
else
MessageBox.Show(this.comboBox1.SelectedValue.ToString());
}
For example, when user select the second item (20) from the list and clicks on the button, messagebox shows 2 as it is expected, but if he types the number 20 into the combobox, the SelectedValue is null.
This problem could be solved by changing the style of combobox:
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
But it prevents user to type into the combobox, so I am forced to use the default ComboBoxStyle.DropDown.
Thats because the combo box does not select the item that you have typed. Add this option
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
Then it will select the item when ever it was able to find it.
By default it is set to AutoCompleteMode.None.
(I think) This is mainly designed for suggestions but it can solve your problem here. also if you want to show the suggestions:
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
by default it is set to AutoCompleteSource.None.
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.autocompletemode%28v=vs.110%29.aspx
An option that you have is using the EventHandler on the comboBox1.TextChange event that will allow you to personally handle how the text is translated into the different options.
This can be added to the designer (similar to a button).
this.comboBox1.TextChanged += new System.EventHandler(this.UpdateValue);
Then depending on how want to read the results and see if you have a match you can create a converter, use another key/value, or you can do a boring old tryparse as I will show you. You will need the list as a property that you can reference to see if you have found the proper results.
private void UpdateValue(object sender, EventArgs e)
{
short result;
if (short.TryParse(comboBox1.Text, out result))
{
var matches = from val in l where val.Value == result select val.Key;
{
foreach (short m in matches)
this.comboBox1.SelectedValue = m;
}
}
}
Good luck! Let me know if you need more examples with the event handler. Don't forget to vote.

c#- listbox how to get listbox values by index

I wantto know how to take list box values by index ? in my list box for first index i have content ="one"
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
string[] n = new string[1];
n[0] = listBox1.Items[0].ToString();
txtbox1.Text = n[0];
}
Using above code when I get the first list box value it returns this:
System.Windows.Controls.ListBoxItem: one
How can get only the content of the listItem(index)
Can anyone please help me?
I must admit that i'm not familiar with WPF controls but MSDN shows it:
ListBoxItem lbi = listBox1.Items[0] as ListBoxItem; // cast object to ListBoxItem
txtbox1.Text = lbi.Content.ToString();
So you have to use the Content property of the ListBoxItem. You are using ToString which just returns the fully qualified name of the type if ToString was not overridden meaningfully.
If the ListBox is empty, you get an exception if you try to access the first item via index, the you have to check it first:
if(listBox1.HasItems) // you can also use listBox1.Items.Count > 0
{
ListBoxItem lbi = listBox1.Items[0];
// ...
}
Simply use
n[0] = listBox1.Items[0].Content.ToString();
instead of
n[0] = listBox1.Items[0].ToString();
Because .ToString() on the ListBox just returns the control as string. You need to call Text.ToString() to when you want to get the text you can see as string.

How to get listbox selected item value

I am working with C# .NET 4.0
I am trying to get the value of a single selected item in a listbox.
This is how I populate the control:
this.files_lb.DataSource = DataTable object
In my designer, I have specified file_name as the DisplayMember and file_id as the DisplayValue
After selecting an item in the listbox, I tried the following to get the value:
this.files_lb.SelectedValue.ToString()
But all it returns is "System.Data.DataRowView".
At this link : Getting value of selected item in list box as string
someone suggested -
String SelectedItem = listBox1.SelectedItem.Value
However, 'Value' is not an option when I try this.
How can I get the ValueMember value from a single selected item in a listbox?
var text = (listBox1.SelectedItem as DataRowView)["columnName"].ToString();
Replace columnName with the name of the column you want to get data from, which will correspond with a column in your datasource.
Also watch out for nulls if there's no selected item.
It really should be this easy; I have the following in a click event for button to make sure I wasn't over simplifying it in my head:
private void button1_Click(object sender, EventArgs e)
{
string selected = listBox1.GetItemText(listBox1.SelectedValue);
MessageBox.Show(selected);
}
And the result:
Edit
It looks like your issue may be from not setting a property on the control:
Select the ListBox control
Click the little arrow to show the binding / items options
Select Use Data Bound Items
If I deselect that box, I get the exact same behavior you are describing.
var selectedValue = listBoxTopics.SelectedItem;
if (selectedValue != null)
{
MessageBox.Show(listBoxTopics.SelectedValue.ToString());
}
You may need to set the DataValueField of the listbox.
NewEmployeesLB.DataSource = newEmployeesPersons.DataList.Select(np => new
ListItem() { Text = np.LastName + ", " + np.FirstName, Value = np.PersonID.ToString() }).ToList();
NewEmployeesLB.DataTextField = "Text";
NewEmployeesLB.DataValueField = "Value";
NewEmployeesLB.DataBind();

combobox returning null value in c#

Here I created a for loop to list a range of numbers from 1 to 30 in the comboBox, but when I try to display the selected item from the combobox into a MessageBox it returns a null value. How can I get it to return the number selected from the comboBox? Here is my code:
string selectedNumber;
public Form1()
{
InitializeComponent();
for (int i = 1; i <= 30; i++)
{
string[] numbers= { i.ToString() };
comboBox1.Items.AddRange(numbers);
}
selectedNumber = comboBox1.SelectedText;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(selectedNumber);
}
}
Reason is clear that you have no text selected
You've to select any item in combobox first. To do so try any of the following
Set SelectedIndex to some valid index
Set SelectedItem to a valid item in combobox through code
Select an item in combobox by clicking it
Then use following code
MessageBox.Show(comboBox1.SelectedText); or
if(comboBox1.SelectedItem != null)//check for null since `SelectedItem` can be null when nothing selected
MessageBox.Show(comboBox1.SelectedItem.ToString());
Note: As #tim pointed in comments SelectedText approach won't work when DropDownStyle set to DropDownList. In that case you've to use SelectedItem approach
Here, with null check:
private void button1_Click(object sender, EventArgs e)
{
var selectedItem = comboBox1.SelectedItem ?? "";
MessageBox.Show(selectedItem.ToString());
}
As several have pointed out, there is nothing selected in the ComboBox when you assign SelectedText to selectedNumber. I would try two things:
First, don't call AddRange every time through the loop - build the array in the loop and then once the loop exits you can use AddRange. I would also use a List<string>:
List<string> numbers = new List<string>();
for (int i = 1; i <= 30; i++)
{
numbers.Add(i.ToString());
}
comboBox1.AddRange(numbers);
Secondly, in your button click event, show the selected text:
MessageBox.Show(comboBox1.SelectedText);
If comBox1's DropDownStyle is set to DropDownList, SelectedText will give an empty string. In that case, something like this might help:
MessageBox.Show(comboBox1.SelectedItem.ToString());
In reality, you'd probably want to handle the corresponding selection changed event for ComboBox as you'd probably want to do something with it in your program, but it looks like you're just trying some things out right now.
Edited To Add
Note that as Sriram said, SelectedItem can be null, so you'll want to check for that condition with either Sriram's or Przemyslaw's code if you're using SelectedItem instead of SelectedText.
Or, you can try this
for (int x = 0; x <= 30; x++)
comboBox1.Items.Add(x.ToString());
I find it a lot simpler

ListBox.DataBinding Method Question

Question about the ListBox.DataBinding method. I'm loading a listbox with a DataRows array object and I want to check for each DataRow element a column value if its true/false. If the column value is true, then modify the style for the current listBox.ListItem object. Below is some sample code.:
System.Data.DataRow[] rows = Data.SchoolDetails.Select(filter);
lstBox.DataBinding += new EventHandler(lstBox_DataBinding);
lstBox.DataSource = rows;
lstBox.DataTExtField = "Value";
lstBox.DataValueField = "ValueCode";
lstBox.DataBind();
static void lstBox_DataBinding(object sender, EventArgs e)
{
ListBox l = (ListBox) sender;
}
You can't really do that with a ListBox. Maybe you should use ListView, which supports an ItemDataBinding event for each item.
The best answer is probably the one you included in the comment above.
As an alternative I can just loop through the DataRow array and do it that way, and set the style by doing this: lstBox.Items.Add(new ListItem("").Attributes.CssStyle.Add(HtmlTextWriterStyle.FontWeight, "Bold"));. Thanks for hte help. – Brandon Michael Hunter
That is exactly how I'd do it.

Categories