Setting dropdownlist values from selected value - c#

I have a dropdownlist which contains some values such as "Hot water" and "Electricity" in C# ASP.Net. What I would like to do is if the user selects one of these values and clicks on a button, then it would set the values of a second dropdownlist to certain values. e.g. if "Hot Water" was chosen and next was clicked then the values in dropdownlist2 would be "Radiator" and "Heating controls". But if "Electricity" was chosen then the values in dropdownlist2 would be "No Power" and "Sockets". My code so far:
protected void NextButton1_Click(object sender, EventArgs e)
{
option1 = DropDownList1.SelectedValue.ToString();
TextBox1.Text = option1;
DropDownList2.Visible = true;
if (DropDownList1.SelectedValue == "Hot Water")
{
DropDownList2.SelectedValue = "Heating controls";
DropDownList2.SelectedValue = "Underfloor Heating";
}
}

I hope I understood you with the following:
if(DropDownList1.SelectedValue == "Hot Water"){
DropDownList2.Items.Clear();
DropDownList2.Items.Add("Radiator");
DropDownList2.Items.Add("Heating Controls");
}
if(DropDownList1.SelectedValue == "Electricity"){
// Do the same like above but for the values in Electricity
}

Don't think you can multi-select in a dropdown list so use a asp:ListControl or asp:CheckBoxList instead.
If you want a dropdown multiselect there are plenty of JS controls that will do that for you.
eg: https://harvesthq.github.io/chosen/
Once you update your code for a list than everything should work fine.

First check whether the Hot Water or Electricity is selected in the dropdownlist1 in Nextclick button code like this.
if(dropdownlist1.SelectedValue == "Hot Water")
{
drodownlist2.Items.Add(new ListItem("Radiator","Radiator")); //First parameter take datatextfield and second parameter take datavaluefield.
drodownlist2.Items.Add(new ListItem("Heating Controls","Heating Controls"));
}
else
{
drodownlist2.Items.Add(new ListItem("No Power","No Power"));
drodownlist2.Items.Add(new ListItem ("Sockets","Sockets"));
}

Related

c# ComboBox prevent selecting item after dropdown

I have a specific problem with a combobox in visual studio.
I use it to let the user type text in the textbox part of the combobox which immediately starts a SQL requst.
The result should be displayed in the dropdownlist part of the combobox.
(DropDownStyle is set to DropDown)
private void UpdateParent(object sender, EventArgs e)
{
ParentListChange(); //Update the listitems
//prevent from opening at the beginning
if (!ParentSelect.Text.Trim().Equals(""))
{
//my problem
ParentSelect.DroppedDown = true;
Cursor.Current = Cursors.Default;
}
}
But as soon as the drop down opens the first item gets selected and the whole text of it will paste into the textbox.
So if you start to write more then one letter in a row the first one "disappears" because the second typed letter replaces the selected text.
I know there is a similar post but the answeres did not help since they would be to slow (user would have to wait for about a second to type on):
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
var savedText = comboBox1.Text;
comboBox1.DroppedDown = true;
comboBox1.Text = savedText;
comboBox1.Select(savedText.Length, 0);
}
Or would not worke with opening the drop down list, which is essential:
comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
Is there a way to just disable the "select first item" thing?
One way to achieve is to have custom user control.
You can have a TextBox overlapping your ComboBox.
So, user will be interacting with Textbox only, and as per text entered in TextBox(using appropriate Event - key press will be fine), you can query in database and load ComboBox with the result of query.

Drop Down Control Selected Index change event

