Xamarin Maps displays but doesn't update - c#

I'm attempting to make a google map using Xamarin forms, the pins displays correctly and zooms in onto the user. It displays the inital map when the page starts, but when moving or zooming the map doesn't change and becomes grids if you zoom in enough. I can see my pin on the grid and everything, but I would like the map to load along with the pin.
public partial class IssueMap2 : ContentPage
{
public UIIssueVM Issue { get; set; }
public GeoLocation Location { get; set; }
public bool AllowPinMovment { get; set; }
private ExtendedMap.ExtendedMap map;
public Xamarin.Forms.Maps.Position OrgIssueLocation { get; set; }
bool IsGettingLocation = false;
bool bMapCtrlReady = false;
IGeolocator Locator;
public IssueMap2(UIIssueVM Issue, GeoLocation location)
{
AllowPinMovment = false;
this.Issue = Issue;
this.Location = location;
Title = "Map";
OrgIssueLocation = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
Locator = CrossGeolocator.Current;
if (Locator.DesiredAccuracy != 100)
Locator.DesiredAccuracy = 100;
if (Device.RuntimePlatform != Device.WinPhone)
{
InitializeComponent();
map = new ExtendedMap.ExtendedMap()
{
IsShowingUser = true,
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand
};
map.LongTap += OnMapLongTap;
map.Ready += MapCtrlReady;
slMap.Children.Add(map);
}
}
public void MapCtrlReady(object sender, EventArgs args)
{
bMapCtrlReady = true;
}
public void OnMapLongTap(object sender, ExtendedMap.TapEventArgs args)
{
if (AllowPinMovment == false)
return;
if (Issue == null)
return;
var pos = args.Position;
// Update Issue
Issue.Latitude = pos.Latitude;
Issue.Longitude = pos.Longitude;
Issue.Changed = true;
// Update Pin
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
}
protected void AddPin(Xamarin.Forms.Maps.Position pos, String Title, String Desc)
{
// MAP pin does not like it if labels are empty
if (Title.Length == 0)
Title = "-";
if (Desc.Length == 0)
Desc = "-";
var pin = new Pin
{
Type = PinType.Place,
Position = pos,
Label = Title,
Address = Desc
};
map.Pins.Add(pin);
}
protected override void OnAppearing()
{
if (Device.RuntimePlatform == Device.WinPhone)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
if (Issue.IsNew == false)
{
var position = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
AddPin(position, Issue.Title, Issue.Description);
MoveToPinLocation();
}
else // Issue is new
{
// Move to main location
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromMiles(1)));
// Get current location for new item
OnGetLocation();
}
}
}
protected override async void OnDisappearing()
{
if (Locator.IsListening)
{
await Locator.StopListeningAsync();
}
// Map controller crashes sometimes if we are to quick with exiting
await Task.Delay(500);
while (bMapCtrlReady == false)
{
await Task.Delay(500);
}
}
void OnButtonCenter(object sender, EventArgs args)
{
MoveToPinLocation();
}
void MoveToPinLocation()
{
double KmDistace = 0.5;
if (Issue != null)
{
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude), Distance.FromKilometers(KmDistace)));
}
else
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonMainLocation(object sender, EventArgs args)
{
double KmDistace = 0.5;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonGetLocation(object sender, EventArgs args)
{
OnGetLocation();
}
async void OnGetLocation()
{
if (IsGettingLocation == true)
return; // already getting location
try
{
if (Locator.IsListening == true)
{
await Locator.StopListeningAsync();
}
if (Locator.IsGeolocationAvailable == false)
{
lbPosText.Text = "GeoLocation is not available.";
this.ForceLayout();
return;
}
if (Locator.IsGeolocationEnabled == false)
{
lbPosText.Text = "GeoLocation is not enabled.";
this.ForceLayout();
return;
}
IsGettingLocation = true;
IsBusy = true;
slCommands.IsVisible = false;
aActIndicator.IsVisible = true;
aActIndicator.IsRunning = true;
lbPosText.Text = "Searching for GPS location...";
this.ForceLayout();
TimeSpan timeSpan = TimeSpan.FromTicks(120 * 1000);
var position = await Locator.GetPositionAsync(timeSpan);
// Update Issue Position
Issue.Latitude = position.Latitude;
Issue.Longitude = position.Longitude;
Issue.Changed = true;
// Update Pin Postion
var pos = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
UpdateGPSLocationText();
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
this.ForceLayout();
// Center map around pin
MoveToPinLocation();
}
catch (Exception /*ex*/)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
lbPosText.Text = "Unable to find position!";
lbPosText.IsVisible = true;
this.ForceLayout();
}
}
void UpdateGPSLocationText()
{
String text = String.Format("{0} x {1}", Issue.Longitude, Issue.Latitude);
lbPosText.Text = text;
}
}
}
Android extended map renderer
[assembly: ExportRenderer(typeof(ExtendedMap.ExtendedMap), typeof(ExtendedMapRenderer))]
namespace ExtendedMap.Android
{
public class ExtendedMapRenderer : MapRenderer, IOnMapReadyCallback
{
private GoogleMap _map;
public ExtendedMapRenderer()
{
}
public ExtendedMapRenderer(IntPtr javaReference, JniHandleOwnership jniHandleOwnership)
{
int x = 0;
x++;
}
private void InvokeOnMapReadyBaseClassHack(GoogleMap googleMap)
{
System.Reflection.MethodInfo onMapReadyMethodInfo = null;
Type baseType = typeof(MapRenderer);
foreach (var currentMethod in baseType.GetMethods(System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.DeclaredOnly))
{
if (currentMethod.IsFinal && currentMethod.IsPrivate)
{
if (string.Equals(currentMethod.Name, "OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
if (currentMethod.Name.EndsWith(".OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
}
}
if (onMapReadyMethodInfo != null)
{
onMapReadyMethodInfo.Invoke(this, new[] { googleMap });
}
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
InvokeOnMapReadyBaseClassHack(googleMap);
_map = googleMap;
if (_map != null)
{
_map = googleMap;
this.NativeMap = googleMap;
_map.MapClick += googleMap_MapClick;
_map.MapLongClick += googleMap_MapLongClick;
((ExtendedMap)Element).OnReady();
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
if (_map != null)
_map.MapClick -= googleMap_MapClick;
base.OnElementChanged(e);
if (Control != null)
((MapView)Control).GetMapAsync(this);
}
private void googleMap_MapClick(object sender, GoogleMap.MapClickEventArgs e)
{
((ExtendedMap)Element).OnTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
private void googleMap_MapLongClick(object sender, GoogleMap.MapLongClickEventArgs e)
{
((ExtendedMap)Element).OnLongTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
}
}

I would double check the Google Maps API key on the manifest of your application!
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzr3yCpVgSOXvTgri29nC6KqFbdO73QmoVQWEw" />
As well as your SHA-1 key of your keystore on the Google API Credential Dashboard.

Related

How can I insert new item on a list<> checking id for duplicates?

I have to make a list of runners and the user cannot insert a runner that has the same Id of another runner (which has been inserted).
I tried with this:
async private void save_Click(object sender, RoutedEventArgs e)
{
int flag = 0;
if (dni.Text != "")
{
Corredor co = new Corredor();
flag = 0;
co.Dni = dni.Text;
co.Nombre = nombreCorredor.Text;
co.Apellidos = apellidos.Text;
co.ClubDeportivo = clubDeportivo.Text;
co.FechaNacimiento = new DateTime(pickerFechaNacimiento.Date.Year, pickerFechaNacimiento.Date.Month, pickerFechaNacimiento.Date.Day);
if(federado.IsChecked == true)
{
co.Federado = true;
}
else
{
co.Federado = false;
}
foreach (Corredor rec in App.lCorredores)
{
if (string.Equals(rec.Dni, co.Dni))
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if (flag == 0)
{
App.lCorredores.Add(co);
MessageDialog md = new MessageDialog("Corredor Añadido");
await md.ShowAsync();
Limpiar_v();
}
else
{
MessageDialog mde = new MessageDialog("Ese corredor ya existe");
await mde.ShowAsync();
}
}
else
{
MessageDialog md = new MessageDialog("Debe rellenar los datos");
await md.ShowAsync();
}
}
but once I insert a duplicated id (Dni) the program just shows me the error again and again. And I can't keep adding items.
I can't see the error here.
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var tst = new TestClass { Id = 1 };
var lst = new List<TestClass> { new TestClass { Id = 1 } };
if (lst.FirstOrDefault(x => x.Id == tst.Id) == null)
{
lst.Add(tst);
}
else
{
// code that maust run is already exists
}
}
}
class TestClass
{
public int Id { get; set; }
}
}
Use dictionaries in this case, they have TryAdd() methothod that can be useful.
Not checked but try to do this way:
async private void save_Click(object sender, RoutedEventArgs e)
{
if (dni.Text != "")
{
var co = new Corredor
{
Dni = dni.Text,
Nombre = nombreCorredor.Text,
Apellidos = apellidos.Text,
ClubDeportivo = clubDeportivo.Text,
FechaNacimiento = new DateTime(pickerFechaNacimiento.Date.Year, pickerFechaNacimiento.Date.Month, pickerFechaNacimiento.Date.Day),
Federado = federado.IsChecked,
};
if (App.lCorredores.FirstOrDefault(x => x.Dni == co.Dni) == null)
{
App.lCorredores.Add(co);
MessageDialog md = new MessageDialog("Corredor Añadido");
await md.ShowAsync();
Limpiar_v();
}
else
{
MessageDialog mde = new MessageDialog("Ese corredor ya existe");
await mde.ShowAsync();
}
}
else
{
MessageDialog md = new MessageDialog("Debe rellenar los datos");
await md.ShowAsync();
}
}

RecyclerView check CheckBox and store in database

Hello someone could help me please, I am making an application in Xamarin android as a project at school, but I have doubts with a checkbox and RecyclerView, what happens is that it assumes that the user can select one or more item within the RecyclerView and when push a poton that btnagregar save all the item name having the Checked property to true in a mysql database
MenuItemA.cs
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecycleAdapter mAdapter;
List<ItemAli> alilist;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate (bundle);
new I18N.West.CP1250();
new I18N.CJK.CP50220();
int idC = Convert.ToInt32(Intent.GetStringExtra("idc") ?? "Data not available");
SetContentView(Resource.Layout.RecyclerItem);
alilist = new List<ItemAli>();
try
{
string connsqlstring = "";
MySqlConnection sqlconn = new MySqlConnection(connsqlstring);
sqlconn.Open();
DataSet ds = new DataSet();
string queryString = "SELECT `IdAli`, `NombreA`, `Precio`, `Imagen`, `Tiempo` FROM `alimentos` as Item WHERE `IdCategoria` = " + idC;
MySqlDataAdapter adapter = new MySqlDataAdapter(queryString, sqlconn);
adapter.Fill(ds, "Item");
foreach (DataRow row in ds.Tables["Item"].Rows)
{
alilist.Add(new ItemAli { AliID = (row[0]).ToString(), Name = row[1].ToString(), Quantity = 0, Price = Convert.ToDecimal(row[2]), ImageId = row[3].ToString(), Time = row[4].ToString(), AddToOrder = false});
}
sqlconn.Close();
}
catch
{
Toast.MakeText(this, "La categoria esta vacia", ToastLength.Short).Show();
}
Button btnagregar = FindViewById<Button>(Resource.Id.btanadir);
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.rvitem);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.SetLayoutManager(mLayoutManager);
mAdapter = new RecycleAdapter(this,alilist);
mAdapter.ItemClick += OnItemClick;
mAdapter.SpinnerItemSelectionChanged += SpinnerItemSelectionChangedEvent;
mRecyclerView.SetAdapter(mAdapter);
btnagregar.Click += delegate
{
};
}
void OnItemClick(object sender, string IdAlimento)
{
var a = new Intent(this, typeof(ActividadDetAli));
a.PutExtra("idA", IdAlimento);
StartActivity(a);
}
void SpinnerItemSelectionChangedEvent(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
var itemPosition = Convert.ToInt32 (spinner.Tag);
var currentquantity = alilist[itemPosition].Quantity;
var selectedQuantity = Convert.ToInt32( spinner.GetItemAtPosition (e.Position).ToString());
if (currentquantity != selectedQuantity) {
alilist [itemPosition].Quantity = selectedQuantity;
mAdapter.NotifyItemChanged (itemPosition);
}
}
}
RecycleAdapter.cs
public class VegeViewHolder: RecyclerView.ViewHolder
{
public ImageView Image { get; set; }
public TextView Name { get; set; }
public Spinner Quantity { get; set; }
public TextView Price { get; set; }
public TextView TotalAmount { get; set; }
public CheckBox cbx { get; set; }
public string idA { get; set; }
public VegeViewHolder(View itemView, Action<string> itemlistner, Action<object,AdapterView.ItemSelectedEventArgs> spinnerItemSelected )
:base(itemView)
{
Image = itemView.FindViewById<ImageView> (Resource.Id.list_image);
Name = itemView.FindViewById<TextView> (Resource.Id.Name);
Price = itemView.FindViewById<TextView> (Resource.Id.Price);
Quantity = itemView.FindViewById<Spinner> (Resource.Id.spinner1);
TotalAmount = itemView.FindViewById<TextView> (Resource.Id.total);
cbx = itemView.FindViewById<CheckBox>(Resource.Id.cbc);
itemView.Click += (sender, e) => itemlistner (idA);
Quantity.ItemSelected+= new EventHandler<AdapterView.ItemSelectedEventArgs> (spinnerItemSelected);
}
}
public class RecycleAdapter:RecyclerView.Adapter
{
public event EventHandler<string> ItemClick;
public event EventHandler<AdapterView.ItemSelectedEventArgs> SpinnerItemSelectionChanged;
public List<ItemAli> Items;
Activity Context;
List<string> _quantity = new List<string> ();
public RecycleAdapter (Activity context, List<ItemAli> list)
{
this.Items = list;
this.Context = context;
PopulateSpinnerDropDownValues ();
}
void PopulateSpinnerDropDownValues()
{
_quantity.Add ("0");
_quantity.Add ("1");
_quantity.Add ("2");
_quantity.Add ("3");
_quantity.Add ("4");
_quantity.Add ("5");
_quantity.Add ("6");
_quantity.Add ("7");
_quantity.Add ("8");
_quantity.Add ("9");
_quantity.Add("10");
_quantity.Add("11");
_quantity.Add("12");
_quantity.Add("13");
_quantity.Add("14");
_quantity.Add("15");
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.list_items, parent, false);
VegeViewHolder vh = new VegeViewHolder(itemView, OnClick,spinner_ItemSelected);
return vh;
}
public override int ItemCount
{
get { return Items != null ? Items.Count : 0; }
}
void OnClick(string IdAlimento)
{
if (ItemClick != null)
ItemClick (this, IdAlimento);
}
private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
if (SpinnerItemSelectionChanged != null)
SpinnerItemSelectionChanged (sender, e);
}
public Bitmap GetBitmapFromUrl(string url)
{
using (WebClient webClient = new WebClient())
{
byte[] bytes = webClient.DownloadData(url);
if (bytes != null && bytes.Length > 0)
{
return BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);
}
}
return null;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
{
var item = Items[position];
var vh = viewHolder as VegeViewHolder;
var spinnerPos = 0;
var adapter =new ArrayAdapter<String>(Context, Android.Resource.Layout.SimpleSpinnerItem, _quantity);
adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.Name.Text = item.Name;
vh.Price.Text = string.Format("Precio: ${0}",item.Price);
vh.ItemView.Tag = position;
if (item.Quantity > 0) {
spinnerPos = adapter.GetPosition (item.Quantity.ToString ());
vh.TotalAmount.Text = string.Format ("${0}", item.Price * item.Quantity);
} else {
vh.TotalAmount.Text = "";
}
vh.Quantity.Tag = position;
vh.Quantity.Adapter = adapter;
vh.Quantity.SetSelection(spinnerPos);
Bitmap bitmap = GetBitmapFromUrl(item.ImageId);
vh.Image.SetImageBitmap(bitmap);
vh.idA = item.AliID +"°"+ item.ImageId + "°" + item.Name + "°" + item.Price + "°" + item.Time;
vh.cbx.Checked = item.AddToOrder;
}
}
}

