ComboBox doubling in values c# - c#

I have following piece of code:
private void nameTextBox_Leave(object sender, EventArgs e)
{
var names = ConfigurationManager.AppSettings.AllKeys
.Where(k => k.StartsWith("name"))
.ToArray();
// Add names to combobox
comboBox.Items.AddRange(names);
}
Problem is each time I press Tab from textbox, comboBox elements keep on doubling. If it had Ken, John, Tim in there, it will show that twice if I press tab again.
I tried using distinct in the names above but that does not do anything as new instantance is created each time and previous is saved. I cannot make comboBox empty right after adding names as it is being used in a button click latter on in the code.
Only alternative i thought was of declaring a global variable and make sure its value is 0
and then only insert values in comboBox, and change it to 1 once value is inserted. But that does not seem like a good coding practice.
Is there any better way to get this done?

Add comboBox.Items.Clear() before the AddRange. So the whole block should be.
private void nameTextBox_Leave(object sender, EventArgs e)
{
var names = ConfigurationManager.AppSettings.AllKeys
.Where(k => k.StartsWith("name"))
.ToArray();
// Add names to combobox
comboBox.Items.Clear();
comboBox.Items.AddRange(names);
}

i'm not sure if I understand perfectly, but why can't you just clear the items before populating?
comboBox.Items.Clear()
comboBox.Items.AddRange(names);
also you could try not to use Items, but DataSource:
comboBox.DataSource = names;

The suggestions to clear the combo box first should solve your problem, but if you are loading the combo box on page load as well then I don't think this is the best solution (just masking the real problem). If you are populating the combobox on page load then add a Page.IsPostBack check in there:
example:
if(!Page.IsPostBack)
{
//Populate the initial values into the combobox
}
If you aren't then the clear solution should be fine.

Related

How to fill the second dropdown with the same value as the first dropdown

I have 2 databounded dropdownlist. They have the same value(all months).
I want that, if a user choose (in the first Dropdown) for example april then the second Dropdown should jump automatically to April.
The only thing I could think of was:
protected void ddMonthfrom_SelectedIndexChanged(object sender, EventArgs e)
{
ddMonthfrom.SelectedItem.Text = ddMonthto.SelectedItem.Text;
}
It does not work. When I click on April the second Dropdown does not Change.
try ddMonthto.SelectedValue = ddMonthfrom.SelectedItem.Value;
OnFristDropDownSelectedIndexChange (ddMonthfrom)
Set the value of the Second DropDown (ddMonthto).
If they are the same values in both Drop Downs then remove the text portion
ddMonthfrom.SelectedItem = ddMonthto.SelectedItem;
Try:
ddMonthfrom.SelectedIndex = ddMonthfrom.FindStringExact(ddMonthto.Text);
This should also work if the comboBox ddMonthto doesn't have a DataSource.
Notes:
You can also use .SelectedItem.ToString() instead of .Text, while .SelectedItem.Text isn't correct.
If you populate your comboBox using a datasource, you can just use the same datasource for both comboBoxes, and the same item should be selected automatically.
Hope that helps :)

Telerik Searchable radcombobox not repopulating after item is selected

I have a RadComboBox that allows for custom searching for about 1500 records. Once one is selected the User control changes accordingly. If I were to want to select a new record, the selected record is the only record that displays and when you type in the search field, nothing is found either.
However, if you select a record, do what you need then click the drop down then click off it then click on it again, it resets itself as desired. How can I make it so the drop down list populates itself on the initial click?
Probably you are losing the datasource.
On the SelectedIndexChange event, you can repopulate the datasoure and set currently selected value from arguments that are passed to this event.
So in a pseudocode it would look like:
procedure OnSelectedIndexChanged(object sender, SelectedIndexChangedEventArgs e)
{
var selectedValue = e.Value;
(sender as RadComboBox).DataSource = YourMethodToGetDatasource();
(sender as RadComboBox).DataBind();
(sender as RadComboBox).SelectedValue = selectedValue;
}
and yes i know currently pseudo code doesn't look so pretty but of course you will need to use the id of your control in place of (sender as RadComboBox).
If someone know a better method for this i would be glad to gain this knowledge :)

Choosing a textBox to be edited from GUI (WinForms)