In my webfrom in asp.net I have a grid view a button, a text box and a Dropdownlist.
I have a method like this to call and select the data in to my grid view.
public void fillGridByAuthor(string searchKey)
{
GVDetails.DataSource = new ViewAllBKByAuthorOP().searchAuthorByAUNM(searchKey);
GVDetails.DataBind();
}
This is my business layer method.
public DataTable searchAuthorByAUNM(string searchKey)
{
string query2 = "EXEC SelectBooksDTByAuthor'" + searchKey + "'";
return new DataAccessLayer().executeTable(query2);
}
I'm calling fillGridByAuthor method in form in the drop downlist selected index change event like this.
protected void DDAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
fillGridByAuthor(DDAuthor.Text);
}
and in the button click event like this
protected void btnSearch_Click(object sender, EventArgs e)
{
fillGridByAuthor(txtAuName.Text);
}
It is working fine when the button is clicked. Though I select the same Item in the drop down list, it doesn't give me the same output.
What's incorrect here?
From MSDN:
The Text property gets and sets the same value that the SelectedValue
property does. The SelectedValue property is commonly used to
determine the value of the selected item in the ListControl control.
If no item is selected, an empty string ("") is returned.
So the Text property returns the Value not the Text property of the currently selected item. Use SelectedItem.Text instead.
fillGridByAuthor(DDAuthor.SelectedItem.Text);
Just set AutoPostBack property of your dropdownlist to true and it will work like a charm.
Try adding autopostback = true to your dropdownlist. It will probably help
And, you should do this:
fillGridByAuthor(DDAuthor.SelectedValue);
EDIT
what Tim Schmelter is probably better because you want the text so:
fillGridByAuthor(DDAuthor.SelectedItem.Text);

Validating if a combobox it's SelectedText property is empty always fails

Simple problem: I am checking to see if a combobox has had an item selected with string.IsNullOrEmpty(). Problem is, even if is is selected, the error message appears. What am I doing wrong?
Here is my code:
private void button1Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(comboBox1.SelectedText))//here should skip to else - but doesn't
{
MessageBox.Show("You must select a conversion type", "Error");
}
else
{
if (comboBox1.SelectedText == "Currency")
{
double input = Convert.ToDouble(textBox1.Text);
if (!string.IsNullOrEmpty(comboBox2.SelectedText))
{
string type = comboBox2.SelectedText;
double result = convertCurrency(type, input);
if (result != -1)
{
label1.Text = Convert.ToString(result);
}
}
else
{
MessageBox.Show("You must select a conversion type", "Error");
}
}
else
{
MessageBox.Show("curency");
}
}
}
Note: This is my second ever C# program - so please don't yell at me if I'm being stupid.
Generally a few observations/suggestions.
First you're using string values and are basing logic on these values, you might want to look into using an Enum and binding all it's values to the combo box. Then use the SelectedItem property and compare it to the Enum.
When nothing is selected the SelectedItem will return NULL, another option is using SelectedIndex which will return -1 when no item has been selected.
So with the SelectedIndex it would become something like;
if (comboBox1.SelectedIndex == -1)//Nothing selected
{
MessageBox.Show("You must select a conversion type", "Error");
}
else
{
//Do Magic
}
Generally using string comparisons should only be done when anything "strong" like an int comparison or even better an enum comparison is not possible. (Maybe it's just me though but strings change to often and are just scary for this sort of stuff.)
For the enum suggestion possibly look at one of these links;
Binding an enum to a WinForms combo box, and then setting it
Load values of enum type into a combobox
Is it possible to load items from an Enum to a ComboBox in .NET 3.5?
Binding a ComboBox to an Enumeration
I'm not sure which .NET version and things you're using as binding is alot easier in WPF then in the old windows form (in my opinion).
from the MSDN doc, this answers your question exactly
You can use the SelectedText property to retrieve or change the
currently selected text in a ComboBox control. However, you should be
aware that the selection can change automatically because of user
interaction. For example, if you retrieve the SelectedText value in a
button Click event handler, the value will be an empty string. This is
because the selection is automatically cleared when the input focus
moves from the combo box to the button.
private void button2_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex==-1)
{
MessageBox.Show("You must select a conversion type", "Error");
}
else
{
MessageBox.Show("Selected");
}
}
Another solution:
You can check whether the combobox has had an item selected by checking a condition with an Index which is out of range (which item is impossible to have), then, if it is not having a possible value, you can set it manually.
if (comboBox1.SelectedIndex == -1) //index out of range
{
//show the error message
comboBox1.SelectedIndex = 1; //set the first value to the combo box
}
else
{
//continue
}
Poor naming on microsoft's part. You should use comboBox.Text to get what you are looking for.
comboBox.SelectedIndex the index of the selected value
comboBox.SelectedItem if you using a DataSource, this is the item seleted in the datasource
comboBox.SelectedValuethe ValueMember of the Datasource or the currently selected value if you added your own Items
comboBox.Text The text that you see, even if it is not in the list
.SelectedText, refers to and text selected (highlighted) within the .Text
private void Resetbtn_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
//Student is a combobox elements.Add again.
comboBox1.Items.Add("Student");
comboBox1.Items.Add("Staff");
}

