windows phone application button content - windows

I've got incredibly weird problem. I'm making memo game app on windows phone. When I click 2 buttons and if they have the same content they should collapse. Problem is that even if they have the same content for example 1 it shows me that this statement is false! Like 1 was not equal 1.
Here's the code:
public partial class Memo : PhoneApplicationPage
{
private int points = 100;
private string[] numbers={"a","a"};
private Button selected_button;
public Memo()
{
InitializeComponent();
button1.Content = numbers[0];
button2.Content = numbers[1];
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (selected_button != null)
{
PageTitle.Text = "" + selected_button.Content + " " + button1.Content;
if (selected_button.Content == button1.Content)
{
button1.Visibility = Visibility.Collapsed;
selected_button.Visibility = Visibility.Collapsed;
points += 3;
}
else
{
points -= 1;
selected_button.Background = new SolidColorBrush(Colors.White);
}
selected_button = null;
//PageTitle.Text = "" + points;
}
else
{
selected_button = button1;
selected_button.Background = new SolidColorBrush(Colors.Green);
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
if (selected_button != null)
{
PageTitle.Text = "" + selected_button.Content + " " + button2.Content;
if (selected_button.Content == button2.Content)
{
button2.Visibility = Visibility.Collapsed;
selected_button.Visibility = Visibility.Collapsed;
points += 3;
}
else
{
points -= 1;
selected_button.Background = new SolidColorBrush(Colors.White);
}
selected_button = null;
//PageTitle.Text = "" + points;
}
else
{
selected_button = button2;
selected_button.Background = new SolidColorBrush(Colors.Green);
}
}
private void button11_Click(object sender, RoutedEventArgs e)
{
button11.Visibility = Visibility.Collapsed;
}
}
Please help :)

Related

How to Resume video after SeekTo() method in VideoView?

