Drop Down Control Selected Index change event - c#

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);

Related

How to get asp.net dropdownlist to allow selections

I have a dropdownlist on a webform that I fill from a sql query, I then want to be able to select individual items in the dropdown and have corresponding fields from a datatable fill textboxes on the form
Problem is rowSel is returning 0 and the dropdown won't let me select any other item it always snaps back to the first itenm in the list.
Thought this might have something to do with autopostback being set to true, but if I set it to false that causes otheer problems, Not sure what else to try Im a winforms person and very new to asp.net
protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
{
int rowSel = ddClients.SelectedIndex;
txtClient.Text = dsShow.Rows[rowSel["ClientsTableFieldA"].ToString();
}
It should allow me to select a value from the drop down then populate some textboxes with fields from the datatable.
You could try:
protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
{
txtClient.Text = ddClients.SelectedItem.Value.ToString();
}
protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
{
txtClient.Text = ddClients.SelectedItem.Text;
}
As suggested by B. Seberle
DDL items have fields value and text so it depends how you bound the ddl to SQL datasource.
place break point on txtClient.Text = ddClients.SelectedItem.Text see if item list is empty.
it should not be necessary but you can force a ddClient.databind() in page_load if(!Page.IsPostback).
however ddClients_SelectedIndexChanged will only trigger on postback.

ComboBox.Items.IndexOf returns -1

I have a ComboBox which is populated on Page Load event. Just after populating the ComboBox I call another method which returns a value that I want to make the default value of the ComboBox when Page loads. How can I change the selectedIndex to a value that is returned when I call another method?
XAML for ComboBox
<ComboBox Name="cboProductType" DisplayMemberPath="ProductTypeName" SelectedValuePath="ProductTypeID" SelectedIndex="0"/>
Page Load event:
void OnProductDetailLoad(object sender, RoutedEventArgs e)
{
GetServiceReference.Service1Client service = new GetServiceReference.Service1Client();
service.GetProductDetailsCompleted += service_GetProductDetailsCompleted;
service.GetProductTypeCompleted += service_GetProductTypeCompleted;
service.GetProductTypeAsync();
service.GetProductDetailsAsync(ProductId);
}
Populating ComboBox when Page Loads:
void service_GetProductTypeCompleted(object sender, GetProductTypeCompletedEventArgs e)
{
cboProductType.ItemsSource = e.Result;
}
Calling the other method which returns a particular ProductTypeName. I tried to get the index of that particular ProductTypeName but returns -1 always.
void service_GetProductDetailsCompleted(object sender, GetServiceReference.GetProductDetailsCompletedEventArgs e)
{
if (e.Result.Count != 0)
{
p.ProductID = e.Result[0].ProductID;
int index = cboProductType.Items.IndexOf(e.Result[0].ProductTypeName);
cboProductType.SelectedIndex = index;
}
Also is this a right approach for setting the SelectedIndex property?
Say I have following items loaded in ComboBox in following Index order:
Index DisplayMemberName(ProductTypeName)
0 Color
1 Size
2 Variant
3 N-size
and e.Result[0].ProductTypeName contains Variant so I now want SelectedIndex = 2 of ComboBox
I hope my question is clear
The SelectedIndex is only valid when you manually fill a combobox. If you are using the ItemsSource to fill the items in a combobox, you must define a SelectedValuePath which will then allows you to use the SelectedItem property to SET/GET the selected item. When using binding to a DataContext to bind the controls, the SelectedValuePath should be the property that links the Parent/Child together.

Error on passing data back to Dropdownlist asp .net webform

I have a dropdownlist that cannot be used for editing purpose. When button Edit is clicked inside listview where data exists, data is supposed to pass back to dropdownlist and other textboxes where the form is located outside listview. Passing data back to textboxes is ok. The problem is dropdownlist data that I want to edit was added to dropdownlist as another record. Please take a loot at picture, and I have to reselect the correct one. Otherwise, that selected data (e.g. December in picture) has no datavaluefield and it stops running if I didn't choose bottom December and click Update button. Here is my code for dropdownlist for months. Any help is appreciated for this. Thank you.
public void BindMonth()
{
ddlStartMonth.DataSource = objUIHelpers.GetAllMonths();
ddlStartMonth.DataTextField = "StartMonthName";
ddlStartMonth.DataValueField = "MonthId";
ddlStartMonth.DataBind();
ddlStartMonth.Items.Insert(0, "Select Start Month");}
Then, I put this method in page load like this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindMonth();
}
}
This is listview data item editing
protected void lvEducation_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
//Delete Method will be fired when command name "Delete" inside Listview is clicked.
case ("Delete"):
int EducationId = Convert.ToInt32(e.CommandArgument);//pass Id of Experience to identify datarow to delete
// DeleteEducationById(ExperienceId);//Call bind to delete method and pass ExperienceId as argument
break;
//Edit Method will fired when command name "Edit" inside Listview is clicked.
case ("Edit"):
EducationId = Convert.ToInt32(e.CommandArgument); //pass Id of Experience to identify datarow to edit
BindEducationDataToEdit(EducationId);//Call bind to edit method and pass ExperienceId as argument
break;
}}
This is part of method that triggers to pass back data to edit.
public void BindEducationDataToEdit(int EducationId)
{
Education edu = objJFUserBAL.GetEducationByIdToEdit(EducationId);
txtAdditionalInfo.Text = edu.AdditionalInfo.ToString();
ddlEndMonth.SelectedItem.Text = edu.mo.EndMonthName;
}
When selected data is posted back for editing, I have extra data like this.
You should not be updating the SelectedItem.Text. This is changing the displayed text. Instead you should be updating which item is selected.
If you do not have access to the value of the month name, you can do the following:
ddlEndMonth.Items.FindByText(edu.mo.EndMonthName).Selected = true;
which will select the item with the month text assuming one exists.
If it is possible to have an edu.mo.EndMonthName which does not exist in the list of items, you will want to do some checks for null and treat accordingly.
You have to fill a list manually, because auto binding is not going to let you put a "select your month" item unless you have one in your data base :
public void BindMonth()
{
List<Month> listOfMonth = new List<Month>();
Month fakeMonth = new Month();
// you need to see your own
//code and try to make a fake month with these parameters you want
fakeMonth.StartMonthName = "Select Start Month";
fakeMonth.MonthId = 0;
listOfmounth.Add(fakeMonth);
foreach(Month m in objUIHelpers.GetAllMonths())
{
listOfMonth.Add(m)
}
ddlStartMonth.DataSource = listOfMonth;
ddlStartMonth.DataTextField = "StartMonthName";
ddlStartMonth.DataValueField = "MonthId";
ddlStartMonth.DataBind();
ddlStartMonth.Items.Insert(0, "Select Start Month");}
}

