Accessing list in adapter - c#

Currently I am using C# with Xamarain and am developing for android. What I have right now is an activity (activity_MainView2) which holds a listview and has an adapter attached (adapter_MainView2). I also have a list (gCartList) which is inside of the activity, that I want to be able to access inside of the adapter to add the row id that the user clicks on. I have the onClick listeners set up inside of the adapter, but I'm not sure how to access the list. Sorry I'm pretty new to c#. Thank you in advance for the help.
From Activity
public List<Cart_List> gCartList { get; set; } = new List<Cart_List>();
When the cart button is press in the activity
public override bool OnOptionsItemSelected(IMenuItem item)
{
if (gDrawerToggle.OnOptionsItemSelected(item))
{
return true;
}
else
{
switch (item.ItemId)
{
case Resource.Id.cartButton:
Toast.MakeText(this, ("Cart Pressed").ToString(), ToastLength.Short).Show();
foreach (var tI in gCartList.OrderBy(a => a.Busn_ID)) System.Diagnostics.Debug.Write(tI);
return true;
}
}
return base.OnOptionsItemSelected(item);
}
In the Adapter
activity_MainView2 act = new activity_MainView2();
var things = act.gCartList;
things.Add(new Cart_List() { Busn_ID = "1", Item_ID = gItems[position].ID, Item_Qty = "1", Item_Name = gItems[position].Name, Item_Desc = gItems[position].Description, Item_Price = gItems[position].Price });

You can create a property in your activity and then it can be accessed like this:
public class Activity1
{
pubic Activity1()
{
this.SomeThings = new List<object>();
}
public List<object> SomeThings { get; set; }
}
public class Activity2
{
public Activity2()
{
// Now in this clas you can access the item to be shared
Activity1 act = new Activity1();
var things = act.SomeThings;
}
}
Or you can pass it to the constructor like this:
public class Activity2
{
private List<object> somethings;
public Activity2(List<object> somethings)
{
//
this.somethings = somethings;
}
}

Related

Casting mistake

Currently, in course, I am trying to check the LandCode from the class Landen to get the cities from the selectedItem land, but I am parsing something wrong.
public partial class Landen
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Landen()
{
this.Steden = new HashSet<Steden>();
this.Talen = new HashSet<Talen>();
}
public string LandCode { get; set; }
public string Naam { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Steden> Steden { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Talen> Talen { get; set; }
}
public MainWindow()
{
InitializeComponent();
var context = new LandenStedenTalenEntities();
landenListBox.ItemsSource = (from Landen in context.Landen select Landen.Naam).ToList();
}
private void landenListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
using (var entities = new LandenStedenTalenEntities())
{
List<string> steden = new List<string>();
var landcode = ((Landen)landenListBox.SelectedItem).LandCode.ToString();
var gekozenland = entities.Landen.Find(landcode);
foreach(var stad in gekozenland.Steden)
{
steden.Add(stad.Naam);
}
stedenInLandenListBox.ItemsSource = steden.ToList();
}
}
Exception:
Unable to cast object of type 'System.String' to type 'TestEFDieter.Landen'.
I want to add them to a list and show them in a second Listbox.
Can anyone help me out? Thank you.
I would suggest you modify the code inside of the constructor so that the landenListBox will contain actual Landen object and displays only the Naam as it's item.
Change the code in the constructor to this:
public MainWindow()
{
InitializeComponent();
var context = new LandenStedenTalenEntities();
landenListBox.ItemsSource = context.Landen.ToList();
landenListBox.DisplayMemberPath = "Naam";
}
Adding DisplayMemberPath will inform ListBox to display that particular property as an item instead of calling ToString() method on that object.
Now in your later code you do not have to change much, just remove ToList() and since you're using EntityFramework you should insert the whole model in it's Find() method but it's useless since you already have that object loaded. You can just retrieve stad from it directly and display it in the same way Landen is displayed:
private void landenListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var landen = landenListBox.SelectedItem as Landen; // safe cast just in case
if (landen != null && landen.Steden != null ) // null checks
{
stedenInLandenListBox.ItemsSource = landen.Steden.ToList(); // in case it's proxy object
stadenInLandenListBox.DisplayMemberPath = "Naam";
}
}
I suppose you want to get that instance of Landen which corresponds the selected item in your list. As the elements in the listbox are just strings that represent the Naam-property of every Landen, you could simply iterate your list of Landen and get that one with the desired Naam:
var selectedLanden = landenList.FirstOrDefault(x => x.Naam == landenListBox.SelectedItem);
if(selectedLanden != null)
{
var landCode = selectedLanden.LandCode;
// ...
}
However as selectedLanden already is an instance of Landen, you won´t need to find it again by its LandCode. Thus your code boils donw to this:
List<string> steden = new List<string>();
var selectedLanden = landenList.FirstOrDefault(x => x.Naam == landenListBox.SelectedItem);
if(selectedLanden != null)
{
foreach(var stad in selectedLanden.Steden)
{
steden.Add(stad.Naam);
}
}
stedenInLandenListBox.ItemsSource = steden.ToList();
or a bit shorter:
stedenInLandenListBox.ItemsSource = selectedLanden.SelectMany(x => x.Steden.Select(y => y.Naam)).ToList();
For this to work you of course have to store a reference to the list of Landen somewehere in your class:
class MainWindow
{
List<Landen> landenList;
public MainWindow()
{
InitializeComponent();
this.landenList = new LandenStedenTalenEntities();
landenListBox.ItemsSource = (from Landen in this.landenList select Landen.Naam).ToList();
}
}