Let's say I have 10 textBoxes in my form. They are named textBox1, textBox2 etc. And I'd like to be able to choose the textBox I want to edit - for example I have a comboBox with numers 1-10 and if I pick, let's say "5", then the text of the textBox5 is being changed (typed in an additional, eleventh, textBox for example).
I know it sounds weird but I need to learn how to choose controls and edit them from the GUI.
You should use the combobox (cmb in my code) SelectedIndexChanged,
private void cmb_SelectedIndexChanged(object sender, EventArgs e)
{
var numberFromComboBox = cmb.Text;
var txtBoxToEdit = Controls.OfType<TextBox>()
.Where(c => c.Name.EndsWith(numberFromComboBox))
.FirstOrDefault();
if(txtBoxToEdit != null)
{
txtBoxToEdit.Text = "was selected";
}
}
Update
To understand what the code does, one needs to understand a bit of Linq.
All Controls (ComboBoxes, DataGridViews, TextBoxes, etc.) are stored in the Controls collection.
But we only want the TextBoxe's that is directly on the form:
List<TextBox> listOfTxtBox = Controls.OfType<TextBox>();
This listOfTextBox now contains all the textboxes. But we only need one that matches the number we selected in the combobox (cmb).
To do that, we "filter" our collection of textboxes with the Where method.
In my expression it starts with - c => c.Name.EndsWith(numberFromComboBox) gives all the Textboxes that has a name (TextBox.Name) that ends with the number from our ComboBox.
The Last part is FirstOrDefault(), it simply takes the first item in our (now filtred) collection. If there is no items in the collection (for whatever reason) FirstOrDefault will return null
Hopes this helps to clearfi what the code does

check if datagrid has been sorted

In the datagrid Item Databound event, I want to know if the grid has been sorted or loading for the first time. I know there is an event OnSortCommand and I can set some variable here to check if there is a sort happening on the grid. But I want to know if there is a better way to check if the grid has been sorted. Thanks in adv. for your help.
PS: I took a look at this post and it suggests to check for Request.Form["__EVENTTARGET"] and Request.Form["__EVENTARGUMENT"]. Let's say I have 'x' number of columns in the grid and other server controls on the form, I feel it's not a correct way to have 'x' If conditions and check if the request is from one of those many controls.
If a DataGridView is sorted, its SortedColumn property will be set.
Here is an example to verify the sort order of the columns of the DataGridView control or checking the status of the property sortorder.
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.Sorted +=new EventHandler(dataGridView1_Sorted);
}
void dataGridView1_Sorted(object sender, EventArgs e)
{
if (this.dataGridView1.SortOrder.Equals(SortOrder.Ascending))
{
// your code here
}
if (this.dataGridView1.SortOrder.Equals(SortOrder.Descending))
{
// your code here
}
if (this.dataGridView1.SortOrder.Equals(SortOrder.None))
{
// your code here
}
}
Regards
The suggestion from the post you linked is rather inelegant ;)
I suggest you read this, which as very straight forward example. It uses a DataView to sort the data. If you want to "remember" for whatever reason, the last sort expression that was used to sort the grid, you can simply store it in ViewState as so:
ViewState["LastSortExpression"]=e.SortExpression;
And retrieve it on PostBack as needed.

Double-Clicking Item in ListView

So I added a list view, and I am displaying 3 columns of strings in each. I also have the full row select on. I want to be able to double click on one of the rows, and have it return the string in the 3rd column. I've tried to look everywhere for a solution to this, but so far nothing comes up.
My code so far is:
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
MessageBox.Show(songList.SelectedItems[2].ToString());
}
Yet it returns an error saying "InvalidArgument=Value of '2' is not valid for 'index'.
Parameter name: index"
You could try:
if (songList.SelectedItems.Count > 0)
{
ListViewItem item = songList.SelectedItems[0];
string s_you_want = item.SubItems[1].Text;
}
Taken a ListViewItem, you can take columns values using SubItems[] property.
I think that you hould bound not your listView to doubleClick event, but listViewItem. sender will have DataContext, from which you can get your third column.
How do you fill the ListView? Wihtout knowing this, it's difficult to help. May be you could try this:
Set a breakpoint in this line:
MessageBox.Show(songList.SelectedItems[2].ToString());
As soon as the debugger hits the breakpoint you could select songList and hit Shift-F9.
Now you can explore the songList and check yourself how to get the string of the third column.
SelectedItems returns a SelectedListViewItemCollection and with the indexer you are accessing elements in this collection, i.e. ListViewItems, not the columns. this means that if you have a single row selected the collection contains only one item, and trying to access the third one gives you the error.
Try (edit according to Marco's comment):
songList.SelectedItems[0].SubItems[1].Text

Categories

Resources