Searching GridView - linq

I am trying to make searchable GridView. it's DataSource is EntityDataSource. I have one textbox and a button. The problem is I need to use Linq to access the data. I don't really have any code yet, because I'm net at Linq and not sure what I'm doing. Can anyone help me?

This should help you to get started
protected void Page_Load(object sender, EventArgs e)
{
List<Customer> lstCust = new List<Customer>();
if (!IsPostBack)
{
for (int i = 0; i < 10; i++)
{
Customer c = new Customer();
c.FName = "FistName " + i.ToString();
lstCust.Add(c);
}
Session["Data"] = lstCust;
GridView1.DataSource = lstCust;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string searchText = TextBox1.Text;
List<Customer> lstCustSearch = new List<Customer>();
List<Customer> lstCust = new List<Customer>();
lstCust = Session["Data"] as List<Customer>;
lstCustSearch = (from data in lstCust
where data.FName.Contains(searchText)
select data).ToList();
GridView1.DataSource = lstCustSearch;
GridView1.DataBind();
}
}
public class Customer
{
public string FName { get; set; }
}
sorry for the coding convention. just came up with this sample

Related

Remove Placeholder from TextInputLayout in Xamarin Forms for Android & IOS

I am trying to create Suggestion Searchbar using Entry
i was able to create the suggestion searchbar but i am not able to change the look of this Entry, i want to remove the tooltip above (Search by Speciality..) and just want it to look like other entry in the app
could anyone help me what and where i had to make change for getting that look
here is my code
Xamarin Android :
[assembly: ExportRenderer(typeof(AutoCompleteViewv2),
typeof(AutoCompleteViewRendererv2))]
namespace App.Droid.Renderers.RevisedRenderer
{
public class AutoCompleteViewRendererv2 :
FormsAppCompat.ViewRenderer<AutoCompleteViewv2, TextInputLayout>
{
public AutoCompleteViewRendererv2(Context context) : base(context)
{
}
private AppCompatAutoCompleteTextView NativeControl => Control?.EditText
as AppCompatAutoCompleteTextView;
protected override TextInputLayout CreateNativeControl()
{
var textInputLayout = new TextInputLayout(Context);
var autoComplete = new AppCompatAutoCompleteTextView(Context)
{
BackgroundTintList = ColorStateList.ValueOf(GetPlaceholderColor()),
Text = Element?.Text,
Hint = Element?.Placeholder,
};
GradientDrawable gd = new GradientDrawable();
gd.SetColor(global::Android.Graphics.Color.Transparent);
autoComplete.SetBackground(gd);
if (Element != null)
{
autoComplete.SetHintTextColor(Element.PlaceholderColor.ToAndroid());
autoComplete.SetTextColor(Element.TextColor.ToAndroid());
}
textInputLayout.AddView(autoComplete);
return textInputLayout;
}
protected override void OnElementChanged(ElementChangedEventArgs<AutoCompleteViewv2> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// unsubscribe
NativeControl.ItemClick -= AutoCompleteOnItemSelected;
var elm = e.OldElement;
elm.CollectionChanged -= ItemsSourceCollectionChanged;
}
if (e.NewElement != null)
{
SetNativeControl(CreateNativeControl());
// subscribe
SetItemsSource();
SetThreshold();
KillPassword();
NativeControl.TextChanged += (s, args) => Element.RaiseTextChanged(NativeControl.Text);
NativeControl.ItemClick += AutoCompleteOnItemSelected;
var elm = e.NewElement;
elm.CollectionChanged += ItemsSourceCollectionChanged;
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Entry.IsPasswordProperty.PropertyName)
KillPassword();
if (e.PropertyName == AutoCompleteViewv2.ItemsSourceProperty.PropertyName)
SetItemsSource();
else if (e.PropertyName == AutoCompleteViewv2.ThresholdProperty.PropertyName)
SetThreshold();
}
private void AutoCompleteOnItemSelected(object sender, AdapterView.ItemClickEventArgs args)
{
var view = (AutoCompleteTextView)sender;
var selectedItemArgs = new SelectedItemChangedEventArgs(view.Text);
var element = (AutoCompleteViewv2)Element;
element.OnItemSelectedInternal(Element, selectedItemArgs);
}
private void ItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
var element = (AutoCompleteViewv2)Element;
ResetAdapter(element);
}
private void KillPassword()
{
if (Element.IsPassword)
throw new NotImplementedException("Cannot set IsPassword on a AutoComplete");
}
private void ResetAdapter(AutoCompleteViewv2 element)
{
var adapter = new BoxArrayAdapter(Context,
Android.Resource.Layout.SimpleDropDownItem1Line,
element.ItemsSource.ToList(),
element.SortingAlgorithm);
NativeControl.Adapter = adapter;
adapter.NotifyDataSetChanged();
}
private void SetItemsSource()
{
var element = (AutoCompleteViewv2)Element;
if (element.ItemsSource == null) return;
ResetAdapter(element);
}
private void SetThreshold()
{
var element = (AutoCompleteViewv2)Element;
NativeControl.Threshold = element.Threshold;
}
#region Section 2
protected AColor GetPlaceholderColor() => Element.PlaceholderColor.ToAndroid(Color.FromHex("#80000000"));
#endregion
}
internal class BoxArrayAdapter : ArrayAdapter
{
private readonly IList<string> _objects;
private readonly Func<string, ICollection<string>, ICollection<string>> _sortingAlgorithm;
public BoxArrayAdapter(
Context context,
int textViewResourceId,
List<string> objects,
Func<string, ICollection<string>, ICollection<string>> sortingAlgorithm) : base(context, textViewResourceId, objects)
{
_objects = objects;
_sortingAlgorithm = sortingAlgorithm;
}
public override Filter Filter
{
get
{
return new CustomFilter(_sortingAlgorithm) { Adapter = this, Originals = _objects };
}
}
}
internal class CustomFilter : Filter
{
private readonly Func<string, ICollection<string>, ICollection<string>> _sortingAlgorithm;
public CustomFilter(Func<string, ICollection<string>, ICollection<string>> sortingAlgorithm)
{
_sortingAlgorithm = sortingAlgorithm;
}
public BoxArrayAdapter Adapter { private get; set; }
public IList<string> Originals { get; set; }
protected override FilterResults PerformFiltering(ICharSequence constraint)
{
var results = new FilterResults();
if (constraint == null || constraint.Length() == 0)
{
results.Values = new Java.Util.ArrayList(Originals.ToList());
results.Count = Originals.Count;
}
else
{
var values = new Java.Util.ArrayList();
var sorted = _sortingAlgorithm(constraint.ToString(), Originals).ToList();
for (var index = 0; index < sorted.Count; index++)
{
var item = sorted[index];
values.Add(item);
}
results.Values = values;
results.Count = sorted.Count;
}
return results;
}
protected override void PublishResults(ICharSequence constraint, FilterResults results)
{
if (results.Count == 0)
Adapter.NotifyDataSetInvalidated();
else
{
Adapter.Clear();
var vals = (Java.Util.ArrayList)results.Values;
foreach (var val in vals.ToArray())
{
Adapter.Add(val);
}
Adapter.NotifyDataSetChanged();
}
}
}
}
how can i get rid of that tooltip or placeholder and make the text in middle

