I have detailsview that will be used to edit customer records. Inside this detailsview, I have a dropdownlist that shows list of countries.
I have a table called CountryList that will populate list of countries to the above dropdownlist.
User can edit and save data without any issue.
But, assume that customer record has the country selected as "Australia" and if I delete Australia from the CountryList and try to edit the customer inside the details view, I am getting below error.
SelectedValue which is invalid because it does not exist in the list of items
I know the reason because the
SelectedValue='<%# Bind("Country") %>'
and it can't find it in the list.
So my question is, how to overcome this issue ?
After searching the web, I found that I can override the Databind but I am not sure how to do this. Have no idea how to override and can someone please give me sample code ?
Also is there any other solution for this such as validate it before set ?
Thank you.
you can call function before selecting value as follows:
SelectedValue='<%# CheckCountry(Eval("Country"))%>'
in aspx.cs file create function as follows which will check whether country is exist in list or not if it is not there then will show default value as selected
public string CheckCountry(string country)
{
// add your logic to check contry in list
// and return value as per result if it is exist
// return country name else return default value
}
Try checking the existence of the country in your list(dataTable,DataSet etc) before binding ,some thing like
DataTable dtPs=getAvailableCountries();
string countryName = "Australia";
DataRow foundRow = dtPs.Rows.Find(countryName);
if(foundRow != null) {
//You have it ...
bindTheDropdown();
}else{
//You dont have it ...
dontBindTheDropdown();
}
Related
I have a select list with an id of SelectedEmployee. I have a on change event in jquery where I successfully get the value of the selected item:
$("#SelectedEmployee").change(function () {
selectedEmployee = $("#SelectedEmployee").val();
$("div.myDropDownDiv select").val(selectedEmployee.toString());
alert(selectedEmployee);
myCal.fullCalendar('refetchEvents');
});
My alert returns the value of the selected employee but the DOM still thinks the previous selection is the selected employee. I have tried both the following within the change event with no luck.
$("div.myDropDownDiv select").val(selectedEmployee.toString());
$('#SelectedEmployee option[value=' + selectedEmployee + ']').prop('selected', true)
The first example you gave
$("div.myDropDownDiv select").val(selectedEmployee.toString());
should work...
Here is a Working Example
Maybe you should check if selectedEmployee.toString() is returning the correct value.
Or even if the select is inside a div which has the class myDropDownDiv.
Maybe, myDropDownDiv is an id instead of class
So i am getting this error
{"'drpButton1' has a SelectedValue which is invalid because it does not exist in the list of items.\r\nParameter name: value"}
From everything i can read this is because the DropDownList either had existing items or had a selected index or value which is not in the new databound items.
But the thing is i can GUARANTEE that there are no existing items in the object and i can also say with confidence that there has not been an index selected that could be out of range.
Here is what the DropDownList object looks like directly before the .databind() call.
Here it is directly after the databind() call that has caused all the explosions.
My list object contains 7 items and in particular it contains the item that the databind method randomly decides to pick.
But here is the kicker i literally fill up 8 dropdowns with the EXACT same data and it works on the first dropdown just fine. No idea why the second one explodes.
EDIT: here is the code that does the binding:
Here is a snippet from the load method. the first call succeeds the second one fails but it doesn't fail all the time.
private void LoadShortCodeDropDownData()
{
// Initilization junk to get the resultList to use.
base.LoadListDropDown(drpButton0, (IList)resultList, "DeviceShortCodeIndexID", "DeviceShortCodeName", select);
MessageTextEnabled(drpButton0);
base.LoadListDropDown(drpButton1, (IList)resultList, "DeviceShortCodeIndexID", "DeviceShortCodeName", select);
MessageTextEnabled(drpButton1);
}
protected void LoadListDropDown(DropDownList dropDown, IList list, string valueField, string textField, string insertItem)
{
LoadListDropDown(dropDown, list, valueField, textField);
//dropDown.Items.Insert(0, new ListItem(insertItem, ""));
}
protected void LoadListDropDown(DropDownList dropDown, IList list, string valueField, string textField)
{
dropDown.DataSource = list;
dropDown.DataValueField = valueField;
dropDown.DataTextField = textField;
dropDown.DataBind();
}
EDIT2: I think the real question i have here is how is the databind picking which item to select? I noticed that the first dropdown that gets databound randomly selects the first value in the list while the second one tries to bind to the very last one in the list for some reason.
Is this happening on the first load of the page, or after a postback? Because if it's a postback, you very well could have SelectedIndex == 0 just by default.
I can't guarantee that this will solve the problem, but you could try adding
dropDown.SelectedIndex = -1;
... to the top of your second LoadListDropDown overload.
I've run in to this before, and I dont think you can bind the same list to multiple drop downs.
Sir/madam now my problem is this that I want to filter the Grid View of a page using a Drop Down list and a text box.
I mean to say like we write a SQL such as:
Select * from student where roll_no = 101;
Right,
Now I what that the column (roll_no in above statement) should be selected by the drop down list and the value (101 in the above statement) should be entered by the Text box.
In short I want to populate my grid view using Drop Down list and the value of text box by clicking a button..
For developing i am using dataset and table adapters.
Please, help me for this..
I use a drop-down list (combo-box) and a textbox to filter my DataGridView the following way and I think this is what you are looking for.
First, populate your DataGridView. You state you are using a DataSet and TableAdapters. I am guessing that you are using a BindingSource to tie your Data to your DataGridView. If that is the case, then you can Filter your data via the BindingSource.
My set up is similar to this:
My combobox contains the fields that I want to use in my Filter and the textbox is the value that I will be applying. The values in the combobox are user-friendly names so they will understand which field they are filtering on.
The code to apply the filter is:
private void ApplyFilter()
{
var filterEntered = FilterTextBox.Text.Trim().ToLower();
MyBindingSource.RemoveFilter(); // remove previous filter
string filterText = string.Empty;
string filterComboText = string.Empty;
switch (FilterComboBox.Text)
{
case "Profile":
filterComboText = "TSProfile"; // column name in the query
break;
case "User Id":
filterComboText = "TSUserId";
break;
case "Center":
filterComboText = "TSCenter";
break;
case "Prefix":
filterComboText = "TSPrefix";
break;
}
filterComboText = filterComboText + " = '";
filterText += (string.IsNullOrEmpty(filterComboText) ? string.Empty : filterComboText);
filterText += (!string.IsNullOrEmpty(filterText) && !string.IsNullOrEmpty(filterEntered) ? filterEntered + "'" : string.Empty);
MyBindingSource.Filter = filterText;
}
Basically what it is doing, is getting the text name of the combo-box and then the text in the textbox and applying the Filter to the BindingSource.
MSDN has an article on Filtering thats contains full sample code.
The one thing that I recommend is to provide the user with a way to easily remove the filter, I use a Remove Filter button.
it would be helpful if you showed us a little code first..
you could try something like this tho:
in your codebehind, add items to your dropdownlist.
List<yourObject> list = new List<yourObject>();
foreach (yourObject i in list)
{
DropdownList1.Items.Add(new ListItem("" i.name, "" + i.id));
}
im just giving an example here, i.name could be the name of a certain student, i.id would be the id associated with that given student.
Make sure you have the autopostback attribute of your dropdownlist set to true, like this:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
Then in the selected Index Changed event of your dropdownlist, do the following:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
yourDataControl.DataSource = someMethod(Convert.toInt32(DropDownList1.SelectedValue));
yourDatacontrol.DataBind();
}
as i said, im not entirely sure what you're trying to do or how you're trying to do it.
the way i'm describing, you dont need the textbox to enter a certain value, by selecting an item in the dropdownlist you wil automatically get a value: in this case the ID associated with the selected item in the dropdownlist.
I'm not sure how to correct the following problem. I have dropdown list that has a object data source. Then in the code there is a method like this
void InitPageData()
{
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
DataSet.MemberInfoDataTable dt = da.GetMember((Guid)user.ProviderUserKey);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
//rank.Text = mr.rank;
//position.Text = mr.position;
UserName.Text = user.UserName;
...
}
This method populates form fields on the page. What I'm trying to do is to have the rank dropdown list populated from the ods but use this method above to populate the selected item of the rank dropwon list with the line rank.Text = mr.rank. In this example the the line of code that throws the error is commented out otherwise it throws this: "'rank' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value".
I've chaned the code to rank.DataTextFiled = mr.rank and rank.DataValueField = mr.rankid.ToString() but this threw another error: "DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Star'." "Star" is the value of the mr.rank.
Here is what the dropdown list and the ods look like:
<asp:DropDownList runat="server" ID="rank" CssClass="txtfield" DataSourceID="ODCRanks"
DataTextField="Rank" DataValueField="ID" AppendDataBoundItems="True">
<asp:ListItem Text="--- Select a Rank ---" Value="-1" />
<asp:ObjectDataSource ID="ODCRanks" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetRanks"
TypeName="RanksTableAdapters.RankTableAdapter"></asp:ObjectDataSource>
You should try adding data columns to your data tables (with ID and Rank being the column name) so that the data can be binded to control.
The Text property sets it by value.
See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.text.aspx
You seem to have what will be the text associated with the value and you want to set that as the selected item. I guess this mostly because your value collection is bound to something called ID and I figure a rank of Star isn't an ID.
If Star is what will show up as something in DataTextField, use the items collection FindByText method to select it.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitemcollection.findbytext.aspx
Example
ListItem li = DropDownList1.Items.FindByText("one");
if (li != null) li.Selected = true;
If Star is indeed an ID, then check that the collection is fully loaded before trying to select anything in it.
try something like
rank.SelectedIndex = rank.Items.IndexOf(rank.Items.FindByText(mr.rank));
I am creating an MVC project with a table using the JQGrid plugin. I would like to use a DropDownList to allow the user to specify a value, that will be used in an SQL query to retrieve specific data from the table. I.e. user can select a country from the list, and the table will display items only from that country.
My problem is, that I cannot figure out how to retrieve the selected item from the DropDownList, within my data bind function for my table, within my controller class.
DropDownList in the View
<%= Html.DropDownList("Countries")%>
Setting up the DropdownList in my controller
//dt is a DataTable which holds the values for my list
List<SelectListItem> countries = new List<SelectListItem>();
for (int i = 0; i < dt.Rows.Count; i++)
countries.Add(new SelectListItem { Text = dt.Rows[i][0].ToString(), Value = "" + i });
JsonResult DataBind() method where I would like to access the selected value
public JsonResult Charges_DataRequested()
{
string country = "Dropdownbox Selected Text";
}
The problem seems to be that within a JsonResult function I don't have access to the ViewData or my ViewModel, which always seem to be null when I try and access them. I am very new to MVC and web development, any advice would be very welcome.
Thanks for the answer, it put me on the right track. I realized that the grid also has a postdata parameter. I was able to create a javascript postback function for my dropdownlist, and call the jqGrid 'setGridParam' function to add my dropdownlist text to the grid postdata. I could also trigger a grid reload, and grab the string in my controller Jsonresult function.
The Javascript
$('#Countries').change(function() {
var value = $("#Countries option:selected").text();
$("#ChargesGrid").setGridParam ({
postData:{
selectedCountry:$("#Countries option:selected").text()}
});
$("#ChargesGrid").trigger("reloadGrid");
alert(value);
});
The controller
public JsonResult Charges_DataRequested(string selectedCountry)
{
string country = selectedCountry;
}
jqGrid has got a userdata property where you could store this data so it would be available on post. It may mean you'd have to update this dropdown changes.
jQuery("#GridId").getGridParam('userData').SelectedText
I've only used this the other to set data on loading but think it could work the other way around for you. I would have set the SelectedText above in a controller action when creating the grid json as
userdata = new { SelectedText = "SomeValue" }
The only trouble would be if it were a private set equivalent within the jqGrid code.