avoid local host ID to be edited by customers

i have an orderdetails page wherein customers can view their history page. And this is the url:
when i change the ID from 13 to lets say 14, it still shows the details on whats inside ID#14. What i want to happen is to have an error when customers try to change the localhost ID. Or to restrict the ID to be edited? Really dont have any idea on what to do. Encryption?
By the way here is the orderdetails code behind: (this is in user control)
public partial class ucCustomerOrder1 : System.Web.UI.UserControl
{
public bool CanIUpdateStatus;
public string TransactionNoText
{
get { return txtTransactionNo.Text; }
set { txtTransactionNo.Text = value; }
}
public bool IsAuthorizedToAddStatus
{
set { CanIUpdateStatus = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["IslandGasAdmin/ST"] == null)
{
txtTransactionNo.ReadOnly = true;
btnGo.Visible = false;
}
else
{
txtTransactionNo.ReadOnly = false;
btnGo.Visible = true;
}
if (txtTransactionNo.Text != string.Empty)
{
ShowOrderDetails(rblOrderDetails.SelectedValue, Convert.ToInt32(txtTransactionNo.Text));
}
else
{
rblOrderDetails.Visible = false;
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = false;
Panel4.Visible = false;
}
}
}
private void ShowOrderDetails(string PanelId, int OrderNo)
{
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = false;
Panel4.Visible = false;
rblOrderDetails.Visible = false;
if (IsOrderNoValid(OrderNo))
{
rblOrderDetails.Visible = true;
if (PanelId == "1")
{
ShoppingCart k = new ShoppingCart
{
Flag = OrderNo
};
DataTable dtCustomerDetails = k.GetOrderList();
if (dtCustomerDetails.Rows.Count > 0)
{
Panel1.Visible = true;
lblCustomerName.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerName"]);
lblCustomerPhoneNo.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerPhoneNo"]);
lblCustomerEmailID.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerEmailID"]);
lblTotalPrice.Text = String.Format("{0:#,000.00}",dtCustomerDetails.Rows[0]["TotalPrice"]);
lblTotalProducts.Text = Convert.ToString(dtCustomerDetails.Rows[0]["TotalProducts"]);
txtCustomerAddress.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerAddress"]);
lblPaymentMethod.Text = Convert.ToString(dtCustomerDetails.Rows[0]["PaymentMethod"]);
}
}
if (PanelId == "2")
{
Panel2.Visible = true;
ShoppingCart k = new ShoppingCart()
{
Flag = OrderNo
};
dlProducts.DataSource = k.GetTransactionDetails(); ;
dlProducts.DataBind();
}
if (PanelId == "3")
{
Panel3.Visible = true;
DropDownStatus.Visible = CanIUpdateStatus;
txtStatus.Visible = false;
//txtStatus.Visible = CanIUpdateStatus;
btnAdd.Visible = CanIUpdateStatus;
GetSetOrderStatus(0);
}
}
else
{
Panel4.Visible = true;
}
}
private bool IsOrderNoValid(int OrderNo)
{
ShoppingCart k = new ShoppingCart
{
Flag = OrderNo
};
DataTable dtCustomerDetails = k.GetOrderList();
if (dtCustomerDetails.Rows.Count > 0)
return true;
else
return false;
}
private void GetSetOrderStatus(int Flag)
{
ShoppingCart k = new ShoppingCart
{
OrderStatus = DropDownStatus.SelectedValue,
OrderNo = txtTransactionNo.Text,
Flag = Flag
};
DataTable dt = k.GetSetOrderStatus();
gvOrderStatus.DataSource = dt;
gvOrderStatus.DataBind();
//txtStatus.Text = string.Empty;
//DropDownStatus.SelectedValue = string.Empty;
}
please do help me, thank you