I have a VideoView and when I pause video, then leave the page and come back - I need to resume video from last position.
But I have a problem - after SeekTo() method video starts from beginning.
I tried to put SeekTo() in SetSource to AutoPlay but nothing is changed((
Here is my VideoPlayerRender:
[assembly: ExportRenderer(typeof(VideoPlayer),
typeof(FormsVideoLibrary.Droid.VideoPlayerRenderer))]
namespace FormsVideoLibrary.Droid
{
public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, ARelativeLayout>
{
VideoView videoView;
MediaController mediaController; // Used to display transport controls
bool isPrepared;
public VideoPlayerRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> args)
{
base.OnElementChanged(args);
if (args.NewElement != null)
{
if (Control == null)
{
// Save the VideoView for future reference
videoView = new VideoView(Context);
// Put the VideoView in a RelativeLayout
ARelativeLayout relativeLayout = new ARelativeLayout(Context);
relativeLayout.AddView(videoView);
// Center the VideoView in the RelativeLayout
ARelativeLayout.LayoutParams layoutParams =
new ARelativeLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
layoutParams.AddRule(LayoutRules.CenterInParent);
videoView.LayoutParameters = layoutParams;
// Handle a VideoView event
videoView.Prepared += OnVideoViewPrepared;
SetNativeControl(relativeLayout);
}
SetAreTransportControlsEnabled();
SetSource();
args.NewElement.UpdateStatus += OnUpdateStatus;
args.NewElement.PlayRequested += OnPlayRequested;
args.NewElement.PauseRequested += OnPauseRequested;
args.NewElement.StopRequested += OnStopRequested;
}
if (args.OldElement != null)
{
args.OldElement.UpdateStatus -= OnUpdateStatus;
args.OldElement.PlayRequested -= OnPlayRequested;
args.OldElement.PauseRequested -= OnPauseRequested;
args.OldElement.StopRequested -= OnStopRequested;
}
}
protected override void Dispose(bool disposing)
{
if (Control != null && videoView != null)
{
videoView.Prepared -= OnVideoViewPrepared;
}
if (Element != null)
{
Element.UpdateStatus -= OnUpdateStatus;
}
base.Dispose(disposing);
}
void OnVideoViewPrepared(object sender, EventArgs args)
{
isPrepared = true;
((IVideoPlayerController)Element).Duration = TimeSpan.FromMilliseconds(videoView.Duration);
var mediaPlayer = sender as MediaPlayer;
var startTime = new TimeSpan(0, 0, 0);
if (App.CurrentPosition > startTime)
{
var position = (int)App.CurrentPosition.TotalMilliseconds;
****mediaPlayer.SeekTo(position);****
((IElementController)Element).SetValueFromRenderer(VideoPlayer.PositionProperty, position);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(sender, args);
if (args.PropertyName == VideoPlayer.AreTransportControlsEnabledProperty.PropertyName)
{
SetAreTransportControlsEnabled();
}
else if (args.PropertyName == VideoPlayer.SourceProperty.PropertyName)
{
SetSource();
}
else if (args.PropertyName == VideoPlayer.PositionProperty.PropertyName)
{
if (Math.Abs(videoView.CurrentPosition - Element.Position.TotalMilliseconds) > 1000)
{
videoView.SeekTo((int)Element.Position.TotalMilliseconds);
}
}
}
void SetAreTransportControlsEnabled()
{
if (Element.AreTransportControlsEnabled)
{
mediaController = new MediaController(Context);
mediaController.SetMediaPlayer(videoView);
videoView.SetMediaController(mediaController);
}
else
{
videoView.SetMediaController(null);
if (mediaController != null)
{
mediaController.SetMediaPlayer(null);
mediaController = null;
}
}
}
void SetSource()
{
isPrepared = false;
bool hasSetSource = false;
if (Element.Source is UriVideoSource)
{
string uri = (Element.Source as UriVideoSource).Uri;
if (!String.IsNullOrWhiteSpace(uri))
{
videoView.SetVideoURI(Android.Net.Uri.Parse(uri));
hasSetSource = true;
}
}
else if (Element.Source is FileVideoSource)
{
string filename = (Element.Source as FileVideoSource).File;
if (!String.IsNullOrWhiteSpace(filename))
{
videoView.SetVideoPath(filename);
hasSetSource = true;
}
}
else if (Element.Source is ResourceVideoSource)
{
string package = Context.PackageName;
string path = (Element.Source as ResourceVideoSource).Path;
if (!String.IsNullOrWhiteSpace(path))
{
string filename = Path.GetFileNameWithoutExtension(path).ToLowerInvariant();
string uri = "android.resource://" + package + "/raw/" + filename;
videoView.SetVideoURI(Android.Net.Uri.Parse(uri));
hasSetSource = true;
}
}
if (hasSetSource && Element.AutoPlay)
{
videoView.Start();
}
}
// Event handler to update status
void OnUpdateStatus(object sender, EventArgs args)
{
VideoStatus status = VideoStatus.NotReady;
var startTime = new TimeSpan(0, 0, 0);
if (isPrepared)
{
status = videoView.IsPlaying ? VideoStatus.Playing : VideoStatus.Paused;
}
TimeSpan timeSpan = TimeSpan.FromMilliseconds(videoView.CurrentPosition);
((IElementController)Element).SetValueFromRenderer(VideoPlayer.PositionProperty, timeSpan);
if (status == VideoStatus.Paused &&
timeSpan > startTime &&
!isApplicationInTheBackground())
{
App.CurrentPosition = timeSpan;
}
}
I used XamarinMediaManager and all works.

Icon not highlighted when using BottomBarPage

I’m using the BottomBarPage package. I’m changing the Tab on the fly programmatically, however the icon at the bottom doesn’t get highlighted for Android when there’s a tab change. It works well on iOS on the hand.
I tried James Montemagno’s code, I couldn’t get it to work with the BottomBarPage package.
This is the link to his code
https://montemagno.com/dynamically-changing-xamarin-forms-tab-icons-when-select/
How do I get the Icon highlighted when there is a Tab Page happening programmatically for BottomBarPage?
Below is my code.
public AndroidMainPage(int indexPage)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
CurrentPageChanged += MainPage_CurrentPageChanged;
CurrentPage = Children[indexPage];
CurrentPage.Appearing += (s, a) => Children[indexPage].Icon = new FileImageSource() { File = "quizzes_selected.png" };
CurrentPage.Disappearing += (s, a) => Children[indexPage].Icon = new FileImageSource() { File = "quizzes.png" };
_currentPage = CurrentPage;
}
private void MainPage_CurrentPageChanged(object sender, EventArgs e)
{
IIconChange currentBinding;
if (_currentPage != null)
{
currentBinding = ((NavigationPage)_currentPage).CurrentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = false;
}
_currentPage = CurrentPage;
currentBinding = ((NavigationPage)_currentPage).CurrentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = true;
UpdateIcons?.Invoke(this, EventArgs.Empty);
}
Android BottomBarPage Renderer:
[assembly: ExportRenderer(typeof(AndroidMainPage), typeof(MyTabbedPageRenderer))]
namespace TabPageDemo.Android.Renderers
{
public class MyTabbedPageRenderer : BottomBarPageRenderer
{
bool setup;
TabLayout layout;
public MyTabbedPageRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<BottomBarPage> e)
{
if (e != null) base.OnElementChanged(e);
if (Element != null)
{
((AndroidMainPage)Element).UpdateIcons += Handle_UpdateIcons;
}
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (layout == null && e.PropertyName == "Renderer")
{
layout = (TabLayout)ViewGroup.GetChildAt(1);
}
}
void Handle_UpdateIcons(object sender, EventArgs e)
{
TabLayout tabs = layout;
if (tabs == null)
return;
for (var i = 0; i < Element.Children.Count; i++)
{
var child = Element.Children[i].BindingContext as IIconChange;
if (child == null) continue;
var icon = child.CurrentIcon;
if (string.IsNullOrEmpty(icon))
continue;
TabLayout.Tab tab = tabs.GetTabAt(i);
SetCurrentTabIcon(tab, icon);
}
}
void SetCurrentTabIcon(TabLayout.Tab tab, string icon)
{
tab.SetIcon(IdFromTitle(icon, ResourceManager.DrawableClass));
}
int IdFromTitle(string title, Type type)
{
string name = Path.GetFileNameWithoutExtension(title);
int id = GetId(type, name);
return id;
}
int GetId(Type type, string memberName)
{
object value = type.GetFields().FirstOrDefault(p => p.Name == memberName)?.GetValue(type)
?? type.GetProperties().FirstOrDefault(p => p.Name == memberName)?.GetValue(type);
if (value is int)
return (int)value;
return 0;
}
}
}
Using the Renderer, the tab variable is always null from this TabLayout.Tab tab = tabs.GetTabAt(i);
Any suggestion?

How to assign OnActivityResult values to the Listview?

I have a Listview and Click Events in the respective listItems and need to get result back from the click events and populate on the List.
My BaseAdapter class is
public class RemnantListAdapter : BaseAdapter<InventorySlabs>
{
private PartialInventory context;
private List<InventorySlabs> RemnantList;
public RemnantListAdapter(PartialInventory partialInventory, List<InventorySlabs> remnantList)
{
this.context = partialInventory;
this.RemnantList = remnantList;
}
public override InventorySlabs this[int position]
{
get
{
return RemnantList[position];
}
}
public override int Count
{
get
{
return RemnantList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override int ViewTypeCount
{
get
{
return Count;
}
}
public override int GetItemViewType(int position)
{
return position;
}
private class remnantHolder : Object
{
public Button EditRemnant1;
public TextView Remnant1 = null;
public TextView Rem_StockNMaterial1 = null;
public TextView Rem_Dimensions1 = null;
public TextView Rem_Status1 = null;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
remnantHolder holder = null;
if (convertView == null)
{
convertView = (convertView ?? context.LayoutInflater.Inflate(Resource.Layout.remnant_list, parent, false));
holder = new remnantHolder();
holder.EditRemnant1 = convertView.FindViewById<Button>(Resource.Id.editRemnant1);
holder.Remnant1 = convertView.FindViewById<TextView>(Resource.Id.remnant1);
holder.Rem_StockNMaterial1 = convertView.FindViewById<TextView>(Resource.Id.remnant_mtrl1);
holder.Rem_Dimensions1 = convertView.FindViewById<TextView>(Resource.Id.remnant_dimens1);
holder.Rem_Status1 = convertView.FindViewById<TextView>(Resource.Id.remnant_status1);
try
{
InventorySlabs remnantModel = this.RemnantList[position];
if (remnantModel != null)
{
holder.Remnant1.Text = "#" + remnantModel.ExtSlabNo;
holder.Rem_StockNMaterial1.Text = remnantModel.SellName + "-" + remnantModel.Depth + "-" + remnantModel.Finish;
double sqft = (remnantModel.Width * remnantModel.Height) / 144;
holder.Rem_Dimensions1.Text = "(" + remnantModel.Width.ToString() + " * " + remnantModel.Height.ToString() + ")" + sqft.ToString("N2");
holder.Rem_Status1.Text = remnantModel.Status;
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
context.StartActivityForResult(intent, 1);
}
};
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
convertView.Tag = holder;
}
else
{
holder = (remnantHolder)convertView.Tag;
}
return convertView;
}
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
if (remSlab != null)
{
remnantData.Width = double.Parse(data.GetStringExtra("remWidth"));
remnantData.Height = double.Parse(data.GetStringExtra("remHeight"));
double sqft = (remnantData.Width * remnantData.Height) / 144;
Rem_Dimensions.Text = "(" + remnantData.Width.ToString() + " * " + remnantData.Height.ToString() + ")" + sqft.ToString("N2");
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
}
}
In my Main Activity
I am calling the Result as
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
}
After editing the details in Edit view of the ListItem and close the Popup, I am not knowing how to Pass the Values to the Holder to Update in Listview.
You could pass the positon to the new activity in the click event and pass it back with the result intent.
For example:
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
intent.PutExtra("Position", position );
context.StartActivityForResult(intent, 1);
}
};
And in the new activity:
protected override void OnCreate(Bundle savedInstanceState)
{
Intent intent = Intent;
var position =intent.GetIntExtra("Position", -1);
base.OnCreate(savedInstanceState);
Intent data = new Intent();
String text = "extSlabNo";
data.PutExtra("extSlabNo", text);
data.PutExtra("remWidth", 10);
data.PutExtra("remHeight", 20);
data.PutExtra("Position", position);
SetResult(Result.Ok, data);
}
Then you could modify the data in the adapter according to the positon value:
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
int position = data.GetIntExtra("Position", -1);
if (remSlab != null && position >= 0)
{
RemnantList[position].Width = data.GetIntExtra("remWidth", -1);
RemnantList[position].Height = data.GetIntExtra("remHeight", -1);
NotifyDataSetChanged();
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
And reset the adapter in MainActivity OnActivityResult() method :
public class MainActivity : AppCompatActivity
{
RemnantListAdapter remnantListAdapter;
ListView listView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
List<InventorySlabs> remnantList = new List<InventorySlabs>();
for(var i = 0; i < 10; i++)
{
InventorySlabs inventorySlabs = new InventorySlabs();
inventorySlabs.Depth = i.ToString();
inventorySlabs.ExtSlabNo = i.ToString();
inventorySlabs.Finish = "Finish" + i.ToString();
inventorySlabs.Height = 200;
inventorySlabs.SellName = "SellName" + i.ToString();
inventorySlabs.Status = "Status" + i.ToString();
inventorySlabs.Width = 400;
remnantList.Add(inventorySlabs);
}
listView = FindViewById<ListView>(Resource.Id.listView1);
remnantListAdapter = new RemnantListAdapter(this, remnantList);
listView.Adapter = remnantListAdapter;
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
listView.Adapter = remnantListAdapter;
}
}

Issue while Playing, the recorded audio in WP7

Hi Developers,
If we save the recorded voice as a mp3 file. we get the error while opening the file as Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.
Please Give a Solution to overcome this Issue ....
Here is My Source code
namespace Windows_Phone_Audio_Recorder
{
public partial class MainPage : PhoneApplicationPage
{
MemoryStream m_msAudio = new MemoryStream();
Microphone m_micDevice = Microphone.Default;
byte[] m_baBuffer;
SoundEffect m_sePlayBack;
ViewModel vm = new ViewModel();
long m_lDuration = 0;
bool m_bStart = false;
bool m_bPlay = false;
private DispatcherTimer m_dispatcherTimer;
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
DataContext = vm;
m_dispatcherTimer = new DispatcherTimer();
m_dispatcherTimer.Interval = TimeSpan.FromTicks(10000);
m_dispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
m_dispatcherTimer.Start();
FrameworkDispatcher.Update();
//icBar.ItemsSource = vm.AudioData;
}
void frameworkDispatcherTimer_Tick(object sender, EventArgs e)
{
FrameworkDispatcher.Update();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
m_bStart = true;
tbData.Text = "00:00:00";
m_lDuration = 0;
m_micDevice.BufferDuration = TimeSpan.FromMilliseconds(1000);
m_baBuffer = new byte[m_micDevice.GetSampleSizeInBytes(m_micDevice.BufferDuration)];
//m_micDevice.BufferReady += new EventHandler(m_Microphone_BufferReady);
m_micDevice.BufferReady += new EventHandler<EventArgs>(m_Microphone_BufferReady);
m_micDevice.Start();
}
void m_Microphone_BufferReady(object sender, EventArgs e)
{
m_micDevice.GetData(m_baBuffer);
Dispatcher.BeginInvoke(()=>
{
vm.LoadAudioData(m_baBuffer);
m_lDuration++;
TimeSpan tsTemp = new TimeSpan(m_lDuration * 10000000);
tbData.Text = tsTemp.Hours.ToString().PadLeft(2, '0') + ":" + tsTemp.Minutes.ToString().PadLeft(2, '0') + ":" + tsTemp.Seconds.ToString().PadLeft(2, '0');
}
);
//this.Dispatcher.BeginInvoke(new Action(() => vm.LoadAudioData(m_baBuffer)));
//this.Dispatcher.BeginInvoke(new Action(() => tbData.Text = m_baBuffer[0].ToString() + m_baBuffer[1].ToString() + m_baBuffer[2].ToString() + m_baBuffer[3].ToString()));
m_msAudio.Write(m_baBuffer,0, m_baBuffer.Length);
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (m_bStart)
{
m_bStart = false;
m_micDevice.Stop();
ProgressPopup.IsOpen = true;
}
if (m_bPlay)
{
m_bPlay = false;
m_sePlayBack.Dispose();
}
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
m_bPlay = true;
m_sePlayBack = new SoundEffect(m_msAudio.ToArray(), m_micDevice.SampleRate, AudioChannels.Mono);
m_sePlayBack.Play();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAudio.Text != "")
{
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
string strSource = txtAudio.Text + ".wav";
int nIndex = 0;
while (isfData.FileExists(txtAudio.Text))
{
strSource = txtAudio.Text + nIndex.ToString().PadLeft(2, '0') + ".wav";
}
IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strSource, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Write(m_msAudio.ToArray(), 0, m_msAudio.ToArray().Length);
isfStream.Close();
}
this.Dispatcher.BeginInvoke(new Action(() => ProgressPopup.IsOpen = false));
}
}
}
DotNet Weblineindia
my Source Code For UPLOADING A AUDIO TO PHP SERVER:
public void UploadAudio()
{
try
{
if (m_msAudio != null)
{
var fileUploadUrl = "uploadurl";
var client = new HttpClient();
m_msAudio.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(m_msAudio), "uploaded_file", strFileName);
// upload the file sending the form info and ensure a result.it will throw an exception if the service doesn't return a valid successful status code
client.PostAsync(fileUploadUrl, content)
.ContinueWith((postTask) =>
{
try
{
postTask.Result.EnsureSuccessStatusCode();
var respo = postTask.Result.Content.ReadAsStringAsync();
string[] splitChar = respo.Result.Split('"');
FilePath = splitChar[3].ToString();
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/VoiceSlider.xaml?FName=" + strFileName, UriKind.Relative)));
}
catch (Exception ex)
{
// Logger.Log.WriteToLogger(ex.Message);
MessageBox.Show("voice not uploaded" + ex.Message);
}
});
}
}
catch (Exception ex)
{
//Logger.Log.WriteToLogger(ex.Message + "Error occured while uploading image to server");
}
}
First of all Windows Phone does not allow to record .mp3 files. So, the .mp3 file that you are saving will not be played by Windows Phone player.
Have a look at this. This demo is working fine for recording .wav file.
If you wish to save other formats like .aac,.amr then user AudioVideoCaptureDevice class.