Need slideshow of images when my application is launched in windows phone 7

How to get the slideshow of images with time interval of 2 seconds. I had referred the below code from stackoverflow but while running iam nt getting any images displayed.. Please tel where iam went wrong...
Xaml:
<image Name=myImg Source={Binding bi}/>
Code:
private DispatcherTimer tmr = new DispatcherTimer();
private List<string> images = new List<string>();
private int imageIndex = 0;
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
tmr.Interval = TimeSpan.FromSeconds(5);
tmr.Tick += new EventHandler(tmr_Tick);
LoadImages();
ShowNextImage();
}
private void LoadImages()
{
// list the files (includede in the XAP file) here
images.Add("/images/filename1.jpg");
images.Add("/images/filename2.jpg");
images.Add("/images/filename3.jpg");
images.Add("/images/filename4.jpg");
}
private void ShowNextImage()
{
Imagesource bi = new BitmapImage(new Uri(images[imageIndex], UriKind.Relative));
myImg.Source = bi;
imageIndex = (imageIndex + 1) % images.Count;
}
void tmr_Tick(object sender, EventArgs e)
{
ShowNextImage();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (!tmr.IsEnabled)
{
tmr.Start();
}
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
tmr.Stop();
base.OnNavigatedFrom(e);
}
Thanks in Advance
Change Name=myImg to x:Name="myImg" and remove the Source attribute entirely. Otherwise it looks like it should work.

