[Q] How to delete/add an item from a ListBox? - Windows Phone 7 Software Development

Hi there,
I have a ListBox bounded to a query (linq to xml)
Dim CASDAs XDocument = XDocument.Load("./Data/CASD.xml")
Dim CAS_Query As System.Collections.IEnumerable = From query In Cartridge_Doc.Descendants("Cartridges") Order By _
CStr(query.Element("AA")) Descending, CStr(query.Element("AA"))
Select New Cartridge_Data With {.AA1 = CStr(query.Element("AA")), _
.BB1= CStr(query.Element("BB")), _
.CC1 = CStr(query.Element("CC"))}
Me.ListBox_1.ItemsSource = CAS_Query
Now, what I need to do is to select an item and have the option to delete it.
So far, I always got a run-time exception when trying this
Me.ListBox_1.Items.Remove(Me.ListBox_1.SelectedItem)
System.InvalidOperationException was unhandled
Message=Operation not supported on read-only collection.
So far I have tried a lot of options without any luck.
Any help will be greatly appreciated!
Thanks in advance.

Stick your Linq result in an ObservableCollection, bind this to the Listbox and delete the item directly from the underlaying collection.

emigrating said:
Stick your Linq result in an ObservableCollection, bind this to the Listbox and delete the item directly from the underlaying collection.
Click to expand...
Click to collapse
Please, can you poost a little code to do that? I'm fairly new to this collections world.
On the other hand, once the item got deleted, how the Listbox gets refreshed?
Thanks!

You have to set up an NotifyPropertyChanged class to keep the listbox updated with your collection. The default phone list application template that comes with Visual Studio shows you how to do this. I think its's in c# though and it looks like you're coding in VB. I'm sure there's examples in VB you can find on the web with a little searching.

Ren13B said:
You have to set up an NotifyPropertyChanged class to keep the listbox updated with your collection. The default phone list application template that comes with Visual Studio shows you how to do this. I think its's in c# though and it looks like you're coding in VB. I'm sure there's examples in VB you can find on the web with a little searching.
Click to expand...
Click to collapse
My ListBox takes its data from an XML file via query.
Which strategy do you think is the best?
To first delete the Xelement then refresh the ListBox?
Or deleting from the item from the ListBox, then update the XML file?
Sorry but I have all the samples from MS and didn't find any phone list one.
Any code will be greatly appreciated!

Oops. It's called "Windows Phone Databound Application". Attached is a screenshot of the project if it makes it easier for you to find it.
It's hard to post code because I don't know what your xaml looks like and bindings have to be set there for it to work. The best thing you can do is load the above project and play around with it.
You never have to refresh the items in the listbox. A bound listbox updates itself when an item in the collection changes. Change the collection and your listbox will reflect those changes. The NotifyPropertyChanged class is what triggers the listbox to update itself.

I do C#, not VB but the following should give you some idea.
Code:
public class Model : INotifyPropertyChanged
{
public string Title { get; set; }
public string Blurb { get; set; }
public event PropertyChangedEventHandler PropChanged;
public void NotifyPropertyChanged(String _propName)
{
if (null!=PropChanged)
{ PropChanged(this, new PropertyChangedEventArgs(_propName)); }
}
}
The above is your model, create any properties you need there - i.e. one per item of data in your XML file.
Next, you need to create an ObservableCollection somewhere, for the sake of simplicity let's stick it in your MainPage.xaml.cs file for now, so;
Code:
public partial class MainPage : PhoneApplicationPage
{
public ObservableCollection<Model> Items { get; set; }
public MainPage()
{
InitializeComponent();
this.Items = new ObservableCollection<Model>();
MyListBox.ItemsSource = this.Items;
WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(new Uri("http://your.server.here/datafile.xml");
}
public void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (Stream s = e.Result)
{
XDocument xd = Xdocument.Load(s);
var XMLdata = (from q in doc.Descendants("Item") select new Model()
{
Title = (string)q.Element("Title"),
Blurb = (string)q.Element("Blurb")
}
foreach (Model m in XMLdata)
{
this.Items.Add(m);
}
}
}
public MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = (ListBox)sender;
if (lb.SelectedIndex == -1)
return;
this.Items.Remove(lb.SelectedItem)
}
}
This will create a collection named Items as well as tell your ListBox (named MyListBox) to get it's data from said collection. Then it will read (asynchroniously) the XML file from the web and copy each item of data into your collection.
When you select an item in your ListBox it will be deleted from the ObservableCollection which in turn will remove it from the view (ListBox). At this stage you want to include code to also remove this from your actual XML file and so on of course. But the idea is that you work on your Collection only and your View will update based on what is changed - automagically.
Please note, the above code may or may not work out of the box. Written directly here on the forums so it hasn't gone thru VS2010's excellent IntelliSense. Also, the above code is in no way the most efficient way of doing certain things, but it gives you an idea as to what code you need to write to handle your scenario.
While I wrote this I see you've got an answer above which directs you to the VS template - use that and everything should become clear. All you have to remember is that perform operations on the Collection - not directly on the ListBox and you'll be fine.