Infinite loop or infinite recursion error in UWP using autosuggestbox

// The class for the search query
public class SearchQueries
{
List<data> list = new List<data>();
string response;
// The method that return the list after it is set
public List<data> GetData()
{
return list;
}
// The method that do the searching from the google API service
public async void SetData()
{
// The problem starts here, when i instantiate the search class in this class in other to get the value of the text in the autosuggestbox for my query, it crashes whenever i try to launch the page. it works fine whenever i give the address default data e.g string address = "London", the page open when i launch it and give me London related result whenever i type in the autosuggestbox.
Search search = new Search();
string address = search.Address;
list.Clear();
// Note the tutorial i used was getting the data from a local folder, but i'm trying to get mine from Google API
string dataUri = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key=AIzaSyDBazIiBn2tTmqcSpkH65Xq5doTSuOo22A&input=" + address;
string Api = System.Uri.EscapeDataString(dataUri);
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(1000);
try
{
response = await client.GetStringAsync(Api);
for (uint i = 0; i < jsonarray.Count; i++)
{
string json_string_object = jsonarray.GetObjectAt(i)["description"].ToString();
list.Add(new data() { name = json_string_object });
}
}
catch (TimeoutException e)
{
ContentDialog myDlg = new ContentDialog()
{
PrimaryButtonText = "OK"
};
myDlg.Content = e.ToString();
}
}
// Method to get matched data
public IEnumerable<data> getmatchingCustomer(string query)
{
return list.Where(c => c.name.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) > -1).OrderByDescending(c => c.name.StartsWith(query, StringComparison.CurrentCultureIgnoreCase));
}
// constructor for returning the SetData() method
public SearchQueries()
{
// It points to this method whenever the application crash, with the notification of infinite loop or infinite recursion
SetData();
}
}
// The Main Class of the page
public sealed partial class Search : Page
{
public string theaddress { get; set; }
SearchQueriess queries = new SearchQueriess();
public Search()
{
this.InitializeComponent();
myMap.Loaded += MyMap_Loaded;
theaddress = locationAddress.Text;
}
// The text change method of the autosuggest box.
private async void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
if (sender.Text.Length > 1)
{
var marchingData = queries.getmatchingCustomer(sender.Text);
sender.ItemsSource = marchingData.ToList();
}
else
{
sender.ItemsSource = new string[] { "No suggestion...." };
}
}
}
}