Getting a concrete event from WP7 calendar

I'm working on a WP7 application and I need it to play the song in the first link if the current event on the calendar is "Meeting". However, with the current code, it plays the second song instead if the first one even though the event is set correctly.
Here is my code:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
// Load data for the ViewModel Items
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Appointments appts = new Appointments();
//Identify the method that runs after the asynchronous search completes.
appts.SearchCompleted += new EventHandler<AppointmentsSearchEventArgs>(Appointments_SearchCompleted);
DateTime start = DateTime.Now;
DateTime end = DateTime.Now;
int max = 1;
//Start the asynchronous search.
appts.SearchAsync(start, end, max, "Appointments Test #1");
textBlock3.Text = DateTime.Now.ToString("hh:mm:ss tt");
}
void Appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
{
try
{
AppointmentResultsDataLINQ.DataContext =
from Appointment appt in e.Results
where appt.IsAllDayEvent == false
select appt;
}
catch (System.Exception)
{
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
if ((AppointmentResultsDataLINQ.DataContext).Equals("Meeting"))
{
mediaElement1.Source = new Uri("http://www.opendrive.com/files/NV8zNTMwNDYwX2hxRXZR/Crystallize.mp3", UriKind.Absolute);
}
else
{
mediaElement1.Source = new Uri("https://www.opendrive.com/files/NV8zMjAxODY0X0VBNDJY/Hetken%20tie%20on%20kevyt%20(piano%20cover)%20-%20YouTube.mp3", UriKind.Absolute);
}
mediaElement1.Play();
}
}
The problem appears to be this line:
if ((AppointmentResultsDataLINQ.DataContext).Equals("Meeting"))
You're comparing the result of calling the ToString() method on the Appointment instance with the string "Meeting".
You probably want:
if ((AppointmentResultsDataLINQ.DataContext as Appointment).Subject.Equals("Meeting"))
Update
You're actually checking an Enumerable of Appointments.
Here's how to check if any of them are "Meeting":
if ((AppointmentResultsDataLINQ.DataContext as IEnumerable<Appointment>).Any(app => app.Subject.Equals("Meeting")))

WPhone 7 listbox update from XML