Emigrating and Ren13B,
Thanks to both of you for the help. Very appreciated!
Will take both advices to see what comes up.
Thanks!

Related

[REQ] Need some info on MDIs in Smart device applications using C#.net

Hi all guys
i am new to C# and .net stuff as i was working with C++ for many years
i want to know that is it possibhle that i can have an MDI Child Form on my main Form and want it to return me some data
like for example i have my main Form has a "settings" button
when i click on "settings" button it should show a small MDI child form which has all the settings and return some data (i'll take care of data but i dont know how to return through a form)
thnx in advance
Well...as far as 'returning' data from the Form, you can't do that as a "return" call because Forms are objects, so the constructor cannot have a return type, however you can have a method that will set a variable in another class (that is public) to the data you want to return ... You can call this method when the form is closing.
I am not entirely sure if you can achieve the 'small form INSIDE another form' without creating your own control. I am not sure how practical/possible this would be, but you can try 1 of the following: extend the Control class (to make a control) or override the OnPaint of a new Form. This way you can define where stuff goes, and what gets drawn onto the screen.
I have used this piece of code in the past, which worked great.
in my example frmA was an MDIchildform of the main (MDIparent)
frmA()
{
public int a=0;
private btn_click(blabla)
{
frmOptions options = new frmOptions(this);
dialog.ShowDialog();
if(dialog.DialogResult == DialogResult.Yes)
{
dosomethingwith(a);
}
else
{
donothingwith(a);
}
}
}
public partial class frmOptions : Form
{
frmA callingform = null;
public frmOptions(frmA x)
{
callingform = x;
}
private void dosomething()
{
callingform.a = value;
}
private void btnSaveSettings_click()
{
this.DialogResult = DialogResult.Yes;
}
private void btnCancelSettings_click()
{
this.DialogResult = DialogResult.No;
}
}
good luck

[SDK] XFControls - Advanced UI SDK [UPDATED w/ Sense UI Example!]

This is an Advanced UI SDK for developing finger-friendly Application UIs.
The reason for developing this SDK was mainly to learn about programming for Windows Mobile and the Compact Framework 3.5. I also developed this SDK because I could not find good UI controls that gave total display control to the programmer while taking care of all of the Physics, windowing, and frame buffering AND was open source.
Finally, this SDK was originally developed as part of the XDAFacebook application that I am currently developing.
I am releasing this SDK and its source so that people can have a good foundation to build finger-friendly Windows Mobile applications, and so that programmers starting off in the Windows Mobile world won't have to start from scratch when creating useful UI Controls.
Here are some of the features and uses of this SDK.
Features:
Fully customizable
Easily create custom UI Controls
Resolution independent
Full physics for rendering smooth scrolling
Uses:
Quickly create UI controls
Develop full UI SDKs
Learn basic UI programming for .net CF 3.5
I ask that if you use these controls, please provide feedback so that everyone can benefit!
Thank you and I hope you find these controls useful!
SDK Documentation
Even though the controls are easy to implement, they can seem intimidating at first. Here is an over-view of the core pieces to the SDK:
The IXFItem Interface:
Here are Properties of the interface
PHP:
XFPanelBase Parent { get; set; } // The item's List container
XFItemState State { get; set; } /* An Enum to describe the current item's state
This could include things like [B]Selected[/B] or [B]Normal[/B]*/
Bitmap Buffer { get; set; } // This is the item's cache buffer. Allows for speedy rendering
XFItemStyle Style { get; set; } // CSS like style object. Allows for easy customization
XFItemType ItemType { get; set; } /* Enum to label the type of the current object.
For example, [B]Clickable[/B] or [B]Display[/B] meaning the item won't change*/
The following are the methods that need to be implemented
PHP:
int GetHeight(); /* This returns the height of the item. This value is usually calulated
but in some instances is static. The value should be cached because this method
is called several times during the rendering process.*/
void ResetHeight(); // What ever needs to be done to reset the height cache
void ItemPaint(Graphics g, int x, int y); // Where the magic happens. More on this later
XFItemClickResult GetClickResult(); // An enum is return with what the action of clicking this item was.
The main part of the interface is the ItemPaint method. This method is called from the XFPanelList and passes a Graphics object created from the Buffer Bitmap of the Item. In this method, you do all of your graphics logic, drawing it with the supplied graphics object. The x and y are any offset numbers that should influence when the objects are based. Most of the time, these numbers will be 0, 0.
Because the programmer has total control over how the item is rendered, special care must be used when creating the items, to draw all the features with respect to the XFItemStyle object. This object usually is created in CTOR. An example of the XFItemStyle object being created in one of the SenseUI XFItem's CTORs:
PHP:
public SenseItem()
{
ItemType = XFItemType.Clickable;
Style = new XFItemStyle()
{
BoarderBottomColor = Color.FromArgb(189, 182, 189),
DashStyleBottom = System.Drawing.Drawing2D.DashStyle.Dash,
TextColor = Color.Black,
TextFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular),
SelectedTextFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular),
SecondaryTextFont = new Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular),
SelectedSecondaryTextFont = new Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular),
SecondaryTextColor = Color.FromArgb(57, 52, 57),
SelectedTextColor = Color.White,
SelectedBackgroundColor = Color.FromArgb(43, 36, 43),
SelectedSecondaryTextColor = Color.FromArgb(182, 178, 182),
Padding = 11,
PaddingBottom = 12,
PaddingLeft = 10,
PaddingRight = 16
};
}
You will also notice that the ItemType is also set here.
How you use the Style is a little more involved. In the ItemPaint, the programmer should base all of the features off of what is in the Style object. Here is an example of how the above Style object was used in the ItemPaint method:
PHP:
public void ItemPaint(Graphics g, int x, int y)
{
int width = Parent == null ? Screen.PrimaryScreen.WorkingArea.Width : Parent.Width;
XFControlUtils.DrawBoarders(Style, g, 0, 0, width, GetHeight());
int currX = Style.PaddingLeft;
int currY = Style.PaddingTop;
int mHeight = 0;
int sHeight = 0;
if (Icon != null)
currX += _iconSize + Style.PaddingLeft;
SizeF mText = new SizeF();
if (!string.IsNullOrEmpty(MainText))
{
mText = XFControlUtils.GetEllipsisStringMeasure(width - currX - Style.PaddingRight, MainText, Style.TextFont);
MainText = XFControlUtils.EllipsisWord(width - currX - Style.PaddingRight, MainText, Style.TextFont);
}
SizeF sText = new SizeF();
if (!string.IsNullOrEmpty(SecondaryText))
{
sText = XFControlUtils.GetEllipsisStringMeasure(width - currX - Style.PaddingRight, SecondaryText, Style.SecondaryTextFont);
SecondaryText = XFControlUtils.EllipsisWord(width - currX - Style.PaddingRight, SecondaryText, Style.SecondaryTextFont);
}
mHeight = (GetHeight() / 2) - ((int)mText.Height / 2);
if (!string.IsNullOrEmpty(SecondaryText))
{
mHeight = (GetHeight() / 2) - _textSpace - (int)mText.Height;
sHeight = (GetHeight() / 2) + _textSpace;
}
if (State == XFItemState.Selected)
{
XFControlUtils.DrawBackgroundSelected(Style, g, x, y, width, GetHeight());
if (!string.IsNullOrEmpty(MainText))
using (SolidBrush b = new SolidBrush(Style.SelectedTextColor))
g.DrawString(MainText, Style.SelectedTextFont, b, currX, mHeight);
if (!string.IsNullOrEmpty(SecondaryText))
using (SolidBrush b = new SolidBrush(Style.SelectedSecondaryTextColor))
g.DrawString(SecondaryText, Style.SelectedSecondaryTextFont, b, currX, sHeight);
}
else
{
if (!string.IsNullOrEmpty(MainText))
using (SolidBrush b = new SolidBrush(Style.TextColor))
g.DrawString(MainText, Style.TextFont, b, currX, mHeight);
if (!string.IsNullOrEmpty(SecondaryText))
using (SolidBrush b = new SolidBrush(Style.SecondaryTextColor))
g.DrawString(SecondaryText, Style.SecondaryTextFont, b, currX, sHeight);
}
if (Icon != null)
XFControlUtils.DrawAlphaFirstPix(g, Icon, Style.PaddingLeft, Style.PaddingTop);
}
That is as complex as it gets. Other than doing normal Event Handling for ClickReturns, this is all that is required to create beautiful UI Controls for your application.
I hope that this helps! Feel free to PM me or post a reply if you need further clarification.
Class List
Form Controls:
XFPanelContainer - The main control that interacts with the Form.
XFPanels:
XFPanelBase - Basic building block. Handles most of the generic functionality
XFPanelList - Can add IXFItem items.
XFPanelHeader - The top header bar for an XFPanelContainer
XFItems
IXFItem - Interface that all XFItems inherate
XFItemSimpleText - Simple item that displays text
XFItemBack - Special item that allows a panel to slide back
XFItemLoading - Item that allows for work to be down in the background.
XFControlUtils: Library of static, useful utilities for this SDK
DrawAlpha - Draws an image with a supplied Graphics object with a specific level of opacity
DrawAlphaFirstPix - Draws an image and renders all pixels that are the same color as pixel (1,1) are 100% transparent
DrawJustifiedString - draws a justified string
GetEllipsisStringMeasure - Takes a string and if it is more than the supplied width, clips the string and adds a trailing "..." at the end
EllipsisWord - same as the GetEllipsisStringMeasure, except it ellipsis at the words and not at the char level.
GetSizedString - Takes a string and adds "\n" so that the string wraps according to the supplied width
Many Others!
Sense UI Example
Here is a working example. I made this Sense UI example in about 3 hours 15 hours. It isn't complete but gives a good example of how to/why use this SDK. There are 3 screenshots of what this demo looks like.
I'll explain some of the pieces of code when I get some time later today.
The other great example of how to use this SDK is the XFAFacebook Application.
The source for this project is located @ http://code.google.com/p/xda-winmo-facebook/source/browse/#svn/trunk/XFSenseUI
There are a few screenshots of the XDAFacebook application included.
Finally, a quick start tutorial.
Start a new Smart Device project.
Add a reference to the XFControls.dll
Place the following lines of code in the Form1 constructor (after the InitializeComponent()
Code:
XFPanelContainer container = new XFPanelContainer();
container.Dock = DockStyle.Fill;
Controls.Add(container);
XFPanelList list = new XFPanelList();
container.SetMainPanel(list);
list.ShowScrollbar(true);
for (int i = 0; i < 50; i++)
{
list.Add("This is item " + i);
}
Run the project and you will get an output like the "SimpleText.png"
It's that easy!
UPDATE: I've added the XFSense to the Google Code page and have made some pretty extensive updates to it. I've added a few controls including sliders, toggles, checkboxes and radio buttons. It still isn't complete but I will be working to make it a full fledge Sense SDK.
Stay tuned!
Releases:
Initial Release - 9/1/10
When major updates occur, the DLLs will be posted here. The best thing to do is pull the source from the Google Code page and use that.
This will guarantee the freshes code will be used for your projects
Instructions:
Download and unzip the latest XFControls.zip from below.
Add the .dll as a reference.
Program!
The source can be found at: http://code.google.com/p/xda-winmo-facebook/source/browse/#svn/trunk/XDAFacebook/XFControls
List of downloads:
10/6/10 - Updated for speed and better scrolling! - XFControls 0.2.zip
9/1/10 - Initial upload - XFControls 0.1.zip
Other things I might have missed
Reserved Other
Sounds interesting! Definitely looking forward to some screenshots.
kliptik said:
Sounds interesting! Definitely looking forward to some screenshots.
Click to expand...
Click to collapse
Screenshots are up!
Only 3 downloads?! Hmmm.... I figured more people would be interested in a finger-friendly and open source UI SDK...
Is there something wrong with my posts? Are they too confusing?
Let me know what I can do to help! This has taken me a good deal of time to write and I would hope that it would be of use to someone else...
joe_coolish said:
Only 3 downloads?! Hmmm.... I figured more people would be interested in a finger-friendly and open source UI SDK...
Is there something wrong with my posts? Are they too confusing?
Let me know what I can do to help! This has taken me a good deal of time to write and I would hope that it would be of use to someone else...
Click to expand...
Click to collapse
Just DL'd a copy. I'm super swamped at the moment trying to get the next release of KD-Font out, but I'll try and check this out when I get a chance.
Thank you for your contribution!
I will definitely give this a test run at some point. Good work!
you have to add you own graphics to this sdk?
janneman22 said:
you have to add you own graphics to this sdk?
Click to expand...
Click to collapse
yes, this is a UI SDK. it is used to create user controls. The core code handles all the caching and physics, but the programmer must create the actual controls. including the graphics. look at the sense UI example to see how you can implement your own custom UI controls. like i said in the post, it only took about 3 hours to create those controls. most of which was spent creating graphics.
joe_coolish said:
yes, this is a UI SDK. it is used to create user controls. The core code handles all the caching and physics, but the programmer must create the actual controls. including the graphics. look at the sense UI example to see how you can implement your own custom UI controls. like i said in the post, it only took about 3 hours to create those controls. most of which was spent creating graphics.
Click to expand...
Click to collapse
oh right. but does it place controls in the toolbox, or have you to create the controls hard coded?
i could help you to make some grapics packages for this sdk
Ok, I've updated the binaries to be the latest and greatest. The scrolling is super smooth and things are starting to look pretty good!
I also will be updating the XFSense and I'll probably be extending it a little more because I plan on bringing it into the XDA Facebook app.
As always, let me know what you think!
EDIT: Oh, and to answer the question about adding objects to the toolbox, I have not added the OCX files (or whatever they are) so that they can be added to the tool box. But, after you've added the container and the panels, everything is logic after that, so adding the items to the toolbox really doesn't benefit too much.
As far as graphics, I would love help with graphics! Send me a PM and we'll talk!
joe_coolish said:
Here is a working example. I made this Sense UI example in about 3 hours. It isn't complete but gives a good example of how to/why use this SDK. There are 3 screenshots of what this demo looks like.
I'll explain some of the pieces of code when I get some time later today.
The other great example of how to use this SDK is the XFAFacebook Application.
The source for this project is located @ http://code.google.com/p/xda-winmo-facebook/source/browse/
There are a few screenshots of the XDAFacebook application included.
Finally, a quick start tutorial.
Start a new Smart Device project.
Add a reference to the XFControls.dll
Place the following lines of code in the Form1 constructor (after the InitializeComponent()
Code:
XFPanelContainer container = new XFPanelContainer();
container.Dock = DockStyle.Fill;
Controls.Add(container);
XFPanelList list = new XFPanelList();
container.SetMainPanel(list);
list.ShowScrollbar(true);
for (int i = 0; i < 50; i++)
{
list.Add("This is item " + i);
}
Run the project and you will get an output like the "SimpleText.png"
It's that easy!
Click to expand...
Click to collapse
Very nice control. I downloaded the sample (had problem with missing XFControl project but downloaded it from code.google).
Have a couple questions, how would i go about adding image to a child panel?
What I'm trying to so is have about 75 items on the main screen and each item will have sub-panel, when clicking on sub-panel I need to have label x2 and image.
Also when compiling the project I get error:
"Error 1 'XFControls.XFPanels.XFPanelHeader' does not contain a definition for 'BackgroundImage' and no extension method 'BackgroundImage' accepting a first argument of type 'XFControls.XFPanels.XFPanelHeader' could be found (are you missing a using directive or an assembly reference?) C:\downloads\C#\XFSenseUI\XFSenseUIDemo\Form1.cs 39 24 XFSenseUIDemo"
Alright, I'll post an example if I get some time in a bit. But as for the error, it is because the Core XFControls has been modified since the last time I updated this thread. You can download the freshes code from the google code page or use the attached DLL. I'd suggest the Google Code page, since it gets updated more frequently. But then you get all the XDAFacebook with it, so it can also be negative.
Basically to add an image to an XFItem to be added to the XFPanelList, you can either create your own item by inheriting from the IXFItem and doing all the image manipulation in the ItemDraw() method.
For an example of how to do that, look at the XFItemImageDisplay item in the XFControls.XFPanels.XFPanelItems namespace.
If you need something specific, let me know and I'll see if I can whip up an example
I'm new to C# and the compact framework so sample would be good...
Thanks
JarekG said:
I'm new to C# and the compact framework so sample would be good...
Thanks
Click to expand...
Click to collapse
Ok, could you describe how you want the control to look? Also, what you want to supply to the constructor? IE a path for an image, upper text, lower text, maybe even some style things. ETC

[Q] Standard and Professional

Newbie here. Maybe someone can give me some direction. I am writing an app for both standard and professional. I have 2 projects in my solution. One is for standard the othe is for professional. I am not sure if this is the right way or not but what I want to do is when the app opens it checks to see what platform is running and then runs the correct project. Any help would be greatly appreciated.
It is possible to create a single project that is capable of running on both platforms but there is quite a bit of groundwork you will have to do first.
Firstly, the main differences.
Standard : No touch screen i.e. No Mouse events. All user input is via the keyboard, buttons, D-PAD and ENTER. No Open/Save dialogboxes, you have to present the files to the user yourself. Message dialogs appear full screen.
Professional : None of the above limitations.
The are a few pointers here:
http://msdn.microsoft.com/en-us/library/bb985500.aspx
The following code will detect the platform and set the variable 'SmartPhone' to 1 (true) if the version is 'Standard'
Code:
#define MAX_LOADSTRING 100
int SmartPhone;
TCHAR szReturn[MAX_LOADSTRING];
SystemParametersInfo(SPI_GETPLATFORMTYPE,MAX_LOADSTRING,szReturn,false);
SmartPhone=wcscmp(TEXT("SmartPhone"),szReturn)^1;
Your processing code may have code such as:
Code:
if(SmartPhone)
{
........ Standard Stuff.......
}
else
{
......... Professional Stuff........
}
Note also that code dealing with a WM_LBUTTONDOWN message will never be executed on a smartphone, as WinMo Standard never generates this message.
It may seem a pain, but you only have one executable to deliver for both platforms.
As an example, here's one I prepared earlier.
http://forum.xda-developers.com/showthread.php?t=509413
more info
I am coding with VB. What I was thinking was creating a class project and making that the startup project. Within the class the VB would check the platform and then run the correct project.
Should work:
To get the Platform type in .NET CF have a look at:
http://msdn.microsoft.com/en-us/library/ms229660(VS.90).aspx
It's also listed in the VS Help.
I am using VS2008 TS and cf3.5. I have tried several methods and still can't get any to work. I must be missing a reference or something. Here is some code I can't get to work.
If SystemSettings.Platform = WinCEPlatform.PocketPC Then
txtDeviceType.Text = "Windows Mobile Professional"
ElseIf SystemSettings.Platform = WinCEPlatform.Smartphone Then
txtDeviceType.Text = "Windows Mobile Standard"
Else
txtDeviceType.Text = "Not Windows Mobile"
End If
Also tried this.
Public Enumeration WinCEPlatform
Dim instance As WinCEPlatform
I also tried getversionex but couldn't get it to work either.
I only code .NET in C# but there is virtually no difference.
Try this: You will have to add the reference to Microsoft.WindowsCE.Forms;
Right click on References in the Solution Explorer, click on Add Reference, in the .NET Tab, pick it out of the list.
Code:
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsCE.Forms;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WinCEPlatform Platform = new WinCEPlatform();
Platform = SystemSettings.Platform;
label1.Text = Platform.ToString();
}
}
}
Works a treat!
Let's let Red Gate's Reflector translate the IL into VB.
It also reveals that the compiler rips outs the middle variables and goes straight for :
Code:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
Me.label1.Text = SystemSettings.Platform.ToString
End Sub
I am getting an error on this InitializeComponent. Another question. Can I add a class project and use this code to point to the correct project?
Drop the InitialiseComponent function, that is only used used in C#
In VB in Form1 the only code you need is
Code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = Microsoft.WindowsCE.Forms.SystemSettings.Platform.ToString
End Sub
End Class
This code works and puts "YES" in the box if run on a PPC
Code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Microsoft.WindowsCE.Forms.SystemSettings.Platform = Microsoft.WindowsCE.Forms.WinCEPlatform.PocketPC Then
Label1.Text = "YES"
End If
End Sub
End Class
Ok. I got it to work with the following code. But I have another problem. My app is a very simple app. I want it to work on PPC2003 and smartphones. I have 2 different forms for standard and professional. Now the problem is that if I use .net compact framework 3.5 then the device has to have that installed. So if I want to the app to work on older devices it won't work without the .net compact framework. If I use .net compact framework 2.0 then I lose the ability to use the code to determine if its standard or professional. I was hoping there was a way to include the 3.5 CF into my app cab but I haven't seen it. I am currently using VS2008 whcih only allows you 2.0 CF and 3.5 CF. I was thinking about using VS2005 and use 1.0 CF so it would work on all Windows mobile devices. But then I would again lose the ability to use the code. Any ideas would be appreciated.
Shared Sub Main()
Dim Platform As New WinCEPlatform()
Platform = SystemSettings.Platform
If Platform = "1" Then
Application.Run(
New Pro())
ElseIf Platform = "2" Then
Application.Run(
New Standard())
End If
End Sub
Using VS2005 I started a new project and selected SmartDevice 1.0. Now I have some issues.
1. Trying to determine either standard or professional. I am trying to use the Pinvoke to do this. No luck so far. I get an error on ByVal nFolder As ceFolders.
2. The code I was using to play a .wav file no longer works.
Dim myplayer As New System.Media.SoundPlayer(New IO.MemoryStream(My.Resources.Dice))
myplayer.Play()
3. I had resource files for images and a wav file so my code to use these no longer work.
Me.PictureBox1.Image = My.Resources.red_die_1_th
1. I'll have a look at it. Watch this space.
2. The SoundPlayer object is only available from .net CF 3.5 onwards. To play sounds you my have to PInvoke PlaySound()
http://msdn.microsoft.com/en-us/library/ms229685(v=VS.80).aspx
3. Should work, but maybe there's a difference in the frameworks. Microsoft's catch-all is that not all methods, properties etc. are supported in all .NET or .NET CF. versions. You may end up doing it in two stages, create a bitmap image from the resource, then pass that to the picturebox.
The answer to 1 is below. This works in C# under VS2003 .NET CF 1.0 but it is only in C#, I do not have VB installed on this machine. You will have to reverse engineer it into VB yourself, not too difficult. The important code is the DLLImport definition, the SPI_GETPLATFORMTYPE definition, and the call of the function in Form1_Load().
On program start "PocketPC" appears in the label on screen.
Code:
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace PInvTest
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.MainMenu mainMenu1;
[DllImport("coredll.dll", EntryPoint="SystemParametersInfo", SetLastError=true)]
private static extern int SystemParametersInfo(
int uiAction, int uiParam, string pvParam, int fWinIni);
private const int SPI_GETPLATFORMTYPE = 257;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
string Platform = new string(' ',20);
SystemParametersInfo(SPI_GETPLATFORMTYPE,Platform.Length,Platform,0);
label1.Text=Platform;
}
}
}

