Duplicate item in dropdown list - c#

I was create a Employee registration page with dropdown list.Its used for selecting priority for each user. suppose i want to edit some user detail in this time am using the below code to select the dropdown list. It returns repeat value with out first index. That means a user have 3rd priority means it select third priority with out having 1st priority.
foreach (DataRow dr in DS.Rows)
{
txtemail.Enabled = false;
pan_addEdit.Visible = true;
this.btnSave.Text = "Update";
lbluserid.Text = Convert.ToString(dr["fdluserId"]);
txtuername.Text = Convert.ToString(dr["flduser"]);
txtPass.Text = Convert.ToString(dr["fldpass"]);
txtemail.Text = Convert.ToString(dr["fldemail"]);
ddlstatus.SelectedValue = Convert.ToString(dr["fldstatus"]);
ddlusergroup.SelectedValue = Convert.ToString(dr["fldgroupId"]);
ddldept.SelectedValue = Convert.ToString(dr["flddept"]);
ddlperiority.SelectedValue = Convert.ToString(dr["fldperiority"]);
}
dropdown show the below value after binding
1st priority
2nd priority
3rd priority
dropdown show the below value after binding
3rd priority
2nd priority
3rd priority
please help me to fix this error..

You don't want to change the Text of the curently selected item. You want to change the selection itself. Therefor you could use the SelectedIndex or the SelectedValue property of the DropdownList.
ddlperiority.SelectedValue = Convert.ToString(dr["fldperiority"]);
Of course there must be a value that matches dr["fldperiority"]. Maybe this is the text field and you need the PK/FK field.

You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.
ddlperiority.ClearSelection();
ddlperiority.Items.FindByValue(dr["fldperiority"].ToString()).Selected = true;
Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.
Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.
"Cannot have multiple items selected in a DropDownList"

If still above answers are not working for you, try something like this
var item = Convert.ToString(dr["fldperiority"]);
switch(item)
{
case "1st priority":
ddlperiority.SelectedIndex = 0;
break;
case "2nd priority":
ddlperiority.SelectedIndex = 1;
break;
case "3rd priority":
ddlperiority.SelectedIndex = 2;
break;
}

Please do like below
ddlstatus.Items.Clear();
ddlperiority.Items.Clear();
ddlusergroup.Items.Clear();
ddldept.Items.Clear();
foreach (DataRow dr in DS.Rows)
{
txtemail.Enabled = false;
pan_addEdit.Visible = true;
this.btnSave.Text = "Update";
lbluserid.Text = Convert.ToString(dr["fdluserId"]);
txtuername.Text = Convert.ToString(dr["flduser"]);
txtPass.Text = Convert.ToString(dr["fldpass"]);
txtemail.Text = Convert.ToString(dr["fldemail"]);
ddlstatus.Items.Add ( Convert.ToString(dr["fldstatus"]));
ddlusergroup.Items.Add( Convert.ToString(dr["fldgroupId"]));
ddldept.Items.Add( Convert.ToString(dr["flddept"]));
ddlperiority.Items.Add( Convert.ToString(dr["fldperiority"]));
}

Related

How can I remove my selected item duplicate and provide a Please Select option AFTER my selected item in my DropDownlist is bound?

In my Page Load method I prepopulate the DropDownList with lookups from my database.
ddRelationship.DataSource = _dal.GetStandardLookups(Guid.Parse(fhsConstants.fhsRelationship));
ddRelationship.DataTextField = "LookupDescription";
ddRelationship.DataValueField = "LookupValue";
ddRelationship.DataBind();
ddRelationship.Items.Insert(0, new ListItem("Please Select", "0"));
I then set the existing value from the list in with Populate from database method
if (String.IsNullOrEmpty(_dal.GetStandardLookupDescription(CurrentDependant.Relationship)) == false)
{
ddRelationship.SelectedItem.Value = _dal.GetStandardLookupValue(CurrentDependant.Relationship);
ddRelationship.SelectedItem.Text = _dal.GetStandardLookupDescription(CurrentDependant.Relationship);
}
else
{
ddRelationship.SelectedIndex = 0;
}
The issue I am having is that, if populate from database I am no longer able to see my 'Please Select' option and my selected option appears twice! I.e. If the populate from database method is not called I can see 'Please Select', 'Mother', 'Father'... If I populate from database and my value is Father then I can see 'Father', 'Mother', 'Father'...
Is there a way to stop this duplication and retain my Please Select option? Thanks
I believe this is working for me now, albeit that it uses description instead of value:
ddRelationship.ClearSelection();
ddRelationship.Items.FindByText(_dal.GetStandardLookupDescription(CurrentDependant.Relationship)).Selected = true;