Append a Row to a Datagrid in WPF using MVVM

I have a DataGrid in my View as shown below.,
My Question is how can I Append the values from the textboxes to the row datagrid
I have make sure that the Model has All the properties, When I click on the Add button it overwrites the dataGrid and shows only one latest record the and my ViewModel look like this:
class BatchItemsViewModel : ViewModelBase
{
public SearchItemsModel msearchItems { get; set; }
ObservableCollection<SearchItemsModel> _BatchItemsGrid;
public ObservableCollection<SearchItemsModel> BatchItemsGrid
{
get { return _BatchItemsGrid; }
set
{
_BatchItemsGrid = value;
OnPropertyChanged("BatchItemsGrid");
}
}
private ICommand _addDataToBatchGrid;
public ICommand addDataToBatchGrid
{
get
{
return _addDataToBatchGrid;
}
set
{
_addDataToBatchGrid = value;
}
}
public BatchItemsViewModel()
{
msearchItems = new SearchItemsModel();
addDataToBatchGrid = new RelayCommand(new Action<object>(AddDataInBatchGrid));
}
public void AddDataInBatchGrid(object obj)
{
ObservableCollection<SearchItemsModel> batchGridData = new ObservableCollection<SearchItemsModel>();
var data = new SearchItemsModel
{
BatchNumber = msearchItems.BatchNumber,
MFDDate = msearchItems.MFDDate,
ExpiryDate = msearchItems.ExpiryDate,
Quantity = msearchItems.Quantity,
};
batchGridData.Add(data);
BatchItemsGrid = batchGridData; // HERE I am overwriting the datagrid
//How can I Append the batchGridData to BatchItemsGrid (BatchItemsGrid.Append(batchGridData)???)
}
}
NOTE: I have gone through the other threads as well in the community for the similar posts but I couldn't find the appropriate and please correct me if I am going in wrong direction.
public void AddDataInBatchGrid(object obj)
{
var data = new SearchItemsModel
{
BatchNumber = msearchItems.BatchNumber,
MFDDate = msearchItems.MFDDate,
ExpiryDate = msearchItems.ExpiryDate,
Quantity = msearchItems.Quantity,
};
this.BatchItemsGrid.Add(data);
}
...Should do the trick. (don't replace the whole collection, just add items to it and let the notification events handle the UI updates)

C# ComboBox List<object> ==> Show always the same object.name (multiple time)

I just want my ComboBox to show me the
FullName of objects in List(Curator),
but it show me the same "object.FullName" multiple times :-(
-
Basically, it work cause it show me the FullName of ONE of the Curator,
and the good amount of times,
but it show me the same ONE !
public partial class SGIArt : Form
{
public static Gallery gal = new Gallery(); // from a dll i made
List<Curator> curList = new List<Curator>();
public SGIArt()
{
InitializeComponent();
comboCur.DataSource = curList;
comboCur.ValueMember = null;
comboCur.DisplayMember = "FullName";
UpdateCurList();
}
public void UpdateCurList()
{
curList.Clear();
foreach (Curator cur in gal.GetCurList())
// from the same dll : Curators curatorsList = new Curators();
{
curList.Add(cur);
}
}
private void comboCur_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboCur.SelectedValue != null)
{
//show info in textBox (that work fine)
}
}
}
Curator class :
public class Curator : Person
{
private int id;
private double commission;
const double commRate = 0.25;
private int assignedArtists = 0;
public int CuratorID
{
get
{
return id;
}
set
{
id = value;
}
}
...
public Curator()
{
}
public Curator(string First, string Last, int curID)
: base(First, Last) // from : public abstract class Person
{
id = curID;
commission = 0;
assignedArtists = 0;
}
Edit: You might be looking for this answer.
I do not see the FullName member in your code snippet. I think you are looking for something like this:
List<Curator> curList = new List<Curator>();
public SGIArt()
{
InitializeComponent();
comboCur.DataSource = datasource;
comboCur.ValueMember = null;
comboCur.DisplayMember = "FullName";
UpdateCurList();
}
List<string> datasource()
{
List<string> datasource = new List<string>();
foreach(Curator curator in curList)
{
datasource.Add(curator.FullName)//this assume FullName is an accesible member of the Curator class and is a string.
}
return datasource;
}
The comboBox shows you object.FullName, because this is what you are telling it. The curList is empty at the time when you bind it.
You can update your list before using it:
public SGIArt()
{
InitializeComponent();
UpdateCurList();
comboCur.DataSource = curList;
comboCur.ValueMember = null;
comboCur.DisplayMember = "FullName";
}

How can I load data in combo item property when another changed, in propertygrid c#?

I have two property in my class: MyCountry & MyCity. I set this class to sourceobject of a property grid. I want load cities i combo when select a country. for example I have 2 Country data:
Country1
Country2
And For Country1, I have (city data)
City11
City12
City13
And For Country2, I have (city data)
city21
City22
City23
When I change select country item in propertygrid, I want load cities of it in city item. this mean, when select Country1, display City11,City12,City13 in City item and when select Country2 Display City21,Cityy22,City23 in City Item.
How can I It ?
my class is :
public class KeywordProperties
{
[TypeConverter(typeof(CountryLocationConvertor))]
public string MyCountry { get; set; }
[TypeConverter(typeof(CityLocationConvertor))]
public string MyCity { get; set; }
}
and I use below class for load countries data for display in combo :
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
HumanRoles Db = new HumanRoles();
List<LocationsFieldSet> Items = new List<LocationsFieldSet>();
Items = Db.LoadLocations(0);
string[] LocationItems = new string[Items.Count];
int count = 0;
foreach (LocationsFieldSet Item in Items)
{
LocationItems[count] = Item.Title;
count++;
}
return new StandardValuesCollection(LocationItems);
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
}
The ITypeDescriptorContext interface provides a property called Instance
which lets you access the object to which the type descriptor request is connected.
You can use this property to determine the current value of the MyCountry property
the user selected. Depending on the value you can load the cities for this country.
Furthermore, in the setter of the MyCountry property I check whether or not the
new value is different from the old one and if this is the case I reset the MyCity property
(to not get an invalid combination of country and city).
Here is a small code sample. For the sake of simplicity I only use one type converter
for both properties.
public class KeywordProperties
{
public KeywordProperties()
{
MyCountry = "Country1";
}
private string myCountry;
[TypeConverter(typeof(ObjectNameConverter))]
public string MyCountry
{
get { return myCountry; }
set
{
if (value != myCountry)
MyCity = "";
myCountry = value;
}
}
private string myCity;
[TypeConverter(typeof(ObjectNameConverter))]
public string MyCity
{
get { return myCity; }
set { myCity = value; }
}
}
public class ObjectNameConverter : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
KeywordProperties myKeywordProps = context.Instance as KeywordProperties;
if (context.PropertyDescriptor.Name == "MyCountry")
{
List<string> listOfCountries = new List<string>();
listOfCountries.Add("Country1");
listOfCountries.Add("Country2");
return new StandardValuesCollection(listOfCountries);
}
List<string> listOfCities = new List<string>();
if (myKeywordProps.MyCountry == "Country1")
{
listOfCities.Add("City11");
listOfCities.Add("City12");
listOfCities.Add("City13");
}
else
{
listOfCities.Add("City21");
listOfCities.Add("City22");
listOfCities.Add("City23");
}
return new StandardValuesCollection(listOfCities);
}
}
In the example above there is one side effect I do not like.
Setting the MyCountry property leads to settting also the MyCity property.
To workaround this side effect you could also use the PropertyValueChanged event
of the PropertyGrid to handle invalid country/city selections.
private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
if (e.ChangedItem.Label == "MyCountry")
{
if(e.ChangedItem.Value != e.OldValue)
m.MyCity = "";
}
}
If you use this event, just repalce the code in the setter of the MyCountry property with:
myCountry = value;

Categories