I have a databound Listbox with Multiselect enabled. On page load, I feed the information from a GridView column and select all the options that match, using this code:
string[] separators = { "<br />" };
String Departments = Session["ProjDept"].ToString();
string[] splitDepartments = Departments.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (var dept in splitDepartments)
{
listDepartment.SelectedIndex = listDepartment.Items.IndexOf(listDepartment.Items.FindByText(dept));
}
However, I am running into a strange issue: when there is only one department in the GridView column, the option in the listbox gets properly selected, but when there's multiple departments only the LAST department gets selected.
I've ran System.Diagnostics.Debug.Print(dept) within my foreach to ensure that all the values are getting passed and they all appear in the STDOUT, but the listbox still won't cooperate.
Any ideas as to how I can fix this -- or alternatively, what other code could I use to achieve the same results?
Thank you!
The SelectedIndex property only allows one value at a time, so you're resetting it with each iteration. That's why only the last one is being selected. You need to access the "Selected" property from the ListItem itself.
Without trying it myself, it should look something like:
foreach (var dept in splitDepartments)
{
int index = listDepartment.Items.IndexOf(listDepartment.Items.FindByText(dept));
listDepartment.Items[index].Selected = true;
}
As long as you do have SelectionMode="Multiple" - that code should work.
Related
I am using a Listbox on my windows application. The listbox has a multi-selection option, which users select all the roles the new user will have.
My Listbox is bound to a dataset. The table is Roles, with an ID column and Description column.
When I bound the listbox, I chose the data source being the dataset, the display member to be the description, the value member being the ID and the selected value being the dataset - roles.frolesid
Now when i loop through the listbox's selecteditems, i get only the first item's values etc...
I am trying to assign an int to the current selectedvalue, to get the ID to give to the user.
int num = 0;
foreach (var item2 in lstRoles.SelectedItems)
{
num = Convert.ToInt32(lstRoles.SelectedValue);
}
So if I select 3 roles, for instance Administrator, Capturer and Assessor, I only see the Administrator value.
How do I loop and access the next item? I'm not even using
item2
in my code. Could this be utilised?
For instance:
First iteration:
And it just stays on that selected item, never moving to the next item.
To get list of selected values when the data source is a DataTable, you can use this code:
var selectedValues = listBox1.SelectedItems.Cast<DataRowView>()
.Select(dr => (int)(dr[listBox1.ValueMember]))
.ToList();
But in general Item of a ListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember.
If you are looking for a good solution which works with different settings and different data sources, you may find this post helpful. It contains an extension method which returns value of an item. It works like GetItemText method of ListBox.
solved it
int num = 0;
int count = fRoleIDs.Count;
while (num != count)
{
var item = lstRoles.Items[num] as System.Data.DataRowView;
int id = Convert.ToInt32(item.Row.ItemArray[0]);
num += 1;
}
This goes into the listbox's items and according to the index, gets the item as a Row. This then gets me the itemarray, which is ID and Description {0,1}
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 tried so many articles around, like below to get my task done, but didn't work as I always ends up with an NullReferenceException, I have bound a database table column to the Dropdown list, on page load i want to select an item based on the value from database which is one of those listed items. Please help me.
txt_examtype.DataSource = dt;//txt_examtype is the dropdownlist
txt_examtype.DataTextField = "ExamTypeName";
txt_examtype.DataValueField = "ExamTypeName";
txt_examtype.DataBind();
String examtype = dt.Rows[0]["ExamType"].ToString().Trim();
ListItem myitem = txt_examtype.Items.FindByValue(examtype);
txt_examtype.SelectedValue = myitem.Value;
try this code
txt_examtype.SelectedValue = dt.Rows[0]["ExamType"].ToString()
You should set SelectedIndex instead of SelectedValue. This is safe to use:
txt_examtype.SelectedIndex = txt_examtype.Items.IndexOf(txt_examtype.Items.FindByValue(examtype));
I have a drop down list control populated with items and some code to take the currently selected item value. The problem is I only get the value of the first item in the list regardless of what item is actually selected.
Here is my code to populate the drop down:
protected void displayCreateCategories()
{
StoreDataContext db = new StoreDataContext();
var a = from c in db.Categories
orderby c.Name
select new{catName= c.Name,
catId=c.CategoryID};
ddlCategory.DataSource = a;
ddlCategory.DataTextField = "catName";
ddlCategory.DataValueField = "catId";
ddlCategory.DataBind();
}
To get the value of the currently selected item which in my case is always of type integer I do label1.text=Convert.toInt32(ddlCategory.SelectedValue);
I get the selected value, but it is always for the 1st item in the list. I'm pulling my hair out over this. :(
I suspect you're running the list loading code every time the page loads, which is destroying the list, repopulating the list, and auto-selecting the first item before your selection retrieval code gets run.
Use this construction in Page_Load:
if (!IsPostBack)
{
// Initial control population goes here
}
Data binding will reset the control's selected value so make sure you retrieve the selected value before data binding on postback.
Hi I am developing using the SharePoint namespace and I ran into the following error when I try to retrieve a Title field from the list items.
Value does not fall within the expected range
I know however that the field exists because I printed out all the fields.
string value = (string)listItem[listItem.Fields["Title"].Id];
Console.WriteLine("Title = " + value);
Update: To what extent does the View that was used to retrieve the list items play a role in what fields will be available? This code fails with the same exception:
SPListItemCollection items = list.GetItems(list.DefaultView);
foreach (SPListItem listItem in items)
{
try
{
Console.WriteLine("Title = " + listItem.Title);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
In both cases the list.DefaultView property was used to retrieve the list items.
I don't know if your error is solved or not. But I was facing the same issue and I found the solution to the problem.
You have to go to:
Central Administration > Application Management > Manage Web Applications
select the Web Application in use and choose:
“General Settings > Resource Throttling” via the Ribbon.
In that scroll down and look for "List View Lookup Threshold" in that by default value is 8 increase the value till the error is gone.
Reference Link
I had this issue because the column was not part of the default view. Instead of relying on the view, query for the specific columns directly when creating the SPListItemCollection.
SPList cityList = web.Lists[cityListName];
SPListItemCollection items = cityList.GetItems("Title","LocCode");
foreach (SPListItem item in items)
{
cityName = item["Title"].ToString().Trim();
cityCode = item["LocCode"].ToString().Trim();
}
The "Title" field may exist in the list but not in the default view.
Can you do this?
foreach (var item in list.Items) Console.WriteLine((string)item["Title"]);
I'd suggest something like
if (item.Fields.ContainsField("Last_x0020_Modified"))
{
if (query.ViewFields.Contains("Last_x0020_Modified"))
...
B/c if the field wasn't requested in the SPQuery.ViewFields, you probably can't get it (exceptions include Created field, ID field)
The "Title" field is not (by default) available in the default view. If you have a look at the view settings page, Title is checked, but it is labeled as being "linked to item with edit menu".
The field exposed by the view is actually named "LinkTitle" (you can confirm this by enumerating list.DefaultView.ViewFields).
The solution to your problem is simply to replace item.Title with item["LinkTitle"].ToString().
I don't know why, but I created a GridView from SPListItemCollection as a DataSource. I had the same error. But I tried to get the dataTable from collection:
SPListItemCollection res = da.getAllItems();
DataTable dt = res.GetDataTable();
And then I see in my GridView that field that contains titles of list items is called "LinkTitle". So, I rewrited my code:
SPListItemCollection res = da.getAllItems();
gridView.DataSource = res.Cast<SPListItem>().Select(a=> a["LinkTitle"] );
gridView.DataBind();
And everything works fine :)
This problem can occure if you rename an already existing Column. Try deleting it and create a new one with the same name.
Or in another case that occured to me, I had accidentally wrote a letter of the column name in Greek! eg. "ΙsCooperation" Ι was a greek character