Cannot select multiple items in a dropdownlist - c#

My C# ASP.NET web site has a weird problem.
I set a selected value for a dropdownlilst based on a value from a stored procedure output parameter like this:
this.myDropDown.SelectedValue = cmd.Parameters["#SourceID"].Value.ToString().Trim();
For some reason, I get a "Cannot have multiple items selected in a dropdownlist" error on this line of code. I've stepped through the code and searched for other references to this dropdownlist, commented the references out, and tried again.
Nope, still doesn't work.
The only way the page works is if I comment out the above line of code. Any ideas why this would be a problem?
SourceID is always an integer and exists in the list of selections. I've verified (by stepping through the code) that the selectedValue is always numeric, and never changes between the time this line executes and the time the page finishes loading.
Thoughts?

This would occur if you had two items in the DropDownList with the same Value.

If you do mean to select multiple items, you need to use ListBox control with SelectionMode="Multiple" set.

You have 2 items with the same value.
You can solve it:
1) Find Items by value to list.
2) Get first item index.
3) Select item by index.

Related

how to change starting position combobox C# mysql

I have a little trouble using C# combobox with MySql
So, to begin with... I have combobox and button on a form. After submitting a form, executes MySql query like :
"select * from db1.users where login='"+combobox.SelectedIndex+"')";
It works great, But.... if we submit the first element of combobox - MySql FOREIGN KEY problem occures (= NULL and so on).
Any Ideas how to give him know, that first element from combobox isn't NULL ?
Stupid idea but who knows:
Mysql counts from 1, combobox from 0 did you try:
(selectedIndex + 1)
I'll assume you're talking about just submiting the button without actually selecting a value on the combobox, right?
You should do a simple if before executing your command, like:
if (combobox.SelectedIndex != null)
{
codethis("select * from db1.users where login='"+combobox.SelectedIndex+"')");
}
else
{
//do something else
}
Are you sure what you want isn't combobox.SelectedItem?
This would be the case if "login" was a string in the SQL database.
If it's an integer, have you tried doing combobox.SelectedIndex+1? This could fix the problem if "login" starts at "1" in the SQL whilst SelectedIndex starts at 0 in C#.
In any case, check the answer below if your problem is the combobox having no selected item.
Optionally you can have the form OnLoad do combobox.SelectedItem=1;
You would want to stop using SelectedIndex, because it's not meant to represent your data. The problem may not even be in your current situation (mismatch between 1s and 0s indexing). Consider the following:
Another developer adds sorting to your combox. Now instead of a,b,c the values are c,b,a and the selected index of 0 will now point to c instead of a as it has used to do
Somebody removes users in the database, so in the database you now have b,c,d, think about what data you will have in your combobox?
To fix this problem you should use a value. Each combobox should have: displayed text, corresponding value (which is hidden from user) and selected index. Using selected index (or selected item) you get the item's value which should be your database_id. For example see this answer if the value is not available for your combobox type out of the box.
Bonus points:
use parameterised queries (prevents SQL injection attacks)
never store passwords, instead store password hashes and random salts (read more)

Text property of Listbox control returns string when nothing is selected