how to set the default value to the drop down list in C#?

DataSet dsCurrency = new DataSet();
dsCurrency = ParamCurrency.SelectCurrencys();
ddCurrencyField.DataSource = dsCurrency;
ddCurrencyField.DataTextField = "CurrencyName";
ddCurrencyField.DataValueField ="CurrencyCode";
ddCurrencyField.DataBind();
How to select a default value to the dropdownlist control using C#?
If you know the value will exist:
ddCurrencyField.FindItemByText("YourDefaultText").Selected = true;
else
ListItem selectedListItem = ddCurrencyField.Items.FindItemByText("YourDefaultText");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
};
You can also find item by value :
ListItem selectedListItem = ddCurrencyField.Items.FindByValue("YourDefaultValue");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
};
I assume in your datasource object (dsCurrency) is not parsing the default value for the dropdown.
So first you will have to add the default item. After binding the datasource do the following.
ddCurrencyField.Items.Insert(0, new ListItem("-- Select --",0));
With the above code you will have a default/first item selected as "--Select--". If it does not select the first item then simply set the SelectedIndex to 0.
There are 2 ways to set the default item after populating a dropdown.
you can use the "SelectedValue" property
you can use the "SelectedIndex" property
Most of the code samples are given in the previous answers. But I prefer to use the "FindByValue" method.
ddCurrencyField.SelectedIndex = ddCurrencyField.Items.IndexOf(ddCurrencyField.Items.FindByValue(myValue));
If you want to write a safe code please use the second option.
If this dropdown list is a combobox, use this:
ddCurrencyField.SelectedIndex = ddCurrencyField.Items.IndexOf("Wanted Value");

How to get the value of selected item in a xlDropDown which is added programmatically to a Excel sheet cell

The following code shows the way i created the drop downs programmatically. It works fine. But now I need to get value of a specific dropdown of a cell.
Microsoft.Office.Interop.Excel.DropDowns xlDropDowns;
Microsoft.Office.Interop.Excel.DropDown xlDropDown;
xlDropDowns = ((Microsoft.Office.Interop.Excel.DropDowns)(sheet.DropDowns(Type.Missing)));
xlDropDown = xlDropDowns.Add((double)rag.Left, (double)rag.Top, (double)rag.Width, double)rag.Height, true);
var DropDownList = {"aaaa","bbbb","cccc","dddd"};
int x = 0;
foreach (var item in DropDownList)
{
x++;
xlDropDown.AddItem(item);
}
This is how i tried to get the xlDropDown value. currentCell is the cell where i have the drop down
ColumnVal = currentCell.Text; // This didnt give any output
OR
var dd = (Microsoft.Office.Interop.Excel.DropDown)currentCell.DropDowns(Type.Missing);
I know the 2nd one is wrong, because the cell range and drop down are 2 different things. But I tried all the options, still couldnt find any solution. Someone please help me
More clearly, I want to access a specific cell(currentCell), and the xldropdown it contains and then get value from it
First you would need a reference to the drop down you've just added:
*Assuming there's only one drop down, the below would do
xlDropDown = ((Excel.DropDown)(xlDropDowns.Item(1)));
then you need to access the .get_List() property of the Excel.DropDown while making sure that something has been selected.
Example:
if (xlDropDown.Value > 0)
{
sht.get_Range("A1").Value = xlDropDown.get_List(xlDropDown.Value);
}
else
{
throw new Exception("Nothing was selected yet");
}
Identifying the dropdowns:
You could a for each loop on the xlDropDowns collection and grab the .Name and .ListIndex of each xlDropDown?
foreach (Excel.DropDown xlDD in xlDropDowns)
{
MessageBox.Show(xlDD.Name + ", " + xlDD.ListIndex);
}