[Q] ListBox Binding Error with Observable Collection

Hi all!
Since days I have a problem now. I have an app that manage Entries in a list A. If one of these entries End-Date is today I whant that entry to be shown in a second list B. This is checked when I return from the "addNewItem" Window so I use onNavigatedTo.
Code:
// Static Variables
public static ObservableCollection<Item> lstToday = new ObservableCollection<Item>();
public static ObservableCollection<Item> lstWeek = new ObservableCollection<Item>();
public static ObservableCollection<Item> lstAll = new ObservableCollection<Item>();
// Constructor
public MainPage()
{
InitializeComponent();
MessageBox.Show("Initialize Component");
lbToday.ItemsSource = lstToday;
lbWeek.ItemsSource = lstWeek;
lbAll.ItemsSource = lstAll;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
DateTime currentDate = DateTime.Now;
foreach (Item item in lstAll)
{
if (item.endDate.ToString("yyyy'-'MM'-'dd").Equals(currentDate.ToString("yyyy'-'MM'-'dd")))
{
lstToday.Add(item);
MessageBox.Show("Item '" + item.name + "' added to Todaylist");
}
}
}
private void appBarNew_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri(string.Format("/EditAddItem.xaml"), UriKind.Relative));
}
After that I get an "System.Diagnostics.Debugger.Break();" error that doesn't occur when I delete "lbToday.ItemsSource = lstToday;" to avoid the ListBox Binding.
With lbAll ist runs without any problems!
Can I bind the Listbox direct to the ObservableCollection in XAML=
I really don't know, whats to do. So do you?
It would make my day!
Thanks!
What is the exception message and stack trace when the exception is thrown? (you can browse the properties of the exception using visual studio).
Your code actually works for me (although I had to make some assumptions about what is in lstAll as you don't mention that, and you may have an error in the DataTemplate for the listbox for binding your Item class)
Things to try:
Have you tried it with non static observable collections?
Use binding assignments in the xaml rather than setting the itemssource directly (e.g. using a viewmodel). Then you can let the phone engine worry about when to do the assigments. If you do that don't forget to set the page's datacontext property.
Try it with simple collections of strings first (rather than binding an 'item' class) so you can check it's working without a datatemplate.
Hope you fix it.
Ian

[Q] PhoneGap and Ajax with database?

Hi all,
I recently finished learning how to create an APK using PhoneGap with code written using HTML5, CSS3 and Javascript.
Now, I would like to create a simple database app but I am not sure how to proceed. From what I learned about PhoneGap, everything can only be written in HTML5, CSS and Javascript coding. How do I get information from a database(flat-file or MySQL), display the data and edit it similar to how one would do using Ajax(I currently don't know how to code in ajax)? Is this possible with PhoneGap? How? Do I need a framework like JQuery Mobile to do this?
There would only be one page/view:
- displaying what is in the table
- and editing/adding new data to the table
Thank you.
using frameworks such as jquery mobile is a better option. u can use ajax calls to server to populate data. create a server side code that responds to ajax calls from app and fetch data from my sql and sends back the data either as json or xml
Falen said:
Hi all,
I recently finished learning how to create an APK using PhoneGap with code written using HTML5, CSS3 and Javascript.
Now, I would like to create a simple database app but I am not sure how to proceed. From what I learned about PhoneGap, everything can only be written in HTML5, CSS and Javascript coding. How do I get information from a database(flat-file or MySQL), display the data and edit it similar to how one would do using Ajax(I currently don't know how to code in ajax)? Is this possible with PhoneGap? How? Do I need a framework like JQuery Mobile to do this?
There would only be one page/view:
- displaying what is in the table
- and editing/adding new data to the table
Thank you.
Click to expand...
Click to collapse
If you just want your app to have a local database then HTML5 already does that for you. I've used this library in the past and had no problems with it at all...
http://html5sql.com/
I wrote an app that imported a CSV file into a database. It was a very basic app, written as proof of concept for a bigger project when I first started developing web apps for mobile. Here's a basic version of importing a CSV and using html5sql to create a table with it...
Code:
function createDatabase() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("/sdcard/external_sd/temp/PRODUCTS.CSV", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var csv = evt.target.result;
var lines = csv.split("\n");
var i = 1;
html5sql.openDatabase("com.archer.testapp.db", "Test DB", _dbSize);
html5sql.process("DROP TABLE IF EXISTS products; " +
"CREATE TABLE IF NOT EXISTS products (linecode int, description varchar(255), barcode varchar(25), price int, stock int); ", function() {
function addRow() {
var line = lines[i].split(",");
var sql = "INSERT INTO products (linecode, description, barcode, price, stock) values (" +
line[0] + ", " +
"'" + line[2] + "', " +
"'" + line[1] + "', " +
line[6] + "," +
line[13] + ")";
html5sql.process(sql);
var pd = i / lines.length * 100;
$(".progress-bar").css("width", pd + "%");
i++;
if (i < lines.length) {
setTimeout(addRow, 2);
}
}
addRow();
}, function(error, failingQuery) {
alert("Error : " + error.message + "\r\n" + failingQuery);
});
};
reader.readAsText(file);
}
There's obviously stuff in there that won't be relevant and you'll need to change. Also I had a global variable, _dbSize, that was the initial size (in bytes) of the database, and there's some stuff in there about a progress bar. Use it or delete it - it won't affect the database being created.
Also, note the use of the addRow() function that calls itself. This was to enable the function to run asynchronously, which is needed if you want to be UI friendly (nothing will update whilst doing the import if you just import everything in one go).
However, since you mention AJAX then that may not be relevant. In which case you're just looking at API calls for whatever service is holding your database.
Hi friend ! If you're new to hybrid development, I highly recommend you to take a look at Ionic. It would help you on so many levels ! http://ionicframework.com/
About your issue, you can always define a REST API using your favorite backend (I know it can be done very easily with Laravel framework in PHP using MySQL DB). I prefer using Firebase ! https://www.firebase.com/
Firebase and Ionic framework based on AngularJS are such perfect match that half your code is already done before you knows it.
Happy coding !

Categories

Resources