listBox_groupmakingrepairs is a listbox control on my form. When first loading the form, nothing is selected in the listbox and the code in the following 'if' statement will run because the condition is true.
if (listBox_groupmakingrepairs.Text == "")
{
Error = "You must indicate what group will be making the repairs.";
Con = listBox_groupmakingrepairs;
}
But, if I run the following code...
listBox_groupmakingrepairs.Text = "Cell";
Followed by this code...
listBox_groupmakingrepairs.ClearSelected();
The listbox will not have anything selected, yet it will cause the first code snippet above to be false and not run the code in the 'if' block. When I step through and check the value of 'listBox_groupmakingrepairs.Text' it is "Cell". Yet on the form, the listbox clearly has nothing selected.
Am I using the Text property of the Listbox control incorrectly? Or is this a bug? Or am I missing something altogether obvious?
The way I see it I have a property (Text) that seems to work well most of the time. But under certain conditions it returns a value that isn't the correct value anymore. Why is the Text property returning an old value that has since changed? Does this make logical sense to anyone who can explain it to me?
That is because the ListBox control of C# winform control handles both the Text property and the SelectedItem separately, but in a way together.
It works in the following way:
IF [SelectedItem is True i.e. Item is selected] THEN
Text property = SelectedItem.ToString()
ELSE IF [SelectedItem is False i.e. No Item is selected] THEN
Text Property will still assume its current value (or in a way previous value) unless its manually reset
So always in such cases donot forget resetting the Text property. Hope this helps...
Maybe I am a bit slow, but eventually I realized that Microsoft is the creator, so to them I will go for the answer.
Here is what I found:
According to Microsoft, the following code I was using is a correct way of selecting text in a listbox control.
listBox_groupmakingrepairs.Text = "Cell";
Then, also according to Microsoft, the following code I was using is a correct way of deselecting all items in a listbox.
listBox_groupmakingrepairs.ClearSelected();
Finally, also according to Bill Gates (see two links above) the Text property is also a correct way to retrieve the text of the first selected item.
string SelectedText = listBox_groupmakingrepairs.Text;
But, as I described in my original question above, when I evaluated the Text property WHEN NOTHING WAS SELECTED IN THE LISTBOX, it contained text. But Microsoft says "this property returns the text of the first selected item." WHICH IS FALSE. It should have returned null because there was nothing selected...yet it returned text which was NOT SELECTED.
So to answer my two questions in my original post:
"Am I using the Text property of the Listbox control incorrectly?" -- The answer is YES.
"Or is this a bug?" -- Yes, it is.

C# DataGridView: Selected Row always returns First Row (Regardless of Selection)

I have a DataGridView in which the User selects a Row, and presses a Button which acts based off of the Selected Row.
Currently, I am trying to get the ID (First Column) of the Selected Row using the following method:
int id = (int) DataGrid_Contact.SelectedRow[0].Cells[0].Value;
I have tried other methods, such as dgv.CurrentRow, dgv.SelectedCells, etc. Everything always points to either the First Row, or the First Cell (0, 0). Regardless of my selection, I cannot get this to change.
The notable properties of the DataGridView are:
MultiSelect = false;
ReadOnly = true;
SelectMode = FullRowSelect;
Everything else is either unrelated to Selection and/or set to their default values.
In case it matters, I am populating the DataGridView with an SQL Command, and setting the DataSource of the DataGridView. I've tried this.BindingContext[DataGridView dgv.DataSource].EndCurrentEdit() to no avail.
Lastly, I'm using Microsoft Visual C# 2008 Express Edition and Microsoft SQL Server 2008.
after analysing your code i have observed following mistakes from your code:
1.you are directly casting the object value to int :
Solution: here you need an explicit cast.
2.you are trying to get the selected Row items using following statement:
DataGrid_Contact.SelectedRow[0].Cells[0].Value;
actually above statement won't be compiled as there is no SelectedRow[int] Collection.instead of that you should use SelectedRows[int] Collection as below:
DataGrid_Contact.SelectedRows[0].Cells[0].Value;
3.from your properties it is clear that you have disabled the MultiRowSelect so there is no point of getting data from multiple rows.
Final Solution:
Replace this :
int id = (int) DataGrid_Contact.SelectedRow[0].Cells[0].Value;
With following:
int id = Convert.ToInt32(DataGrid_Contact.SelectedRows[0].Cells[0].Value.ToString().Trim());
You should be able to pull the index of the selected row and then use the original structure to get the proper element.
objList[yourGrid.SelectedIndex]
I figured all of this out.
First of all, there was a typo. SelectedRow should have been SelectedRows.
Also, my cast worked just fine.
Lastly, the issue is that I had set the menu to be invisible before grabbing my selected data. For whatever reason, when the window is invisible the selection defaults to 0, 0 rather than staying at its previous value.