Dropdownlist first value display "choose"

I want that my dropdownlist display first value: "-choose car-"
I succeed at this way:
protected void ddl1_DataBound(object sender, EventArgs e)
{
Convert.ToInt32(ddl1.SelectedValue);
ddl1.Items.Insert(0, new ListItem("-Choose car-", "-Choose car-" ));
}
and that's ok,the "-choose-" is in the first place but the problem now is that if I have values,for example,the dropdownlist show like that:
-Choose car-
Subaro
Fiat
Honda
The first value that display when I'm enter to the site is the Subaro,and to see the -choose car- the user need to open the dropdownlist and then he will see the -choose car- at the first place.How can I do that from the start,from the page load - the -choose car- will display at the ddl from the page load.Where I wrong at the code ?
I tried the itemlist with AppendDataBoundItems = "true" but I got an error, and when I succeed,the problem is the same like I said before.
You were on the right track with using the AppendDataBoundItems property, it should be set to true if you're databinding the list.
Your markup should look like this
<asp:DropDownList runat="server" ID="ddl1" AppendDataBoundItems="true">
<asp:ListItem Text="-Choose car-" />
</asp:DropDownList>
and your code behind probably already looks something like this
ddl1.DataSource = [your datasource goes here];
ddl1.DataBind();
This will place the Choose car text as the first option in the drop-down list and append the rest of the options below it.
Now for the more interesting part of why you were seeing the behavior you were seeing (first item not being selected). If you look at the implementation of SelectedIndex using a tool like JustDecompile (not affiliated with Telerik, just happen to use their tool) you'll see code that looks like this:
public int SelectedIndex
{
get
{
int num = 0;
num++;
while (num < this.Items.Count)
{
if (this.Items[num].Selected)
{
return num;
}
}
return -1;
}
set
{
// stuff you don't care about
this.ClearSelection();
if (value >= 0)
{
this.Items[value].Selected = true;
}
// more stuff you don't care about
}
}
As you can see, the index isn't stored anywhere, it's computed every time based on which item has the Selected property set to true. When you set the SelectedIndex to 0 in the markup and databind your datasource, it will select the 0th item in that list, in your case Subaro. When you insert a new item at the beginning of the list, Subaro is still marked as the selected item, which is why when the page loads, you see that selected and not Choose car. If you want to mark Choose car as the selected item using code, you will have to do it after you data databind your dropdown. Please note, this is just an implementation detail of how DropdownList works. It could change in future version of ASP.NET so do not write code that relies on it working this way.
Make sure that you bind the data source and insert you "-choose care-" item first before selected he first item
make sure when you insert your 1st item "-Choose car-" you make it once not on each PostBack. Check if not IsPostBack to add the 1st item.
EDIT:
Example:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ddl1.Items.Insert(0, new ListItem("-Choose car-", "-Choose car-" ));
}
ddl1.SelectedIndex = 0;
}
You should do ddl1.Items.Insert(0, new ListItem("-Choose car-", "-Choose car-")); first, and than ddl1.SelectedIndex = 0
private void FillCar()
{
DataTable dt = GetCar();
ddl1.Items.Clear();
ddl1.DataSource = dt;
ddl1.DataTextField = "carName"; // field name in the database
ddl1.DataValueField = "CarNum"; // field name in the database
ddl1.DataBind();
ListItem li = new ListItem();
li.Text = "--Choose car--";
li.Value = "-1";
ddl1.Items.Insert(0, li);
ddl1.SelectedIndex = 0;
}
I use method like this and call it in the page load in if (!IsPostBack){}.

