List Picker Selection Change - windows-phone-7

I have 2 list pickers which showing item name and batch number. Batch number depends on Item Name. So when selecting Item Name I want to bind Batch numbers to the second list picker.My code like this. I'm writen code for Item list picker 'SelectionChanged' event. This is not working.
private void lstItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstItem.SelectedIndex != 0)
{
int itemId = invoice.listItems[lstItem.SelectedIndex].ItemMasterID;
getBatches = invoice.bindBatchesForItem(itemId);
lstBatch.ItemsSource = getBatches;
}
}
bindBatchesForItem will return the list of batch numbers for selected item.This method returning the batch properly. But 'lstItem_SelectionChanged' event calling twise automatically. First time executing properly and when second time executing attached error comming.
public ObservableCollection<BatchNumbers> bindBatchesForItem(int selectedItem)
{
listBatches.Clear();
var batchList = from DailyItemStock DI in APPCommon.SFADB
where Convert.ToDateTime(DI.StockDate).Date == Convert.ToDateTime(APPCommon.TransactionDate).Date && DI.ItemMasterID == selectedItem
select new
{
DI.BatchNo
};
listBatches.Add(new BatchNumbers() { BatchNo = "0" });
foreach (var lists in batchList)
{
listBatches.Add(new BatchNumbers()
{
BatchNo = lists.BatchNo.ToString()
});
}
batchList = null;
return listBatches;
}

Related

Using Messaging center xamarin forms PCL to set current objects value

