Dropdownlist.selectedItem.text in Dropdownlist not working - c#

I am populating the value from the DB table to a dropdown Field, but when it is getting bound to the drop-down list in the screen the exact value is getting bound, but 2 times (ie. Duplicate value is getting bound) in the drop-down list along with the original Value.
if (ddlhour.Items.Contains(ddlhour.Items.FindByValue(time[0].ToString())))
{
ddlhour.SelectedItem.Text = time[0].ToString();
}
In the SelectedItem.Text the value is getting duplicated .
Can anyone help me solve the issue?
Where in time[0], there is a Text from the DB table.

FindBYText
int index = ddlhour.Items.IndexOf(ddlhour.Items.FindByText("Others"));
//index = 1
if (index != -1) {
ddlhour.SelectedIndex = index;
}
FindBy Value
int j = ddlhour.Items.IndexOf(ddlhour.Items.FindByValue("Others"));
if (j != -1) {
ddlhour.SelectedIndex = j;
}

Try this:
if (ddlhour.Items.Contains(ddlhour.Items.FindByValue(time[0].ToString())))
{
ddlhour.Items.FindByValue(time[0].ToString()).Selected = true;
}

use selectedValue
ddlhour.SelectedValue = time[0].ToString();
ddlhour.SelectedItem.Text changes the text of selected item

Related

C# What does setting the SelectedIndex of a combobox to -1 do?

When I was working on one of my projects I was trying to write to a datasourced combobox and then write a value into the combobox like below:
//Create list for combobox
List<string> companyList= new List<string>() { "", "Company1", "Company2" };
//Datsource list to combobox
cbCompanyName.DataSource = companyList;
//If form is set to import data and the billing address is not null
if (importAddress && StaticValues.billAddress != null)
{
//Fill all fields with data from Static Values class
cbCompanyName.Text = StaticValues.billAddress.CompanyName;
cbCountry.Text = StaticValues.billAddress.Country;
}
else
{
//Set country to US
cbCountry.SelectedIndex = 0;
}
however the line cbCompanyName.Text = StaticValues.billAddress.CompanyName; ran without writing any text to the combobox, until I set the selected index of the combobox to -1. What does setting the combobox selected index to -1 do that would change this as apposed to setting the selected index to 0?
Setting the SelectedIndex on a ComboBox to -1 deselects (SelectedItem is NULL). Setting to 0 selects the first item in Items
Combobox needs to know what is my value and display member,
giving the datasource is not enough for it.
I think you can use like this or
// comboBox.DisplayMember = "Text";
// comboBox.ValueMember = "Value";
int =0;
companyList.forEach(x=> comboBox.Items.Add(new { Text = x.toString(), Value =i++ }));
comboBox1.SelectedIndex = 0;
you can look this article
similar question and answers

C# Combobox Selected.Index = -1 not working

It should reset the Combobox to no value, Combobox is in the same panel, but the code sets the index to 0 wich is the first value of the data binded list.
It works on the second click tho...ON the first click it sets the index to 0, on the second to -1.
if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
{
foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
{
if(C.SelectedIndex != -1)
{
C.SelectedIndex = -1;
}
}
}
Perhaps you could try adding a dummy first item to your ComboBox to act as a placeholder.
This way you can deselect simply using ComboBox.SelectedIndex = 0;
Just be sure not to interpret this item in the ComboBox as a real item anywhere.
Also, try:
ComboBox.ResetText();
ComboBox.SelectedIndex = -1;
Or:
ComboBox.SelectedItem = null;
thanks all for answers...in the end I solved the issue with a workaround. The problem was, that button of the code above needed two clicks to set index to -1.
On the first click it moved to 0 and on the second to -1. I dont know why tho...Another problem was i had a index changed event on combobox and i wanted to fire it only once - not twice.
I solved the problem this way...
if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
{
foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
{
if(C.SelectedIndex != -1)
{
C.SelectedIndexChanged -= this.ComboBox_Promo_SelectedIndexChanged;
while (C.SelectedIndex != -1)
{
C.SelectedIndex = -1;
}
C.SelectedIndexChanged += this.ComboBox_Promo_SelectedIndexChanged;
this.ComboBox_Promo_SelectedIndexChanged(C, EventArgs.Empty);
}
}
}

How to set Selectedvalue in Combobox c#