Selecting and displaying certain items from list based on specific property

i have a list of objects saved in a text file that I can display onto a form. However now I need a button that will only display certain objects from the list based on a property, in my case brand. Below is the code I've been trying to use but cant get it to work.
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
Underneath is the full code, in case more information is needed, thanks for your help.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Car_Manager
{
public partial class Form1 : Form
{
string currentfile;
Car c;
int curIndex = -1;
List<Car> cars = new List<Car>();
public Form1()
{
InitializeComponent();
c = new Car();
saveFileDialog1.CreatePrompt = true;
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.FileName = "myText";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter =
"Text files (*.txt)|*.txt|All files (*.*)|*.*";
}
public void clearForm()
{
txtBrand.Text = "";
txtModel.Text = "";
txtYear.Text = "";
txtPrice.Text = "";
txtNumMiles.Text = "";
txtInformation.Text = "";
radAutomatic.Checked = false;
radManual.Checked = false;
radConvertible.Checked = false;
radCoupe.Checked = false;
radEstate.Checked = false;
radHatchback.Checked = false;
radHPV.Checked = false;
radSaloon.Checked = false;
radSUV.Checked = false;
}
private void DisplayCar()
{
txtBrand.Text = c.Brand;
txtModel.Text = c.Model;
txtYear.Text = c.Year;
txtPrice.Text = c.Price;
txtNumMiles.Text = c.NumMiles;
DisplayBody();
DisplayGear();
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void FormToObject()
{
c.Brand = txtBrand.Text;
c.Model = txtModel.Text;
c.Year = txtYear.Text;
c.Price = txtPrice.Text;
c.NumMiles = txtNumMiles.Text;
BodyCheck();
GearCheck();
}
private void BodyCheck()
{
if (radHatchback.Checked == true)
{ c.Body = radHatchback.Text; }
else if (radHPV.Checked == true)
{ c.Body = radHPV.Text; }
else if (radSUV.Checked == true)
{ c.Body = radSUV.Text; }
else if (radSaloon.Checked == true)
{ c.Body = radSaloon.Text; }
else if (radConvertible.Checked == true)
{ c.Body = radConvertible.Text; }
else if (radCoupe.Checked == true)
{ c.Body = radCoupe.Text; }
else if (radEstate.Checked == true)
{ c.Body = radEstate.Text; }
}
private void DisplayBody()
{
if (c.Body == "Hatchback")
{ radHatchback.PerformClick(); }
else if (c.Body == "HPV")
{ radHPV.PerformClick(); }
else if (c.Body == "SUV")
{ radSUV.PerformClick(); }
else if (c.Body == "Convertible")
{ radConvertible.PerformClick(); }
else if (c.Body == "Saloon")
{ radSaloon.PerformClick(); }
else if (c.Body == "Coupe")
{ radSaloon.PerformClick(); }
else if (c.Body == "Estate")
{ radEstate.PerformClick(); }
}
private void GearCheck()
{
if (radAutomatic.Checked == true)
{ c.GearBox = radAutomatic.Text; }
else if (radManual.Checked == true)
{ c.GearBox = radManual.Text; }
}
private void DisplayGear()
{
if (c.GearBox == "Manual")
{ radManual.PerformClick(); }
else if (c.GearBox == "Automatic")
{ radAutomatic.PerformClick(); }
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
currentfile = openFileDialog1.FileName;
saveToolStripMenuItem.Enabled = true;
Stream s1 = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(s1);
while (reader.Peek() != -1)
{
string str = reader.ReadLine();
Car c = new Car();
c.ReadString(str);
cars.Add(c);
}
curIndex = 0;
c = cars[curIndex];
DisplayCar();
reader.Close();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save everything in a dialog box
saveFileDialog1.ShowDialog();
// Open the file and save the information
Stream textOut = saveFileDialog1.OpenFile();
StreamWriter writer = new StreamWriter(textOut);
FormToObject();
string str = c.GetToString();
writer.WriteLine(str);
writer.Close();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save the file with the current file name
FileStream f1 = new FileStream(currentfile, FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(f1);
// get the object into a string
FormToObject();
StreamWriter file = new System.IO.StreamWriter(f1);
cars.ForEach(file.WriteLine);
file.Close();
}
private void btnAddInfo_Click(object sender, EventArgs e)
{
c.Information.Add(txtAddInfo.Text);
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtInformation.Text = "";
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void btnPreviousCar_Click(object sender, EventArgs e)
{
curIndex--;
if (curIndex < 0)
curIndex = cars.Count - 1;
c = cars[curIndex];
DisplayCar();
}
private void btnNextCar_Click(object sender, EventArgs e)
{
curIndex++;
if (curIndex >= cars.Count)
curIndex = 0;
c = cars[curIndex];
DisplayCar();
}
private void button1_Click(object sender, EventArgs e)
{
int a = cars.Count;
textBox1.Text = Convert.ToString(cars[2]);
}
private void btnEditCar_Click(object sender, EventArgs e)
{
txtBrand.ReadOnly = false;
txtModel.ReadOnly = false;
txtYear.ReadOnly = false;
txtPrice.ReadOnly = false;
txtNumMiles.ReadOnly = false;
txtAddInfo.ReadOnly = false;
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
private void yearToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
}
class Car
{
//List of properties
private string brand;
private string model;
private string year;
private string price;
private string numMiles;
private string body;
private string gearbox;
private List<string> information;
//Constructor
public Car() //Default Constructor
{
brand = "Unknown";
model = "Unknown";
year = "Unknown";
price = "Unknown";
numMiles = "Unknown";
information = new List<string>();
}
public Car(string str)
{
information = new List<string>();
ReadString(str);
}
public void ReadString(string str)
{
string[] words = str.Split('|');
int Nwords = words.Count();
brand = words[0];
model = words[1];
year = words[2];
price = words[3];
numMiles = words[4];
body = words[5];
gearbox = words[6];
information.Clear();
for (int i = 7; i < Nwords; i++)
information.Add(words[i]);
}
//Methods
public string Brand
{
get { return brand; }
set { brand = value; }
}
public string Model
{
get { return model; }
set { model = value; }
}
public string Year
{
get { return year; }
set { year = value; }
}
public string Price
{
get { return price; }
set { price = value; }
}
public string NumMiles
{
get { return numMiles; }
set { numMiles = value; }
}
public string Body
{
get { return body; }
set { body = value; }
}
public string GearBox
{
get { return gearbox; }
set { gearbox = value; }
}
public List<string> Information
{
get { return information; }
set { information = value; }
}
public string GetToString()
{
string str = "";
str += brand + "|";
str += model + "|";
str += year + "|";
str += price + "|";
str += numMiles + "|";
str += body + "|";
str += gearbox + "|";
for (int i = 0; i < information.Count(); i++)
str += information[i] + "|";
return str;
}
}
}
First thing that I noticed:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
// You already have list of cars, this line will copy your list
// into a new one, which is unnecessary work (you don't use it later).
// You don't need this:
List<Car> BrandSelect = new List<Car>(cars);
// the "c" here is not the "c" that is the field of your form
// it's a part of the syntax of linq query
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
// This method displays what is in the field "c" (this.c)
// ... and the content of "c" didn't change at all
DisplayCar();
}
the code here should be, for example:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
//beware this can be null
this.c = (from a in this.cars
where a.Brand == textBox1.Text
select a).FirstOrDefault();
}
[msdn] introduction to linq queries

Cannot delete selected a row from sqlite database

I want to delete the row by its Id but I cant delete it by its Id.like for example the values are
date|time|Floor|zone|Latitude|longitude and I want to delete a row of its while selecting it but i cannot.below is the class where i wrote all main functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
public void AddInfo()
{
//string f = Checkin.Floor_st;
Debug.WriteLine(Checkin.a);
string z = Checkin.Zone_st;
DbHelper Db_helper = new DbHelper();
Db_helper.Insert((new historyTableSQlite
{
Date = DateTime.Now.ToShortDateString(),
Time = DateTime.Now.ToShortTimeString(),
Zone = "D",
Floor = "7",
latitude =12344.66,
longtitude = -122.56
}));
}
// Delete specific contact
public void DeleteContact(int Id)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
var existingvalue = dbConn.Query<historyTableSQlite>("select * from historyTableSQlite where Id =" + Id).FirstOrDefault();
if (existingvalue != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingvalue);
});
}
}
}
//Delete all contactlist or delete Contacts table
public void DeleteAllContact()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
//dbConn.RunInTransaction(() =>
// {
dbConn.DropTable<historyTableSQlite>();
dbConn.CreateTable<historyTableSQlite>();
dbConn.Dispose();
dbConn.Close();
//});
}
}
}
below is the class where I show the values
public partial class History : PhoneApplicationPage
{
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
DbHelper Db_helper = new DbHelper();
//int Selected_HistoryId;
public static int Selected_HistoryId { get; set; }
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
public History()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Db_helper.AddInfo();
ReadHistoryList_Loaded();
// Selected_HistoryId = int.Parse(NavigationContext.QueryString["SelectedHistoryID"]);
}
public void ReadHistoryList_Loaded()
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();
//Latest contact ID can Display first
}
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
int Selected_HistoryId = listitem.Id;
}
}
public void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(Selected_HistoryId);
}
private void DeleteAll_Click(object sender, EventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.DeleteAllContact();//delete all db
DB_HistoryList.Clear();
ListData.ItemsSource = DB_HistoryList;
}
//public void updateDB(string fl,string zo,double la, double lo)
//{
// using (var db = new SQLiteConnection(dbPath))
// {
// var existing = db.Query<historyTableSQlite>("select * from historyTableSQlite").FirstOrDefault();
// if (existing != null)
// {
// existing.Floor = fl;
// existing.Zone = zo;
// existing.latitude = la;
// existing.longtitude = lo;
// db.RunInTransaction(() =>
// {
// db.Update(existing);
// });
// }
// }
//}
//public void AddDb(string fl, string zo, double la, double lo)
//{
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
// using (var db = new SQLiteConnection(dbPath))
// {
// db.RunInTransaction(() =>
// {
// db.Insert(new historyTableSQlite()
// {
// Date = DateTime.Today.ToShortDateString(),
// Time = DateTime.Now.ToShortTimeString(),
// Floor = fl,
// Zone = zo,
// longtitude = la,
// latitude = lo
// });
// Debug.WriteLine(db);
// });
// }
}
I am updating the table class so that it is easy to understand
public class historyTableSQlite : INotifyPropertyChanged
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id { get; set; }
private int idvalue;
private string dateValue = string.Empty;
public string Date {
get { return this.dateValue; }
set
{
if (value != this.dateValue)
{
this.dateValue = value;
NotifyPropertyChanged("Date");
}
}
}
private string timeValue = string.Empty;
public string Time
{
get { return this.timeValue; }
set
{
if (value != this.timeValue)
{
this.timeValue = value;
NotifyPropertyChanged("Time");
}
}
}
private string floorValue = string.Empty;
public string Floor
{
get { return this.floorValue; }
set
{
if (value != this.floorValue)
{
this.floorValue = value;
NotifyPropertyChanged("Floor");
}
}
}
public string zoneValue;
public string Zone
{
get { return this.zoneValue; }
set
{
if (value != this.zoneValue)
{
this.zoneValue = value;
NotifyPropertyChanged("Zone");
}
}
}
private double latValue;
public double latitude
{
get { return latValue; }
set
{
if (value != this.latValue)
{
this.latValue = value;
NotifyPropertyChanged("Latitude");
}
}
}
private double lonValue;
public double longtitude
{
get { return this.lonValue; }
set
{
if (value != this.lonValue)
{
this.lonValue = value;
NotifyPropertyChanged("Longitude");
}
}
}
// public string isMarkPoint { get; set; }
public historyTableSQlite()
{
}
public historyTableSQlite(string date,string time,string floor,string zone,double lat,double lng)
{
Date = date;
Time = time;
Floor = floor;
Zone = zone;
latitude = lat;
longtitude = lng;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
when i click the delete i.e the method delete_click i cant delete the row
EDIT: I cut and pasted your code incorrectly...you have very poor alignment :)
Okay I think I finally got your code to run, your problem is here
public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListData.SelectedIndex != -1)
{
historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
// this will get destroy when the function exits, it's local decalartion
int Selected_HistoryId = listitem.Id;
// History.Selected_HistoryId = listitem.Id;
// you need to set the Property not a local variable
}
}
you made a local variable named the same as the Property it should be
History.Selected_HistoryId = listitem.Id;
public void Delete_Click(object sender, EventArgs e)
{
Db_helper.DeleteContact(History.Selected_HistoryId);
}

Categories