System.Web.HttpException: Cannot have multiple items selected in a DropDownList

During page load, index 0 was already selected. Then this code statement selected index 1:
dropDownList.Items.FindByValue(myValue).Selected = true;
// assume myValue is found at index 1 of dropDownList.Items
On completion of page load, the page reads: "System.Web.HttpException: Cannot have multiple items selected in a DropDownList."
Why did I get the exception? And how can I fix it?
I noticed that both index 0 and index 1 had the properties "Selected" set to true (dropDownList.Items[0].Selected and dropDownList.Items[1].Selected both were true). However, dropDownList.SelectedIndex was still 0, even though index 1 was set most recently.
I tried resolving this by clearing the list selection beforehand.
dropDownList.ClearSelection();
dropDownList.Items.FindByValue(myValue).Selected = true;
But that didn't help. Same exception occurred.
What did help, was setting the selected value another way:
dropDownList.SelectedIndex = dropDownList.Items.IndexOf(dropDownList.Items.FindByValue(myValue));
Now the selection change propogates throughout the list.
So, don't use dropDownList.Items[x].Selected = true/false to change the selected value of a DropDownList. Instead, use dropDownList.SelectedIndex = x;
I just had this problem, and found out it was caused by something different. I was adding the same ListItem instance to multiple dropdowns:
ListItem item = new ListItem("Foo", "1");
ListItem item2 = new ListItem("Bar", "2");
ddl1.Items.Add(item);
ddl2.Items.Add(item);
ddl1.Items.Add(item2);
ddl2.Items.Add(item2);
Then setting the SelectedValue:
ddl1.SelectedValue = "1"; //sets the Selected property of item
ddl2.SelectedValue = "2"; //sets the Selected property of item2
Switching to adding separate instances of ListItem fixed the problem.
My guess is that when you set the SelectedValue of the DropDownList, it sets the Selected property on the appropriate ListItem in its Items collection. So in this case, at the end of the second code block, both items are selected in both dropdowns.
I had a similar problem but under a slightly different scenario. I thought I should post it and the resolution here as it may help someone save time if they happen to be in my similar scenario.
First the error message:
AMError: Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException:
Cannot have multiple items selected in a DropDownList.
My Scenario:
I was using using VisualStudio 2010 to step through the application (ASP VB Net) when I encountered the problem. I looked over the 2 dropdownlists on the page, checked the internet and wasted several hours w/o any resolution.
Resolution:
Then I got feedup and exited VS 2010 and took a break. When I came back. I reran the application and there was no problem. That's when I realized my costly mistake: I had setup an expression that set the
SelectedValue in the Debugger Watch Window! Hence the multiplicity!
I removed the expression and all was well again --- Visual Studion 2010 able to get past the dropdownlist section onto the another area of focus of the application.

How do I prevent selectedValue altering when calling tableAdapter's Fill() method?

I have bound my ListBox to some data.
The problem is when I call myTableAdapter.Fill(..) method, SelectedValue changes to whatever is the first item ID in the list. Although "Selected Value" in VS is not bound anywhere (see image).
alt text http://img370.imageshack.us/img370/2548/ss20090108212745qz2.png
How do I prevent this behaviour, please?
Thank you very much for helping.
You shouldn't be binding on each request. If you absolutely have to bind on each request for some reason you have to set SelectedIndex on the ListBox manually. This is because the Fill method first clears the list then creates new list items for the fetched data.
The simplest way I can think of is to change your table adapter fill code to something like this:
string preSelected = myDropDownList.SelectedValue;
myTableAdapter.Fill(myDataTable);
myDropDownList.SelectedValue = preSelected;
You will run into an issue if the item doesn't exist anymore, so you may want to add a condition to check for that.

Categories