I have one combobox in which I have set DataSource Value, but when I try to set SelectedValue, the ComboBox returns null. so please help.
BindingList<KeyValuePair<string, int>> m_items =
new BindingList<KeyValuePair<string, int>>();
for (int i = 2; i <= 12; i++)
m_items.Add(new KeyValuePair<string, int>(i.ToString(), i));
ComboBox cboGridSize = new ComboBox();
cboGridSize.DisplayMember = "Key";
cboGridSize.ValueMember = "Value";
cboGridSize.DataSource = m_items;
cboGridSize.SelectedValue = 4;
when I set SelectedValue with 4 then it returns NULL.
Agree with #Laazo change to string.
cboGridSize.SelectedValue = "4";
or somthing similar to this
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());
and refer to this looks as if it would be good for your issue:
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem(v=vs.110).aspx
How do I set the selected item in a comboBox to match my string using C#?
Getting selected value of a combobox
I came across this question while also trying to solve this problem. I solved it by creating the following extension method.
public static void ChooseItem<T>(this ComboBox cb, int id) where T : IDatabaseTableClass
{
// In order for this to work, the item you are searching for must implement IDatabaseTableClass so that this method knows for sure
// that there will be an ID for the comparison.
/* Enumerating over the combo box items is the only way to set the selected item.
* We loop over the items until we find the item that matches. If we find a match,
* we use the matched item's index to select the same item from the combo box.*/
foreach (T item in cb.Items)
{
if (item.ID == id)
{
cb.SelectedIndex = cb.Items.IndexOf(item);
}
}
}
I also created an interface called IDatabaseTableClass (probably not the best name). This interface has one property, int ID { get; set; } To ensure that we actually have an ID to compare to the int id from the parameter.

dropdownlist.Text not working

dropdownlist always show the first index of Item populated from database and in debug mode ddlcountry.Text always empty string("").
I have "Philippines" item in my dropdownlist but "Argentina" always shown first in my dropdown instead of "Philippines".
Please help.
//in formload
if(!isPostback)
{
DataTable dtCountry= new DataTable();
dtCountry= network.GetCountry();
for (int row = 0; row < dtCountry.Rows.Count; row++)
{
ddlCoutry.Items.Add(new ListItem { Text = dtCountry.Rows[row][1].ToString(), Value = dtCountry.Rows[row][1].ToString() });
}
}
ddlCountry.Text = "Philippines";
As I mentioned in the comment above, I think your problem is you are trying to select the dropdown option by text but getting confused with .Text property. You can do this:-
ddlCountries.Items.FindByText("Philippines").Selected = true;
Set the selected item to "Philippines" because I assume your list of countries is in alphabetical order.
ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText("Philippines"));
Also I want to point out your variable is misspelled:
**ddlCoutry**.Items.Add(new ListItem { Text = dtCountry.Rows[row][1].ToString(), Value = dtCountry.Rows[row][1].ToString() });

Finding an item in asp.ListView with Value when paging is enabled

I'm trying to find the selected Item in an aspx ListView that is on a separate page, then switch the page and select the item. I have the value property of the ListViewItem I am looking for, but cannot seem to get it to work. Here is what I tried:
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectItem(i);
break;
}
}
So lvProject is my list view. The project Variable is an Int64 which represents the UID of my Project. This is also the Value of my ListViewItems. The problem with the code above is that when paging is enabled, and the item is on a different page this will not work because the listView.Items.Count is set to the # of Items on the current page only.
My goal is to find the item, set the listview to display the correct page, and finally select the item. You would figure that I could just set the SelectedValue property, but this is not that simple as it is read only. Any ideas would help greatly, thanks in advance.
--Roman
In order to get the total record count from the object data source, you should use the Selected event as follows:
protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
// Get total count from the ObjectDataSource
DataTable dt = e.ReturnValue as DataTable;
if (dt != null) recordCount = dt.Rows.Count; // recordCount being declared outside the method
}
You would then be able to search for the item as follows:
for (int i = 0; i < recordCount; i++)
{
Label lblItem = (Label)lvProject.Items[i].FindControl("IdLabel");
if (lblItem.Text.Equals(itemToSearch))
{
lvProject.SelectedIndex = i;
break;
}
}
Hope it helps!
How do you bind ListView Items?
If you are using database level paging (stored procedure, query) - you should do search in the same way - using database query/stored procedure by passing a search criteria.
If you are bind ListView Items to a collection of items which are provided by a business/data layer - you have to create search method on layer which provides items so this method will be able to loop through the items.
You should set the SelectedIndex property to i
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectedIndex = i;
break;
}
}

Categories

Resources