I have a scenario where i create Entry Controls programmatically.
foreach (var control in FormInfo.FormElementsInfo)
{
case "textbox":
//Some code
break;
case "dropdown":
Entry objDropdown = new Entry();
objDropdown.HeightRequest = 40;
objDropdown.StyleId = Convert.ToString(control.ElementId);
objDropdown.SetBinding(Entry.TextProperty, "ElementValue",BindingMode.TwoWay);
objDropdown.BindingContext = control;
layout.Children.Add(objDropdown);
MessagingCenter.Subscribe<Picklists, string>(objDropdown, "PicklistSelected", (sender, arg) =>
{
objDropdown.Text = arg;
// I tried this too as this is two way binding. It didn't show the value.
//control.ElementValue = arg;
} );
break;
}
If i click on any entry it will open me a list view. Once i select the option in the list view it will populate that data in the Entry.
But this should show the selected value only in the current entry but it is changing the value in all the entry's.
How to avoid this situation. I want the selected value to be populated only in the current entry.
Any suggestion would be appreciated. Thank you.
=== More clear question=====
If we create n number of Entry controls programmatically with 2 way binding . Is it possible to change the single entry value on selecting something in other page? If yes how to achieve this?
FormInfo
public class FormInfo
{
public List<FormsElementInfo> FormElementsInfo { get; set; }
}
FormsElementInfo
public class FormsElementInfo : INotifyPropertyChanged
{
private string _elementValue;
public string ElementValue {
get => _elementValue;
set {
if(_elementValue != value)
{
_elementValue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ElementValue"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Content Page
public class ListStackOverflow : ContentPage
{
private FormInfo _info = new FormInfo
{
FormElementsInfo = new List<FormsElementInfo>()
{
new FormsElementInfo { ElementValue = "test 1"},
new FormsElementInfo { ElementValue = "test 2"},
new FormsElementInfo { ElementValue = "test 3"},
new FormsElementInfo { ElementValue = "test 4"},
}
};
private StackLayout _stack = new StackLayout();
private List<string> _source = new List<string>
{
"output 1","output 2","output 3","output 4",
};
public ListStackOverflow()
{
//BindingContext = _info;
foreach(var c in _info.FormElementsInfo)
{
Entry tempEntry = new Entry
{
HeightRequest = 40,
Placeholder = c.ElementValue,
BindingContext = c
};
tempEntry.SetBinding(Entry.TextProperty, "ElementValue");
_stack.Children.Add(tempEntry);
}
ListView _lv = new ListView { ItemsSource = _source };
_lv.ItemSelected += Lv_ItemSelected;
_stack.Children.Add(_lv);
Content = _stack;
}
private void Lv_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var selectedElement = e.SelectedItem.ToString();
var index = _source.IndexOf(selectedElement);
var entry = _info.FormElementsInfo[index];
entry.ElementValue = selectedElement;
}
}
Output
Selecting the corresponding index in the listview will update "ElementValue" for the same index.
First of all Thank you #Joshua Poling for taking time to help me.
I think MessagingCenter is not suitable for this approach.
I am assigning a unique styleId to each element that i create.That basically stores the position in the stack layout.
I have written a delegate which returns the selected value and also the position of the element. As the element is always an Entry that fires this event. I used the below code to achieve this.
Entry myentry = (Xamarin.Forms.Entry)layout.Children[src.ElementId];

Metro App OnNavigatedTo setting textbox value in a different method

I am following around on a kindle book I bought for developing metro apps. For some reason I cannot set the text value of a text box in a method outside the OnNavigatedTo method. This is the code that the book provides:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//passed in the view model
viewModel = e.Parameter as ViewModel;
this.DataContext = viewModel;
viewModel.PropertyChanged += (sender, eventArgs) =>
{
if (eventArgs.PropertyName == "SelectedItemIndex")
{
if (viewModel.SelectedIndex == -1)
{
SetItemDetail(null);
}
else
{
SetItemDetail(viewModel.GroceryList[viewModel.SelectedIndex]);
}
}
SetItemDetail(viewModel.GroceryList[viewModel.SelectedIndex]);
};
}
private void SetItemDetail(GroceryItem item)
{
ItemDetailName.Text = "test"; //(item == null) ? "" : item.Name;
ItemDetailQuantity.Text = "test"; //(item == null) ? "" : item.Quantity.ToString();
//if (item != null)
//{
// ItemDetailStore.SelectedItem = item.Store;
//}
//else
//{
// ItemDetailStore.SelectedIndex = -1;
//}
}
I have commented parts out in the set item detail method, but I still cannot set the value of a textbox when I click it (this is supposed to be the behavior). I have used break points and the property of the textbox is getting set, however, it is not displayed on screen.
Thanks.

ASP.NET DropDownList not set to the selected item in async call

I am using VS 2010 (framework 4.0) for website development along with rad/telerik controls. The scenario is I have radwindow popup, actually a confirmation message box. On the basis of decision I have to call the base page again where have to call respective function. Here I want to set Country dropdownlist and state dropdowlist. I call the server side event in javascript function on OnClientClose event of Radwindow and in server side function call respective functions to set the form fields where I set Country and State list as well. But when I try to set Country selected value, it not get selected though there are items in dropdownlist. Here is the code,
Javascript function
function OnradWndConfirmSelfOwnerClose(oWnd) {
var hdn = document.getElementById("<%= hdnIsOwner.ClientID %>");
try {
var arg = oWnd.argument;
if (arg == "YES") {
hdn.value = 'true';
}
else {
hdn.value = 'false';
}
__doPostBack('<%=this.btnInitializeOwnerForm.UniqueID %>', '');
}
catch (err) { }
}
Server side function,
protected void btnInitializeOwnerForm_Click(object sender, EventArgs e)
{
bool IsOwner = !String.IsNullOrEmpty(hdnIsOwner.Value) ? Convert.ToBoolean(hdnIsOwner.Value) : false;
if (IsOwner)
{
SaveOwner();
}
else
{
InitializeOwnerData();
}
}
and in InitializeOwnerData() there is call for SetDefaultFields() function,
private void SetDefaultFields(ApplicationAccessInfo objAAInfo)
{
//Set Company Information fields
txtOrganizationName.Text = objAAInfo.EntityorOrganization;
txtCompanyWebsite.Text = objAAInfo.CompanyWebsite;
txtStreetAddress.Text = objAAInfo.StreetAddrees;
txtOfficeNumber.Text = objAAInfo.SuiteorOfficeNumber;
txtCity.Text = objAAInfo.City;
if (Guid.Empty != objAAInfo.CompanyCountryId)
{
**ddlCountry.Items.FindByValue(objAAInfo.CompanyCountryId.ToString()).Selected = true;**
PopulateStateList();
if (ddlCountry.SelectedItem.Value != "0")
**ddlState.Items.FindByValue(objAAInfo.CompanyStateId.ToString()).Selected = true;**
}
txtPostalCode.Text = objAAInfo.PostalCode;
//Disable Company Information fields
txtCompanyWebsite.Enabled = false;
txtOrganizationName.Enabled = false;
txtStreetAddress.Enabled = false;
txtOfficeNumber.Enabled = false;
txtCity.Enabled = false;
txtPostalCode.Enabled = false;
ddlCountry.Enabled = false;
ddlState.Enabled = false;
}
Item not get selected at ddlCountry.Items.FindByValue(objAAInfo.CompanyCountryId.ToString()).Selected = true
so ultimately gets error on,
ddlState.Items.FindByValue(objAAInfo.CompanyStateId.ToString()).Selected = true;
Note that when I call this same function normally then all works perfectly. In this scenario I found Items in Country list and objAAInfo.CompanyCountryId is also in the list.
Please help me out of this

Unable to show the selected item in the Wp7 Listpicker control

Basically i am trying to pull the contacts from the phone and showing them in the Listpicker control for a feature in my app. I have two Listpickers, one for name of contacts list and the other showing the list of phonenumbers for the chosen contact.
Here is my code:
//Declarations
ContactsSearchEventArgs e1;
String SelectedName;
String SelectedNumber;
List<string> contacts = new List<string>();
List<string> phnum = new List<string>();
public AddressBook() // Constructor
{
InitializeComponent();
Contacts contacts = new Contacts();
contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contacts_SearchCompleted);
contacts.SearchAsync(string.Empty,FilterKind.None,null);
}
void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
e1 = e;
foreach (var result in e.Results)
{
if (result.PhoneNumbers.Count() != 0)
{
contacts.Add(result.DisplayName.ToString());
}
}
Namelist.ItemsSource = contacts;
}
private void Namelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedName = (sender as ListPicker).SelectedItem.ToString();
phnum.Clear();
foreach (var result in e1.Results)
{
if (SelectedName == result.DisplayName)
{
phnum.Add(result.PhoneNumbers.FirstOrDefault().ToString());
}
}
Numbers.ItemsSource = phnum;
}
private void Numbers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedNumber = (sender as ListPicker).SelectedItem.ToString();
}
Am able to populate the Numberlist with phonenumbers for the chosen name at the Listpicker background, but the number is not showing up in the front. I think Numbers_SelectionChanged() event is called only one time when the page loads and am not seeing it triggerd when i change the contact list. Anyone has an idea of where am going wrong ?
If you change
List<string>
To
ObservableCollection<string>
this should work.
Also then you only need to set the ItemSource once, in Xaml or you constructor.
But you may run into another issue with the November 2011 Toolkit and ListPicker.
See more in thread.
private void Namelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedName = (sender as ListPicker).SelectedItem.ToString();
phnum = new List<string>(); // Changed instead of phnum.Clear()
foreach (var result in e1.Results)
{
if (SelectedName == result.DisplayName)
{
phnum.Add(result.PhoneNumbers.FirstOrDefault().ToString());
}
}
Numbers.ItemsSource = phnum;
}
This works !!. While debugging i found its phnum.Clear() giving a problem. So i thought to create a new instance of phnum list for selected contact.