I am having a problem with my Listbox not updating/refresing.I have read here that i need to use ObservableCollection but i didn't have any luck.I am populating my Listbox from a XML.
public class PestotoraPost
{
public string ID { get; set; }
public string Date { get; set; }
public string Name { get; set; }
public string Message { get; set; }
}
void WebLoad()
{
WebClient pestotora = new WebClient();
pestotora.DownloadStringCompleted += new DownloadStringCompletedEventHandler(pestotora_DownloadStringCompleted);
pestotora.DownloadStringAsync(new Uri("wwww.someURL.com/xml.php"));
}
Note that the actual xml is a php containing the xml structure (from a sql DB)
void pestotora_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
XElement doc = XElement.Parse(e.Result);
listBox1.ItemsSource = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name=results.Element("DataName").Value,
Message=results.Element("DataMessage").Value
};
}
Everytime the XML changes,my Listbox won't update doing a listBox1.UpdateLayout();
Any clue/help on how to start implementing this one?
Thank you very much.
UPDATED
namespace pestotora
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
UIload(true);
WebLoad();
}
public ObservableCollection<PestotoraPost> Posts { get; set; }
public class PestotoraPost
{
public string ID { get; set; }
public string Date { get; set; }
public string Name { get; set; }
public string Message { get; set; }
}
void WebLoad()
{
WebClient pestotora = new WebClient();
pestotora.DownloadStringCompleted += new DownloadStringCompletedEventHandler(pestotora_DownloadStringCompleted);
pestotora.DownloadStringAsync(new Uri("www.domain.com/xml.php"));
}
void UIload(bool Splash)
{
if (Splash == true)
{
ApplicationBar.IsVisible = false;
}
else
{
ApplicationBar.IsVisible = true;
}
}
void pestotora_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//XDocument doc = XDocument.Parse(e.Result);
XElement doc = XElement.Parse(e.Result);
/* listBox1.ItemsSource = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name=results.Element("DataName").Value,
Message=results.Element("DataMessage").Value
}; */
var list = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name = results.Element("DataName").Value,
Message = results.Element("DataMessage").Value
};
Posts = new ObservableCollection<PestotoraPost>(list);
foreach (var post in list)
{
Posts.Add(post);
}
UIload(false);
}
private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
{
//stckPost.Visibility = System.Windows.Visibility.Visible;
}
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/Post.xaml", UriKind.Relative));
}
private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
{
listBox1.UpdateLayout();
//listBox1.ScrollIntoView(listBox1.Items[0]);
WebLoad();
}
}
}
1. If you use MVVM pattern: In viewModel implement INotifyPropertyChanged and declare:
private ObservableCollection<PestotoraPost> _posts;
public ObservableCollection<PestotoraPost> Posts
{
get{return _posts;}
set
{
_posts = value;
RaisePropertyChanged("Posts");
}
}
in xaml write:
<ListBox Name="listbox1" ItemsSource="{Binding Posts}"/>
in pestotora_DownloadStringCompleted method:
var list = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name=results.Element("DataName").Value,
Message=results.Element("DataMessage").Value
};
Posts = new ObservableCollection<PestotoraPosts>(list);
2. If you run everything in a code-behind just declare
public ObservableCollection<PestotoraPosts> Posts {get;set;}
And in Page constructor init collection:
Posts = new ObservableCollection<PestotoraPosts>();
Xaml will have the same declaration.
And in pestotora_DownloadStringCompleted method:
var list = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name=results.Element("DataName").Value,
Message=results.Element("DataMessage").Value
};
foreach(var post in list)
{
Posts.Add(post);
}
What have we done?
In xaml we set a databinding . Now listBox1 will get data from Post collection.
Then we created new collection and notyfied listBox1 to update it's view. (in first vatiant).
In second variant we populated collection and as it was observable it notifyed a list box.

Inotify propertychanged not updating

I have a class which implements inotifypropertychaned.
public class Item : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name = string.Empty;
public string Name
{
get
{
return _name;
}
set
{
this._name = value;
onPropertyChanged(this, "Name");
}
}
private void onPropertyChanged(object sender, string property)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(sender, new PropertyChangedEventArgs(property));
}
}
}
here in UI i ve a textbox where a textchanged event when the length exceeds and updates the UI(grid) which binds the observable collection of the above mentioned class. but the UI is not updating.
ObservableCollection<Item> lstItem = null;
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length > 4)
{
Item obj = new Item();
obj.Name = textBox1.Text;
lstItem = new ObservableCollection<Item>();
dataGridView1.DataSource = lstItem;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message.ToString());
}
}
Thanks.
Look at this code:
Item obj = new Item();
obj.Name = textBox1.Text;
lstItem = new ObservableCollection<Item>();
dataGridView1.DataSource = lstItem;
You're setting the data source to an empty collection each time, and you're creating a new Item and then throwing it away again. Did you intend to add the item to the collection?
lstItem = new ObservableCollection<Item> { obj };
(It's not really clear whether you should be creating a new collection or even a new item - perhaps you should be using something like:
lstItem[0].Name = textBox1.Text;
instead?)

Resources