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));
Related
I am trying to bind a List of string to a Dropdown.
On frontend, I am able to see the list of dropdown correctly but when I select a value and click on search, it throws a null reference exception because it seems like it is read only. This is what I tried:
<asp:DropDownList runat="server" ID="ddl" AppendDataBoundItems="True">
<asp:ListItem Value="">Please Select</asp:ListItem></asp:DropDownList>
Code behind:
List<string> items = helper.GetData(); //A method that simply returns a list of strings.
ddl.DataSource = items;
ddl.DataBind();
protected void searchClick(object sender, EventArgs e){
/*This is null and when I inspect this, I don't see any value matching
the string selected in dropdown.*/
var selectedOption = ddl.SelectedItem.Text;
}
I tried every possible solution online. I even tried converting it to a dictionary just like it has been given here.
I also tried converting it into an object assigning it a title and an ID property as given here
Thank you.
You have bind list in dropdownlist but has not append which value has to be fetched when any value got selected.
If(!isPostBack())
{
ddl.DataSource = items;
ddl.DataTextField = "Field name which hold items(Text to be shown in ddl)";
ddl.DataValueField = "ID of items(Value for items)";
ddl.DataBind();
}
If have only list and have to append in dropdown list then use bleow code.
List<string> items=helper.GetData();
for(var i=0; i < items.Count; i++)
{
ddl.Items.Add(new ListItem(i, items[i]));
//ddl.Items.Add(new ListItem(key, source)); For reference only
}
To get value you can use:
ddl.SelectedItem.Value;
ddl.SelectedItem.Text;
Having a look at this I notice 2 things:
If the first 4 lines are in your page load make sure that you wrap them in a
if(!isPostBack)
{
}
If it is not wrapped in the !isPostBack then the value will default to the first value every time a postback occurs as the ddl wil get rebound each time.
As mentioned above you are not specifying the DataTextField or DataValueField. If these arent specified you will get object types in the dropdownlist instead of values.
Also, consider using ddl.SelectedValue rather than SelectedItem.Text as this will give you the unique ID assigned to the DataValueField
Dictionary<string, string> openWith =
new Dictionary<string, string>();
insted of list you need to use following dropdown
ddl.DataSource = items;
ddl.DataTextField = "Text Which Show In DropDown";
ddl.DataValueField = "value -When Text Is Select From Dropdown";
ddl.DataBind();
I am trying to fetch a field called footer from the Item FooterComponent and want to display.This is the code I have tried but cannot fetch and display.
cs code:
Item footerText=Sitecore.content.Database.GetItem(GUID);
string MyFooter=FooterText["Footer"];
txtFooter.Item = MyFooter;
ascx code:
<sc:fieldrenderer runat="server" id="txtFooter" fieldname="Footer"/>
You should not set a string value of the field to the field renderer. Just set correct item and field name:
Item footerTextItem = Sitecore.content.Database.GetItem(GUID);
txtFooter.Item = footerTextItem;
<sc:fieldrenderer runat="server" id="txtFooter" fieldname="Footer"/>
See more information here: https://sitecoresandbox.com/tag/fieldrenderer/
Also read What's a good way to set the Item or DataSource attribute of a FieldRenderer?
i have two nested drop down list.
one drop down show group,the other show sub group.
i have coded data source of subgroup drop down list on group drop down list selected indexed change event.
What I'm trying to do is set a drop down list to be whatever its value is in the database when editing an entry.
i have used data row.
i have two tables.documentgroup(GroupId,parentId,groupTitle,subGroupTitle) and documents(DocID,GroupID,Title,url)
in my drop down lists i have added list item like this
<asp:ListItem Text = "--select group--" Value = ""></asp:ListItem>
when i click on editing a document,i have this.
protected void grdDocuments_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DoEdit")
{
GC.Collect();
GC.WaitForPendingFinalizers();
int DocID = Convert.ToInt32(e.CommandArgument);
ViewState["DocumentID"] = DocID;
ViewState["EditMode"] = "Edit";
DataTable dtDocuments = DataLayer.Documents.SelectRow(DocID).Tables["Documents"];
if (dtDocuments.Rows.Count != 0)
{
DataRow drDocuments = dtDocuments.Rows[0];
txtDocTitle.Text = drDocuments["DocTitle"].ToString();
txtDocPubYear.Text = drDocuments["DocPubYear"].ToString();
ddlDocGroupTitle.SelectedValue = drDocuments["ParentID"].ToString();
ddlDocSubGroupTitle.SelectedValue = drDocuments["DocGroupID"].ToString();
ViewState["DocCurrentUrl"] = drDocuments["DocUrl"].ToString();
mvDocuments.SetActiveView(vwEdit);
}
}
but i get this error
'ddlDocSubGroupTitle' has a SelectedValue which is invalid because it
does not exist in the list of items. Parameter name: value
and this is the same for ddldocgroupTitle.
i have made an inner join between two tables.
what should i do?
I could not really grasp your question, but it looks like you want to have 2 dropdown, and upon selection in the first, the second gets populated/filtered correct?!?
I recommend that you use javascript/Jquery to do so. Upon page load, issue a ajax get request to fill the "main" dropdown, and upon selection on the first one, you issue a second ajax request to fetch the possible values of the second one...
A alternative is to fetch the items for the first dropdown AND all the values possible for the second, storing the result in some hidden-field data. Then upon selection of the first value, you can only filter + display relevant data.
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();
}
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.