Dropdown List not returning the correct value

i am trying to retrieve the value on a previously databinded DropDownList like this:
<asp:DropDownList ID="DropDownListReception" runat="server" CssClass="span3 drop-down-reception"
OnPreRender="DropDownListReception_PreRender" OnSelectedIndexChanged="DropDownListReception_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
var receptions = BLLFactory.ReceptionBLL.GetListAll();
DropDownListReception.DataSource = receptions;
DropDownListReception.DataBind();
}
On the DropDown PreRender i am personalizing this DropDown like this:
protected void DropDownListReception_PreRender(object sender, EventArgs e)
{
if (DropDownListReception.DataSource != null)
{
DropDownListReception.Items.Clear();
DropDownListReception.Items.Add(new ListItem("-- Select --", "NA"));
foreach (Reception item in (DropDownListReception.DataSource as IEnumerable))
{
DropDownListReception.Items.Add(new ListItem(item.Name + " " + item.Number, item.Id.ToString()));
}
}
}
this is working perfectly, my DropDown loads as it should, my problem is when i try to retrieve the SelectedValue in the SelectedIndexChanged event, it wont return the value as a string but as a type, what i am doing is:
protected void DropDownListReception_SelectedIndexChanged(object sender, EventArgs e)
{
//CurrentReception is a string i want to save in ViewState
//I also tried (sender as DropDownList).SelectedValue
//Tried DropDownListReception.SelectedValue
CurrentReception = DropDownListReception.SelectedItem.Value;
}
but this "DropDownListReception.SelectedItem.Value" will always return "Reception" which is the type of the item, not the id i assigned as the item value in the PreRender event. This also happens if i do this: "DropDownListReception.SelectedItem.Text", this also return "Reception". How can i return the string Value i assigned to the DropDown item?
var CurrentReception = DropDownListReception.SelectedItem as Reception;
string val = CurrentReception.PropertyYouNeed;
DropDownListReception.SelectedItem.Text and DropDownListReception.SelectedItem.Value will return the value of the selection, which is the second term in the ListItem used when you add it to the list. In other words, the problem is with item.Id.ToString(). It returns the type of the object instead of the ID. I'm not sure what your item object actually consists of so I'm not sure what you actually need, but are you sure it's not just item.Id? ToString() is generally the string representation of the object, if item.Id is an int, then ToString should give you the string equivalent of that int... but the fact that it doesn't work suggests item.Id is not actually an int.
I think you need to cast the list item to the type that you stored in it (Reception), then access the property from the Reception object that you want (from your description it sounds like you want the id). Like this:
protected void DropDownListReception_SelectedIndexChanged(object sender, EventArgs e)
{
//CurrentReception is a string i want to save in ViewState
CurentReception = ((Reception)DropDownListReception.SelectedItem).Id.ToString();
}
I figured it out, i was DataBinding the DropDownList on the PageLoad, which fires before the SelectedIndexChanged event. Since the DropDown does a PostBack when its value changes, the PageLoad was "Recreating" the DropDown and i was losing the changes before getting to the SelectedIndexChanged code.
Thank you all for your answers.:)