Sharepoint 2010 Custom Webpart - Access Denied Error

we've created a custom webpart to display announcements from all lists a user has access to, removing a few. The error we are having is that the webpart works fine on the page for the administrators, but when testing with regular user accounts, they are unable to see the page at all and are given a Access Denied error which is coming from the webpart itself.
Only when a user is added as a Site Collection Administrator they can see the page and have access to the webpart. What I'd like some advice on is how to be able to apply full read permissions to a select group within the code itself.
Below is the backend code
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace Test.TestWebPart
{
public partial class TestWebPartUserControl : UserControl
{
//Global variable call
private SPSite thisSite = SPContext.Current.Site;
private SPWebCollection thisWeb;
private DataTable dt;
private SPListCollection siteLists;
private DataTableWrapper myDataTable;
//Occurs when the page loads
protected void Page_Load(object sender, EventArgs e)
{
//Pulls all the websites in the site into a webcollection
thisWeb = thisSite.AllWebs;
//If the page is not postback call BindToGrid()
if (!Page.IsPostBack)
{
BindToGrid();
}
}
private void BindToGrid()
{
//Create a new DataTable along with the columns and headers
dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("Created");
dt.Columns.Add("List");
//Call to populate the DataTable
dt = SelectData();
//Populate DataTableWrapper class and get the type
myDataTable = new DataTableWrapper(dt);
Type t = myDataTable.GetType();
//Create a ObjectDataSource to hold data and bind to spgridview
ObjectDataSource ds = new ObjectDataSource();
ds.ID = "myDataSource";
ds.TypeName = t.AssemblyQualifiedName;
ds.SelectMethod = "GetTable";
ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
this.Controls.Add(ds);
grid.ID = "gridID";
BoundField column = new BoundField();
column.DataField = "Title";
column.HtmlEncode = false;
//column.SortExpression = "Title";
column.HeaderText = "Title";
grid.Columns.Add(column);
BoundField column1 = new BoundField();
column1.DataField = "Created";
column1.HtmlEncode = true;
//column1.SortExpression = "Created";
column1.HeaderText = "Created";
grid.Columns.Add(column1);
BoundField column2 = new BoundField();
column2.DataField = "List";
column2.HtmlEncode = false;
//column2.SortExpression = "List";
column2.HeaderText = "List";
grid.Columns.Add(column2);
//Provide the SPGridview with the DataSource
grid.DataSourceID = "myDataSource";
this.Controls.Add(grid);
//grid.PageSize =10;
//grid.AllowPaging = true;
//Default Pagination - commented out due to not working
//grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
//grid.PagerTemplate = null;
//Bind the data to the grid
grid.DataBind();
}
//private void GenerateColumns()
//{
//}
//Used to deal with the PageIndexChange event
void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grid.DataBind();
}
//Used to deal with the ObjectCreated event
void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
myDataTable = new DataTableWrapper(dt);
e.ObjectInstance = myDataTable;
}
//Pulls the data from lists which will be displayed
public DataTable SelectData()
{
try
{
//Create a new instance of type DataRow
DataRow row;
//Loop through each website in the webcollection
foreach (SPWeb web in thisWeb)
{
//Pull the lists from the site into a list collection
siteLists = web.Lists;
//Display only lists the current user has access to
siteLists.ListsForCurrentUser = true;
//Loop through each list within the list collection
foreach (SPList list in siteLists)
{
//If the list is an announcement list continue otherwise skip
if (list.BaseTemplate.ToString() == "Announcements")
{
//Exclude the lists stated from those whose data will be collected
if (list.Title.ToString() == "Bulletins" || list.Title.ToString() == "The Buzz - Curriculum" || list.Title.ToString() == "The Buzz - Personal" || list.Title.ToString() == "The Buzz - Support" || list.Title.ToString() == "Critical Annoucements")
{
}
else
{
//Create a item collection for each item within the current list
SPListItemCollection listItem = list.Items;
//Loop through each item within the item collection
foreach (SPListItem item in listItem)
{
//Get the url of the current website
string weburl = web.Url;
//Gets the URL of the current item
string dispurl = item.ContentType.DisplayFormUrl;
dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
//Joins together the full URL for the current item into a single variable
dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
//Create a new in the datatable as an instance of row
row = dt.Rows.Add();
//Put the correct information and links into the correct column
row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
row["Created"] = item["Created"].ToString();
row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
}
}
}
}
}
//Return the completed DataTable
return dt;
}
//Exception to catch any errors
catch (Exception s)
{
return dt;
}
}
}
}
Thanks
thisWeb = thisSite.AllWebs;
This code requires Administrator previliges. Run it under Elevated Previleges:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx
Based on the above comments and edited changes, here is the full working code, encase anyone was wondering:-
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace Test.TestWebPart
{
public partial class TestWebPartUserControl : UserControl
{
//Global variable call
private SPSite thisSite = SPContext.Current.Site;
//private SPWebCollection thisWeb;//
private SPWeb thisWeb = SPContext.Current.Web;
private DataTable dt;
private SPListCollection siteLists;
private DataTableWrapper myDataTable;
//Occurs when the page loads
protected void Page_Load(object sender, EventArgs e)
{
//Pulls all the websites in the site into a webcollection
//thisWeb = thisSite.AllWebs.;//
//If the page is not postback call BindToGrid()
if (!Page.IsPostBack)
{
BindToGrid();
}
}
private void BindToGrid()
{
//Create a new DataTable along with the columns and headers
dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("Created");
dt.Columns.Add("List");
//Call to populate the DataTable
dt = SelectData();
//Populate DataTableWrapper class and get the type
myDataTable = new DataTableWrapper(dt);
Type t = myDataTable.GetType();
//Create a ObjectDataSource to hold data and bind to spgridview
ObjectDataSource ds = new ObjectDataSource();
ds.ID = "myDataSource";
ds.TypeName = t.AssemblyQualifiedName;
ds.SelectMethod = "GetTable";
ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
this.Controls.Add(ds);
grid.ID = "gridID";
//Sorting, Filtering & paging does not work so has been commented out for now
//this.grid.AllowSorting = true;
//Bind the three columns to the SPGridView
//HtmlEncode must be false for the links to appear as true html
BoundField column = new BoundField();
column.DataField = "Title";
column.HtmlEncode = false;
//column.SortExpression = "Title";
column.HeaderText = "Title";
grid.Columns.Add(column);
BoundField column1 = new BoundField();
column1.DataField = "Created";
column1.HtmlEncode = true;
//column1.SortExpression = "Created";
column1.HeaderText = "Created";
grid.Columns.Add(column1);
BoundField column2 = new BoundField();
column2.DataField = "List";
column2.HtmlEncode = false;
//column2.SortExpression = "List";
column2.HeaderText = "List";
grid.Columns.Add(column2);
//Has been commented out due to these sections not working
//grid.AllowFiltering = true;
//grid.FilterDataFields = "Title";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//grid.FilterDataFields = "Created";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//grid.FilterDataFields = "ListName";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//Provide the SPGridview with the DataSource
grid.DataSourceID = "myDataSource";
this.Controls.Add(grid);
//grid.PageSize =10;
//grid.AllowPaging = true;
//Default Pagination - commented out due to not working
//grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
//grid.PagerTemplate = null;
//Bind the data to the grid
grid.DataBind();
}
//private void GenerateColumns()
//{
//}
//Used to deal with the PageIndexChange event
void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grid.DataBind();
}
//Used to deal with the ObjectCreated event
void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
myDataTable = new DataTableWrapper(dt);
e.ObjectInstance = myDataTable;
}
//Pulls the data from lists which will be displayed
public DataTable SelectData()
{
try
{
//Create a new instance of type DataRow
DataRow row;
//Loop through each website in the webcollection
{
//Pull the lists from the site into a list collection
siteLists = thisWeb.Lists;
//Display only lists the current user has access to
siteLists.ListsForCurrentUser = true;
SPBasePermissions perms = SPBasePermissions.ViewListItems;
//Loop through each list within the list collection
foreach (SPList list in siteLists)
{
if (list.DoesUserHavePermissions(perms))
{
//If the list is an announcement list continue otherwise skip
if (list.BaseTemplate.ToString() == "Announcements")
{
//Exclude the lists stated from those whose data will be collected
if (list.Title.ToString() == "The Buzz" || list.Title.ToString() == "Test 2 list")
{
}
else
{
//Create a item collection for each item within the current list
SPListItemCollection listItem = list.Items;
//Loop through each item within the item collection
foreach (SPListItem item in listItem)
{
//Get the url of the current website
string weburl = thisWeb.Url;
//Gets the URL of the current item
string dispurl = item.ContentType.DisplayFormUrl;
dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
//Joins together the full URL for the current item into a single variable
dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
//Create a new in the datatable as an instance of row
row = dt.Rows.Add();
//Put the correct information and links into the correct column
row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
row["Created"] = item["Created"].ToString();
row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
}
}
}
}
}
}
//Return the completed DataTable
return dt;
}
//Exception to catch any errors
catch (Exception s)
{
return dt;
}
}
}
}
SPWeb.GetSubwebsForCurrentUser() should be used. It gets SubWebs that current user has access to. Avoid using ElevatedPriveleges until you absolutely need it.

Resources