Sorting ASP Datalist after BINDING

I am binding a DataList with dynamic values (ie distances from google api From a particular location.)
ie from x location :
10 km away
15 km away etc as follows
Using this code in ItemDataBound :
private void bindDataList(string location)
{
DataSet dstProperty = Tbl_PropertyMaster.getPropertiesByLocation(location);
dlstNearbyProperties.DataSource = dstProperty;
dlstNearbyProperties.DataBind();
}
.
protected void dlstNearbyProperties_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
Label lblPropId = (Label)e.Item.FindControl("lblPropId");
Label lblKmAway = (Label)e.Item.FindControl("lblKmAway");
Label lblPrice = (Label)e.Item.FindControl("lblPrice");
DataSet dstEnabledStat = Tbl_PropertyMaster.GetPropertyDetailsbyId(Convert.ToInt32(lblPropId.Text));
if (dstEnabledStat.Tables[0].Rows.Count > 0)
{
//string origin = "8.5572357 ,76.87649310000006";
string origin = InitialOrigin;
string destination = dstEnabledStat.Tables[0].Rows[0]["Latitude"].ToString() + "," + dstEnabledStat.Tables[0].Rows[0]["Longitude"].ToString();
lblKmAway.Text = devTools.getDistance(origin, destination) + " Away";
}
lblPrice.Text = getMinnimumOfRoomPrice(Convert.ToInt32(lblPropId.Text));
}
}
Is there a way to sort these value in ascendind or descening w.r.t distances .
NB: Distances are not DB values,they are dynamic.
Can this be sorted in a Button1_Click ?
Alrite after lot of hours of playing with codes I did it.
The following is for GRIDVIEW,Similar steps can be followed for DataList As well.
Page Load : I added an extra column 'Miles' to the already existing datatable
protected void Page_Load(object sender, EventArgs e)
{
dtbl = Tbl_PropertyMaster.SelectAllPropertyAndUserDetails().Tables[0];
dtbl.Columns.Add("Miles", typeof(int));
//userId = devTools.checkAdminLoginStatus();
if (!IsPostBack)
{
fillDlPhotoViewAll();
FillGrProperty();
}
}
Row Data Bound :
protected void grProperty_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataSet dstEnabledStat = Tbl_PropertyMaster.GetPropertyDetailsbyId(PropId);
if (dstEnabledStat.Tables[0].Rows.Count > 0)
{
string origin = InitialOrigin;
string destination = dstEnabledStat.Tables[0].Rows[0]["Latitude"].ToString() + "," + dstEnabledStat.Tables[0].Rows[0]["Longitude"].ToString();
decimal Kilometre=0.00M;
if(devTools.getDistance(origin, destination)!=0)
{
Kilometre=Convert.ToDecimal(devTools.getDistance(origin, destination))/1000;
}
lblmiles.Text = Kilometre.ToString() + "Kms";
dtbl.Rows[inn]["Miles"] = Convert.ToInt32(devTools.getDistance(origin, destination));
inn = inn + 1;
}
}
ViewState["dtbl"] = dtbl;
}
Sort by distance Button_Click:
protected void btnSort_Click(object sender, EventArgs e)
{
DataTable dataTable;
dataTable = (DataTable)ViewState["dtbl"];
if (dataTable.Rows.Count > 0)
{
dataTable.DefaultView.Sort = "Miles DESC";
dataTable.AcceptChanges();
grProperty.DataSource = dataTable;
grProperty.DataBind();
}
}

Resources