I'm very new to C#/LINQ/WP7 development and am struggling to format data being returned from my LINQ query.
I have the following LINQ c# structure:
var boughtItemsInDB = from DBControl.MoneySpent bought in BoughtItemDB.BoughtItems
select bought;
BoughtItems = new ObservableCollection<DBControl.MoneySpent>(boughtItemsInDB);
The definition for MoneySpent is below;
[Table(Name = "MoneySpent")]
public class MoneySpent : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property and database column.
private int _itemId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int ItemId
{
get
{
return _itemId;
}
set
{
if (_itemId != value)
{
NotifyPropertyChanging("ItemId");
_itemId = value;
NotifyPropertyChanged("ItemId");
}
}
}
// Define item budget: private field, public property and database column.
private int _itemBudget;
[Column]
public int ItemBudget
{
get
{
return _itemBudget;
}
set
{
if (_itemBudget != value)
{
NotifyPropertyChanging("ItemBudget");
_itemBudget = value;
NotifyPropertyChanged("ItemBudget");
}
}
}
// Define item category: private field, public property and database column.
private string _itemCategory;
[Column]
public string ItemCategory
{
get
{
return _itemCategory;
}
set
{
if (_itemCategory != value)
{
NotifyPropertyChanging("ItemCategory");
_itemCategory = value;
NotifyPropertyChanged("ItemCategory");
}
}
}
// Define item description: private field, public property and database column.
private string _itemDescription;
[Column]
public string ItemDescription
{
get
{
return _itemDescription;
}
set
{
if (_itemDescription != value)
{
NotifyPropertyChanging("ItemDescription");
_itemDescription = value;
NotifyPropertyChanged("ItemDescription");
}
}
}
// Define item amount: private field, public property and database column.
private decimal _itemAmount;
[Column]
public decimal ItemAmount
{
get
{
return _itemAmount;
}
set
{
if (_itemAmount != value)
{
NotifyPropertyChanging("ItemAmount");
_itemAmount = value;
NotifyPropertyChanged("ItemAmount");
}
}
}
// Define item date: private field, public property and database column.
private DateTime _itemDateTime;
[Column]
public DateTime ItemDateTime
{
get
{
return _itemDateTime;
}
set
{
if (_itemDateTime != value)
{
NotifyPropertyChanging("ItemDateTime");
_itemDateTime = value;
NotifyPropertyChanged("ItemDateTime");
}
}
}
I need to format the data returned from the database, the following is stored in my DB:
ItemDateTime - DateTime, ItemDescription - String, ItemAmount - Decimal
I need to be able to to format the Date based on the current locale of the user, and format the decimal to 2 dp.
I am also not sure if I need to use IQueryable when I get the data results .
Any help would be much appreciated.
Thanks,
Mark
Since you don't provide enough detail - just a general idea
var boughtItemsInDB = from bought in BoughtItemDB.BoughtItems
select new { ItemDateTime = bought.ItemDateTime.ToString(), ItemDescription = bought.ItemDescription, ItemAmount = bought.ItemAmount.ToString("0,0.00") };
BUT formatting is better done in the control you use to display the data, not in the Linq query...
EDIT - after the addition frm OP:
From what I see the MoneySpent class is already prepared for "data binding"...
So formatting should be done in the displaying control... for some information see:
What is the WPF XAML Data Binding equivalent of String.Format?
http://www.codeproject.com/KB/WPF/binding_in_linq-sql.aspx
http://odetocode.com/code/740.aspx
http://www.codeguru.com/csharp/.net/wp7/article.php/c18933
Related
I have a (Devexpress) Datagrid-Control, which contains 3 columns of information. The names of the columns are generated automatically, each line describes one object of those:
private string fName;
private bool fCheck;
private DateTime fDate;
public bool checked
{
get { return this.fCheck; }
set { this.fCheck = value; }
}
public string fileName
{
get { return this.fName; }
set { this.fName = value; }
}
public DateTime createDate
{
get { return this.fDate; }
set { this.fDate = value; }
}
These Objects are saved in a List<> (dataSource):
gridFiles.DataSource = dataSource;
gridFiles.MainView.PopulateColumns();
Now, the names of the Columns are "checked","fileName" & "createDate". How can I change those?
Veeramani's answer does the job perfectly but just thought I should share an alternative solution with take less coding. You can also achieve this by adding a DisplayName attribute on each property. i.e:
My Class:
public class GridColumns
{
private string fName;
private bool fCheck;
private DateTime fDate;
[DisplayName("Checked Option")]
public bool Checked
{
get { return fCheck; }
set { this.fCheck = value; }
}
[DisplayName("File Name")]
public string fileName
{
get { return this.fName; }
set { this.fName = value; }
}
[DisplayName("Date Created")]
public DateTime createDate
{
get { return this.fDate; }
set { this.fDate = value; }
}
}
Then use it:
List<GridColumns> dataSourc = new List<GridColumns>();
dataGridView1.DataSource = dataSourc;
Using Gridview, we can rename the column name at Form_load() event...
gridView1.Columns["fileName"].Caption = "Your custom name";
as the question title says, I am trying to map a custom object to a db column on windows phone how can I do this? the exception I am getting: "Unable to determine SQL type for 'Layer'."
layer is a custom object, what is the correct way to store this, can someone please provide me with a example. thank you
code:
...
[Table]
public class Product : INotifyPropertyChanged, INotifyPropertyChanging
{
#region ID
//not autogenerated, this is from the client
private String _id;
[Column(IsPrimaryKey = true, IsDbGenerated = false, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public String Id
{
get { return _id; }
set
{
if (_id != value)
{
NotifyPropertyChanging("id");
_id = value;
NotifyPropertyChanged("id");
}
}
}
#endregion
#region Product Layer
private Layer _productlayer;
[Column]
public Layer ProductLayer
{
get { return _productlayer; }
set
{
if (_productlayer != value)
{
NotifyPropertyChanging("ProductLayer");
_productlayer = value;
NotifyPropertyChanged("ProductLayer");
}
}
}
#endregion
....
public class Layer
{
public string name{ get; set; }
public string des { get; set; }
public string pos { get; set; }
}
I'm using local database to store my data in Windows Phone 8 application. At first I have data stored in JSON object which is converted to my classes objects and then collection of these objects I try to store in local database. I was checking in debug mode and data is in those objects, but when I check database, it's empty.
This is how I move data from collection to database:
// Data context for the local database
private TablesDataContext tablesDB;
// Define the query to gather all of items.
var customersTablesInDB = from CustomerItem todo in tablesDB.CustomersTable
select todo;
// Execute the query and place the results into a collection.
CustomersTable = new ObservableCollection<CustomerItem>(customersTablesInDB);
foreach (Customer customer in customersList)
{
// Create a new item
CustomerItem newCustomer = new CustomerItem
{
Id = customer.id,
Number = customer.number.Value,
Name = customer.name,
Email = customer.email
};
// Add item to the observable collection.
CustomersTable.Add(newCustomer);
// Add item to the local database.
tablesDB.CustomersTable.InsertOnSubmit(newCustomer);
}
Here is my class for DataContext:
public class TablesDataContext : DataContext
{
// Specify the connection string as a static, used in main page and app.xaml.
public static string DBConnectionString = "Data Source=isostore:/Customers.sdf";
// Pass the connection string to the base class.
public TablesDataContext(string connectionString)
: base(connectionString)
{ }
// Specify a single table for the items.
public Table<CustomerItem> CustomersTable;
}
And here is my CustomerItem class:
[Table]
public class CustomerItem : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property and database column.
private int _id;
[Column(IsPrimaryKey = true, IsDbGenerated = false, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int Id
{
get
{
return _id;
}
set
{
if (_id != value)
{
NotifyPropertyChanging("Id");
_id = value;
NotifyPropertyChanged("Id");
}
}
}
// Define item name: private field, public property and database column.
private int? _number;
[Column]
public int? Number
{
get
{
return _number;
}
set
{
if (_number != value)
{
NotifyPropertyChanging("Number");
_number = value;
NotifyPropertyChanged("Number");
}
}
}
// Define completion value: private field, public property and database column.
private String _name;
[Column]
public String Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
NotifyPropertyChanging("Name");
name = value;
NotifyPropertyChanged("Name");
}
}
}
// Define completion value: private field, public property and database column.
private String _email;
[Column]
public String Email
{
get
{
return _email;
}
set
{
if (_email != value)
{
NotifyPropertyChanging("Email");
_email = value;
NotifyPropertyChanged("Email");
}
}
}
// Version column aids update performance.
[Column(IsVersion = true)]
private Binary _version;
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region INotifyPropertyChanging Members
public event PropertyChangingEventHandler PropertyChanging;
// Used to notify the data context that a data context property is about to change
private void NotifyPropertyChanging(String propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
#endregion
}
You are missing a "tablesDB.SubmitChanges()" after your foreach-loop.
I'm writing a wpf app. I have a local database (sqlCE) with two entity classes that correspond to different tables. The first one class is Account and the second one is Movements. There's a relationship one-to-many between the two tables: an account can have more movements.
Here is Account class:
[Table]
public class Account
{
.....other private fields...
private Int16 iDA;
private EntitySet<Movement> movements;
...other properties with column attribute....
//primary key
[Column(IsPrimaryKey = true, Storage="iDA", IsDbGenerated = true, AutoSync = AutoSync.OnInsert, DbType = "smallint")]
public Int16 IDA
{
get { return iDA; }
private set { iDA = value; }
}
//association
[Association(Storage = "movements", OtherKey = "IDA")]
public EntitySet<Movement> Movements
{
get { return movements; }
set { this.movements.Assign(value); }
}
public Account()
{
this.movements = new EntitySet<Movement>();
}
}
and here's Movement class:
[Table]
public class Movement
{
...other fields...
private Int16 iDA;
private int iDM;
private EntityRef<Account> myAcc;
//primary key
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert, DbType = "int NOT NULL IDENTITY", Storage = "iDM")]
public int IDM
{
get { return iDM; }
set { iDM = value; }
}
//property links the two tables
[Column(DbType = "smallint", Storage="iDA", isPrimaryKey=true)]
public Int16 IDA
{
get { return iDA; }
set { iDA = value; }
}
//association
[Association(Storage = "myAcc", ThisKey = "IDA")]
public Account MyAccount
{
get { return this.myAcc.Entity; }
set { this.myAcc.Entity = value; }
}
......
public Movement()
{
this.myAcc = new EntityRef<Account>();
}
}
I define IDA property to link the two tables. After that I write datacontext class:
public class DataBase : DataContext
{
public Table<Account> AccountTable
{
get { return this.GetTable<Account>(); }
}
public Table<Movement> MovementTable
{
get { return this.GetTable<Movement>(); }
}
public DataBase(string connection) : base(connection) { }
}
In mainclass I create database, but when i try to populate it with an account object, I get a sql exception! I can insert data calling InsertOnSubmit(Account a) without problems, but when I call SubmitChanges() the program stops and the exception says "The column can not contain null values. [Column name = IDA, Table name = Account]".
Anyone can help me?
Try using DbType = "smallint not null identity" and CanBeNull = false parameters for the Column attribute of the IDA field.
I've solved my problem, changing in Int the IDA property in both classes and making some adjustment.
I have a Common Field Object:
public class Field
{
public string Name { get; set; }
public string oldName { get; set; }
private object _Value = null;
public object Value
{
get
{
return _Value;
}
set
{
_Value = value;
}
}
private FieldType _fieldType = FieldType.Normal;
public FieldType FieldType
{
get
{
return _fieldType;
}
set
{
_fieldType = value;
}
}
private bool _isKey = false;
public bool IsKey
{
get
{
return _isKey;
}
set
{
_isKey = value;
}
}
}
a Common Record Object:
public class Record
{
public string TableName{get;set;}
pubilc FieldCollection _fieldcollection = new FieldCollection();
public FieldCollection FieldCollection
{
get
{
return _fieldcollection;
}
set
{
_fieldcollection = value;
}
}
}
The Data from database to convert to Record Object,and then I want to Binding the Record Data to the Control,but it's not working.
I want to know how can I Binding Data like:
textBox1.DataBindings.Add("Text", listBox1.DataSource , "BarDesc");
I think you want to drag and drop a BindingSource control onto your winform in Design-Time.
Set the BindingSource's DataSource property > Object > Record class. Then set the BindingSource's DataMember.
Select your control (eg Textbox) and set its DataBinding property to the bindingSource control's DataMember.
HTH, at least it should point you in the right direction.