I have a variable value string i = xyz;
and i want to set dropdownlist selectedIndex value from a variable value.
And I am trying this
dd_Interest.SelectedIndex = dd_Interest.Items.IndexOf(dd_Interest.Items.FindByText(categoryInterest1));
But its not working
How can i do this?
Waiting for reply
You not need to find the index of the selected item you just try the following code where you want to get the selected value of dropdownlist.
dd_Interest.SelectedItem.Value = Convert.ToString(Request.QueryString["searchInterest"]);
Or there some other ways like given below:
dd_Interest.Items.FindByText(Convert.ToString(Request.QueryString["searchInterest"])).Selected= true;
That's all.
It is very simple, just set the SelectedItem property
dd_Interest.SelectedItem= myString
Have a look here at the MSDN documentation
ComboBox.SelectedItem Property
How about:
dd_Interest.Items.FindByText("some text").Selected = true;
or
dd_Interest.Items.FindByValue("some value").Selected = true
You can also do a combination between both using Linq:
ListItem item = dd_Interest.Items.Cast<ListItem>()
.FirstOrDefault(x => x.Text == "some text"|| x.Value == "some value");
if (item != null)
{
item.Selected = true;
}
Hope this helps :)
I read in your comment, and I'm not sure what's the error you met. Anyway I saw something strange in your comment...
This is a querystring (Request.QueryString["searchInterest"];) and I
get querystring value in a variable str_LastSearchInterest =
Request.QueryString["searchInterest"]; and I get
querystring(Interest|AP Chinese) and then i store AP Chinese in a
variable categoryInterest1 =
str_LastSearchInterest.Split('|')[0].ToString(); and Interest in
categoryInterest2 = str_LastSearchInterest.Split('|')[1].ToString();
But after splited, at the index 0 should store "Interest" and index 1 should store "AP Chinese".
So categoryInterest1 value should be "Interest", not "AP Chinese". Then if you want to find index of "AP Chinese" and select it as default, you have to use categoryInterest2 instead.
Related
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
Trying to make an application in C# using Windows Forms in Visual Studio Version 15. Id like to be able to check to make sure each selected item is different in each comboBox. I've discovered that you can create an array of controls but the problem I'm having is in accessing the values in that array to check each one programmaticly
how could I use this array to check to see if all values are unique and return a simple bool?
Control[] statboxes = { comboBoxA, comboBoxB, comboBoxC, comboBoxD, comboBoxE, comboBoxF };
You can use linq like this:
var result = statboxes.Distinct().Count() == statboxes.Count();
Edit:
To check the unique selected item try this:
var result = statboxes.Select(s => ((ComboBox)s).SelectedItem).Distinct().Count() == statboxes.Select(s => ((ComboBox)s).SelectedItem).Count();
With Combobox.selectedindex you can select an item based on their index nr. And with Combobox.selectedvalue, you can select an item based on their name.
As for picking the unique values, you can use Combobox.Distinct().Count, which is explained in t2t's answer.
You can utilize HashSet<T>.Add(value) method with Enumerable.All extension method
// For example combobox values is of type int
var values = new HashSet<int>();
var isUnique = statboxes.All(combobox => values.Add((int)combobox.SelectedValue));
HashSet<T>.Add method will return true if given value was successfully added to the set and false if given value already exists.
Use ComboBox array instead of Control so you no need to cast it while doing your operation:
ComboBox[] statboxes = { comboBoxA, comboBoxB, comboBoxC, comboBoxD,
comboBoxE, comboBoxF };
Then check if all of the comboboxes has unique selected value:
bool IsAllComboBoxesHasDistinctSelectedValue = statboxes.Select<ComboBox,string>((cb) =>cb.SelectedValue.ToString()).Distinct().Count() == statboxes.Count();
I have a small problem with ComboBoxEdit (DevExpress.XtraEditors). I cannot add a value or set SelectedIndex for my ComboBoxExit.
ComboBoxEdit combo = new ComboBoxEdit();
ComboBoxItemCollection coll = combo.Properties.Items;
coll.BeginUpdate();
try
{
coll.Add(new PersonInfo("Sven", "Petersen"));
coll.Add(new PersonInfo("Cheryl", "Saylor"));
coll.Add(new PersonInfo("Dirk", "Luchte"));
}
finally
{
coll.EndUpdate();
}
combo.SelectedIndex = -1; Comboboxedit1.Properties.Items.Add(combo);
It does not work and just adds shows this:
WIth this line :
Comboboxedit1.Properties.Items.Add(combo);
You are adding the ComboBox object inside itself. ComboBoxEdit ToString() method returns the name you are seeing in your screenshot.
So, remove this line.
Your code in taken from the official DevExpress documentation (except the line above that you should remove), and works fine : items are indeed added.
However, setting the SelectedIndex property to -1 doesn't select anything, as the documentation states :
The BaseListBoxControl.SelectedIndex property is set to -1 for
demonstrative purposes (the property is set to -1 by default). This
ensures that no item is currently selected in the combo box.
You can do :
combo.SelectedIndex = 0; // Select Sven
Or
combo.SelectedIndex = 1; // Select Cheryl
Or
combo.SelectedIndex = 2; // Select Dirk
Use some like this:
try
{
ComboBoxEdit combo = new ComboBoxEdit();
combo.Properties.Items.Add("Sven, Petersen");
combo.Properties.Items.Add("Cheryl, Saylor");
combo.Properties.Items.Add("Dirk, Luchte");
}
Will work fine!
No complication, no inovation, simple like need be!
I want to set the selecteditem attribute for an ASP.Net dropdownlist control programmatically.
So I want to pass a value to the dropdownlist control to set the selected item where the item is equal to the passed value.
Assuming the list is already data bound you can simply set the SelectedValue property on your dropdown list.
list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";
list.DataBind();
list.SelectedValue = myValue.ToString();
The value of the myValue variable would need to exist in the property specified within the DataValueField in your controls databinding.
UPDATE:
If the value of myValue doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.
ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :
ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.
Here is the code I was looking for :
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));
Or
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));
Well if I understood correctly your question. The Solution for setting the value for a given dropdownlist will be:
dropdownlist1.Text="Your Value";
This will work only if the value is existing in the data-source of the dropdownlist.
If you need to select your list item based on an expression:
foreach (ListItem listItem in list.Items)
{
listItem.Selected = listItem.Value.Contains("some value");
}
Just Use this oneliner:
divisions.Items.FindByText("Some Text").Selected = true;
divisions.Items.FindByValue("some value").Selected = true;
where divisions is a dropdownlist control.
Hope it helps someone.
var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);
OR
foreach (var listItem in ctx.Items)
listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);
Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
On load of My Windows Form the comboBox will display the ClassName column of my DataTable as it's the DisplayMember also has its ValueMember (not visible to user) with it.
private void Form1_Load(object sender, EventArgs e)
{
this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
}
Safety check to only select if an item is matched.
//try to find item in list.
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;
ddlemployee.DataSource = ds.Tables[0];
ddlemployee.DataTextField = "Employee Name";
ddlemployee.DataValueField = "RecId";
ddlemployee.DataBind();
ddlemployee.Items.Insert(0, "All");
I am dynamically creating a combobox like this:
public Control GenerateList(Question question)
{
// Get a list with answer possibilities
List<QuestionAnswer> answers = question.GetAnswers();
// Get a collection of given answers
Collection<QuestionnaireAnswer> givenAnswers = question.GetFilledAnswers();
ComboBox cmb = new ComboBox();
cmb.Name = "cmb";
cmb.DataSource = answers;
cmb.DisplayMember = "Answer";
cmb.ValueMember = "Id";
// Check an answer is given to the question
if (givenAnswers != null && givenAnswers.Count > 0)
{
cmb.SelectedValue = givenAnswers[0].AnswerId;
}
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.SelectedIndexChanged += new EventHandler(cmb_SelectedIndexChanged);
cmb.Leave += new EventHandler(cmb_Leave);
return cmb;
}
The problem is,when executing cmb.SelectedValue = givenAnswers[0].AnswerId; cmb.SelectedValue is always null.
When debugging and I explore answers (the datasource) I see that Id (ValueMember) is exactle the same as AnswerId (in the if statement). Both have the same type (long) and the same value, but SelectedValue stays null.
Is there something I don't see?
EDIT:
It looks like the combobox stays empty. When I replace cmb.SelectedValue = givenAnswers[0].AnswerId; with cmb.SelectedIndex = 0; I get an ArgumentOutOfRangeException. This while the answers collections count is 2. So the datasource isn't null... Very strenge huh?
Solution:
The SelectedValue, SelectedIndex, SelectedItem properties can't be set until the control is added to the form. After the control is added to the form, the selectedValue, -Index and -Item properties can be set.
Solution:
The SelectedValue, SelectedIndex, SelectedItem properties can't be set until the control is added to the form. After the control is added to the form, the selectedValue, -Index and -Item properties can be set.
I met this weird issue before, at last I gave up and used another way:
cmb.Items.FindByValue(givenAnswers[0].AnswerId).Selected = true;
It worked fine...Hope you good luck!
cmb.SelectedIndex = cmb.FindStringExact("Desired Value")
The cmb.FindStringExact("Desired String") returns the index of the value you would like to select and the cmb.SelectedIndex sets the combobox to that index.
Thanks to Billious for showing me the light!
FYI - This is the VB.NET Winforms Version.
Are you looking at the same property?
cmb.ValueMember = "Id";
..
cmb.SelectedValue = givenAnswers[0].AnswerId;
You're refering to another ValueMember then the Id you're posting into the SelectedValue.
Besides that you might want to try to set your Display- and Value-member before databinding. It's faster.
Make sure QuestionAnswer has public accessors corresponding (same name) to the Display/Value Members you use.
I ran into the same problem, and found that my issue was I was treating SelectedValue as an integer, when in actual fact it was an object. The "FindByValue" solution from Danny Chen above doesn't work in WinForms, so I tried using "FindStringExact" and searched on the DisplayMember:
cmb.Items.FindStringExact(<Display string>)
Not an ideal solution, but it worked.