check combo-box selected value string and change selexctedIndex in another combo box

I have combobox in which I am checking if the selected item text="Digital" then change the behavior in another combobox. It worked when I was checking by Selected Value but when i changed it to the following it stopping performing this behavior:
if (cmbCamSupplier.SelectedItem.ToString().Equals("Digital"))
cmbCamPrb.SelectedIndex = cmbCamSupplier.Items.IndexOf("Digital");
//cmbCamPrb.SelectedIndex = 5;
else
//cmbCamPrb.SelectedIndex = cmbCamSupplier.Items.IndexOf("Digital");
cmbCamPrb.SelectedIndex = 1;
What am I doing wrong. This should work but seems to be broken somewhere. Any help??
Before it was this:
if (cmbCamSupplier.SelectedValue.Equals(5))
cmbCamPrb.SelectedIndex = 5;
else
cmbCamPrb.SelectedIndex = 1;
but with this I knew the Digital was located at ='5' but i wanted it by name not by the selected value
Text will give you the selected text of the editable portion, Selected Item will return you the object and selected index will return you the index. Does this work?
if (cmbCamSupplier.Text.Equals("Digital"))
cmbCamPrb.SelectedIndex = cmbCamPrb.Items.IndexOf("Digital");
else
cmbCamPrb.SelectedIndex = 1;

How to set Selected item of ComboBox in C# Windows Forms?

I am trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.
For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.
Not working code:
for (int i = 0; i < cmbVendor.Items.Count; i++)
if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
{
cmbVendor.SelectedIndex = i;
break;
}
You can get your item index by the .Items.IndexOf() method. Try this:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));
You don't need to iterate.
You can find more information in Stack Overflow question How do I set the selected item in a comboBox to match my string using C#?.
The following is working for me perfectly. Pass any value or Text which is available in the combobox.
comboBox1.SelectedIndex = comboBox1.FindString(<combobox value OR Text in string formate>);
You have it in your if:
cmbVendor.SelectedItem = cmbVendor.Items[i];
At last I found it out. It's:
cmbVendor.Text = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.
If you have set ValueMember property for the ComboBox control, you can simply assingn the Value to the ComboBox control's SelectedValue property. You don't have to find the index explicitly.
Here's an example:
public class Vendor{
public int VendorId {get; set;}
public string VendorName {get; set;}
}
// Inside your function
var comboboxData = new List<Vendor>(){
new Vendor(){ vendorId = 1, vendorName = "Vendor1" },
new Vendor(){ vendorId = 2, vendorName = "Vendor2" }
}
cmbVendor.DataSource = comboboxData;
cmbVendor.DisplayMember = "VendorName";
cmbVendor.ValueMember = "ValueId";
// Now, to change your selected index to the ComboBox item with ValueId of 2, you can simply do:
cmbVendor.SelectedValue = 2;
Assuming gridView1.GetFocusedRowCellValue("vVendor") really works as expected, the following code should fix the problem.
string selected = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
foreach ( var item in cmbVendor.Items )
{
if (string.Compare(item.ToString(), selected, StringComparison.OrdinalIgnoreCase) == 0)
{
cmbVendor.SelectedItem = item;
break;
}
}
The original code had multiple calls to gridView1.GetFocusedRowCellValue("vVendor"), whereas you only need one.
The suggested "comboBox1.Items.IndexOf(" assumes too much about the content of cmbVendor.Items.
I had a similar problem and worked it out partially with the help of the other answers here. First, my particular problem was that
combobox1.SelectedItem = myItem;
was not working as expected. The root cause was that myItem was an object from a group which was effectively the same list as the items in the combobox, but it was actually a copy of those items. So myItem was identical to a valid entry, but itself was not a valid object from the combobox1 container.
The solution was to use SelectedIndex instead of SelectedItem, like this:
combobox1.SelectedIndex = get_combobox_index(myItem);
where
private int get_combobox_index(ItemClass myItem)
{
int i = 0;
var lst = combobox1.Items.Cast<ItemClass >();
foreach (var s in lst)
{
if (s.Id == myItem.Id)
return i;
i++;
}
return 0;
}
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String From DataGrid Cell value")
Try this this will work fine in C# Windows application
this works for me.....
string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;

Categories