DropdownList.selectedIndex always 0 (yes, I do have !isPostBack)

(Scroll down to bottom of post to find solution.)
Got a asp.net page which contains a
Datalist. Inside this datalist, there
is a template containing a
dropdownlist and each time the
datalist is filled with an item, a
ItemCreatedCommand is called. The
itemCreatedCommand is responsible for
databinding the dropdownlist.
I think the problem lies here, that
I'm using ItemCreatedCommand to
populate it - but the strange things
is that if I choose the color "green",
the page will autopostback, and I will
see that the dropdown is still on the
color green, but when trying to use
it's SelectedIndex, I always get 0...
protected void DataListProducts_ItemCreatedCommand(object
source, DataListItemEventArgs e)
var itemId = (String)DataListProducts.DataKeys[e.Item.ItemIndex];
var item = itemBLL.GetFullItem(itemId);
var DropDownListColor = (DropDownList)e.Item.FindControl("DropDownListColor");
//Also tried with :
//if(!isPostBack) {
DropDownListColor.DataSource = item.ColorList;
DropDownList.Color.Databind();
// } End !isPostBack)
Label1.test = DropDownListColor.SelectedIndex.toString();
// <- THIS IS ALWAYS 0! *grr*
I've narrowed down the code a bit for
viewing, but still you can see what
I'm trying to do :) The reason for
why I'm doing this, and not declaring
the datasource for the colors directly
i aspx-page, is that I need to run a
test if(showColors), but I do not want
to clutter up the html-page with code
that I feel should be in the code
behind-file.
EDIT: After trying to alter
SelectedIndexChange - I'm having a
"logical" confusion in my head now -
how am I to alter elements inside the
datalist? Since, as far as I know - I
do not have any way to check which of
the items in the datalist this
particular dropdownlist belongs to...
Or? I'm going to try out a few ways
and see what I end up with ;) But do
please post your thoughts on this
question :)
SOLUTION:
Either bubble the event to ItemCommand, or Handle the event, get the senders parent(which is a datalistItem and manipulate elements in there.
protected void DropDownListColor_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
var item = items[dataListItem.ItemIndex];
var color = item.ItemColor[dropDownListColor.SelectedIndex];
var LabelPrice = (Label)dataListItem.FindControl("LabelPrice");
LabelPrice.Text = color.Price;
}
When the DataList is data-bound, the AutoPostBack has not been handled yet, i.e. the values in the ItemCreated event are still the original values.
You need to handle the SelectedIndexChange event of the dropdown control.
Regarding your 2nd question:
I suggest you remove the AutoPostBack from the dropdown, add an "Update" button, and update the data in the button Click event.
The button can hold Command and CommandArgument values, so it's easy to associate with a database record.
some MSDN links with C# examples on bubbling
http://msdn.microsoft.com/en-us/library/system.web.ui.control.onbubbleevent.aspx
http://msdn.microsoft.com/en-us/library/aa719644(VS.71).aspx
http://msdn.microsoft.com/en-us/library/aa720044(VS.71).aspx
Thank You for your solution
protected void ddlOnSelectedIndexChanged(object sender, EventArgs e) {
try {
ModalPopupExtender1.Show();
if (ViewState["Colors"] != null) {
FillColors(ViewState["Colors"].ToString());
}
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
Image image = (Image)dataListItem.FindControl("mdlImage");
Label ProductCode = (Label)dataListItem.FindControl("lblprdCode");
Label ProductName = (Label)dataListItem.FindControl("lblProdName");
DropDownList ddlQuantity = (DropDownList)dataListItem.FindControl("ddlQuantity");
Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
Label TotalPrice = (Label)dataListItem.FindControl("lblTotPrice");
//Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
} catch (Exception ex) {
}
}

Categories