C# ComboBox in DropDownList style, how do I set the text?

I want to use a ComboBox with the DropDownList style (the one that makes it look like a button so you can't enter a value) to insert a value into a text box. I want the combobox to have a text label called 'Wildcards' and as I select a wildcard from the list the selected value is inserted in to a text box and the combobox text remains 'Wildcard'. My first problem is I can't seem to set a text value when the combobox is in DropDownList style. Using the properties pallet doesn't work the text value is simply cleared when you click off, adding comboBox.Text = "Wildcards"; to form_load doesn't work either. Can anyone help?
The code you specify:
comboBox.Text = "Wildcards";
...should work. The only reason it would not is that the text you specify is not an item within the comboBox's item list. When using the DropDownList style, you can only set Text to values that actually appear in the list.
If it is the case that you are trying to set the text to Wildcards and that item does not appear in the list, and an alternative solution is not acceptable, you may have to be a bit dirty with the code and add an item temporarily that is removed when the drop-down list is expanded.
For example, if you have a form containing a combobox named "comboBox1" with some items and a button named "button1" you could do something like this:
private void button1_Click(object sender, EventArgs e)
{
if (!comboBox1.Items.Contains("Wildcards"))
{
comboBox1.Items.Add("Wildcards");
}
comboBox1.Text = "Wildcards";
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
if (comboBox1.Items.Contains("Wildcards"))
comboBox1.Items.Remove("Wildcards");
}
That's pretty quick and dirty but by capturing the DropDownClosed event too you could clean it up a bit, adding the "Wildcards" item back as needed.
You can select one of items on formload or in form constructor:
public MyForm()
{
InitializeComponent();
comboBox.SelectedIndex = 0;
}
or
private void MyForm_Load(object sender, EventArgs e)
{
comboBox.SelectedIndex = 0;
}
Try this
comboBox1.SelectedValue = "Wildcards";
This may be a possible solution:
comboBox1.SelectedValue = comboBox1.Items.FindByText("Wildcards").Value;

Categories