I have two entites with association. I create a dataGridView by drag and drop from objects Data Source and manually binding from to list. Everything works fine with one entity. Is there any possibility of create one dataGridView with two entities(Zamow and ZamSkany) by drag and drop + manually filling? I can do this by view (on SQL side) but in same cases I'd like to have other possibilities.
pg = new PGEntities();
BindingList<Zamow> myList;
var query = (from zam in pg.Zamow where zam.Rok == 2012 select zam).Take(100);
MyList = new BindingList<Zamow>(query.ToList());
zamowBindingSource.DataSource = MyList;
Yes, try to create Class, let say a ViewZamowAndSamSkany
public class ViewZamowAndSamSkany
{
public string Data { get; set; }
public string Proforma { get; set; }
//and Others Properties
}
and now, rebuild your project and from the Objects Data Source add the ViewZamowAndSamSkany then drag-drop to your Form as a DataGridView and you can apply the linq-entites inner join
var query = (from zam in pg.Zamow
join skany in zam.NUMBER equals skany.NUMBER
where zam.Rok == 2012
select new ViewZamowAndSamSkany
{
Data = zam.Data,
Proforma = zam.Proforma
}).Take(100);
MyList = new BindingList<ViewZamowAndSamSkany>(query.ToList());
zamowBindingSource.DataSource = MyList;
Related
I am working on a project in C# using Entity Framework. Using EF, I connect to database that has a dozen of tables, and none of the views.
What I want to accomplish is create object in code that would represent sql view (i.e. three DB tables joined for presenting useful data).
I need this so I could create binding data source for the datagirdview. Right now I manually wrote SQL query for joining three tables and creating a list which then I define as datagridview.DataSource
This troubles me because of hard design about presenting the data in the datagridview. I have to manually write everything in code, and also not sure how to accomplish everything I need.
I would be more satisfied if I could create new class that would represent above and then in Designer View add Data source as object and view it in Designer mode and edit columns right there.
My query which does the job is as follows:
using (var context = new csModelEntitites())
{
var listaVozila = (from voz in context.Vozilo
join var in context.Varijanta on voz.VarijantaID equals var.ID
join mod in context.Model on var.ModelID equals mod.ID
join mar in context.Marka on mod.MarkaID equals mar.ID
select new
{
voz.ID,
voz.VIN,
Vozilo = mar.Naziv + " " + mod.Naziv + " " + var.Motor,
voz.GodProizvodnje,
voz.RegOznaka,
voz.RegDo
}).ToList();
VozilaPrikaz.DataSource = null;
VozilaPrikaz.DataSource = listaVozila;
foreach (DataGridViewColumn c in VozilaPrikaz.Columns)
{
if (c.HeaderText == "GodProizvodnje")
c.HeaderText = "Godina proizvodnje";
if (c.HeaderText == "RegOznaka")
c.HeaderText = "Registarska oznaka";
if (c.HeaderText == "RegDo")
c.HeaderText = "Registriran do";
I want to create class that would do the similar. Any help appreciated.
You can bind a user defined custom class to a datagridview and edit the column headers in the designer-view. The steps would be.
First create the class whose public properties you would want as the datagridview column name. For example I created the class Class1.cs in my project folder. Later on , you can edit the column header or other related property in the designer.
namespace WindowsFormsApp2
{
public class Class1
{
public string x1 { get; set; }
public string x2 { get; set; }
public Class1(string x1, string x2)
{
this.x1 = x1;
this.x2 = x2;
}
}
}
Next in the designer view, pull an empty DataGridView from the ToolBox.
Right click on the DataGridView->Properties->DataSource->Add Project DataSource ->
Then in the dialog box, choose "Object" as "Data Source Type".
Then under "Select the data Objects" if you expand the tree , you would see your class.
In my case, I select "Class1" , the same class which I had earlier created.
Then using edit columns, you can change any header text or so.
In the code file, the data needs to be filled in as below:
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
private BindingSource bindingSource1 = new BindingSource();
public Form1()
{
InitializeComponent();
bindingSource1.Add(new Class1("gdc1", "gdc2"));
dataGridView1.DataSource = bindingSource1;
}
}
}
That's the . The datagridView is all set.
Today I've faced one very strange behavior. After creating an object with Linq query and object initializer with setting property of List<string> type the original collection and the collection that the object contains have different entries order.
public class PrintHeaderModel
{
public List<string> Ships { get; set; }
}
...
var shipsList = new List<string>() { /* some items */ };
var model = (from inv in db.invoices
where inv.ListID == id && inv.RealmID == realmId
select new PrintHeaderModel()
{
Ships = shipsList,
}).FirstOrDefault();
After that the orders of entries in model.Ships and shipsList are different
Notes:
db is DbContext instance (I'm using Entity Framework and MySQL database)
shipsList is not sorted after it's filled
If I create model object without Linq (just with "new"), the order of entries is the same in model and in the list
The order becames correct if I reassign model.Ships right after model is created:
model.Ships = shipsList; // after that the order of entries is correct
The order of entries in model.Ships is not the same always. It changes randomly without any changes in code or database
Where was I wrong?
I have never used Linq-to-Sql before in an application but I used LinqPad to develop a query and just wanted to paste it into into my code.
It's not so simple. I guessed that I need a DataContext to handle the connection but I still get errors because the view names aren't recognised.
Do I have to use the designer and create all the View/Table- classes? Is there a more simple way?
This is the query. Don't need any updates - just this one query....
var q = from user in V020
join userapp in V010 on user.SPP_USER_ID equals userapp.SPP_USER_ID
join app in V030 on userapp.SPP_AW_ID equals app.SPP_AW_ID
join tx in V040 on app.SPP_AW_ID equals tx.SPP_AW_ID
join appber in V070 on app.SPP_AW_ID equals appber.SPP_AW_ID
join ber in V050 on appber.SPP_AW_BEREICH_ID equals ber.SPP_AW_BEREICH_ID
where app.SPP_AW_AKTIV && user.SPP_USER_ID == "userid" && tx.SPP_AW_SPR == "de" && ber.SPP_AW_SPR == "de"
orderby ber.SPP_BER_SORTNB
select new {
AppName = app.SPP_AW_KURZBEZ, Url = tx.SPP_AW_URL, Label = tx.SPP_AW_NAME, Description = tx.SPP_AW_BESCHR,
Bereich = ber.SPP_AW_BERNAME,
Owner = app.SPP_AW_VERANTW, Remote = app.SPP_AW_REMOTE
}
;
Create a dbml file, as above
Open the 'server explorer'
Connect to your database
Drag the tables you wish to use from your database connection onto the designer
Party time
In EF I have used context.Database.ExecuteSQLCommand to run a stored procedure without the need to use domain modal designer (and hence generating the tables). I am sure you can do something similar in Linq to SQL. However this will not support the linq query you have. You need to move all the logic in stored procedure.
SiteManagedRepairDetails Model properties:
public long RepairID { get; set; }
public int RepairLineID { get; set; }
DAL method:
public static int UpsertData(SiteManagedRepairDetails obj)
{
XYZ.DBContexts.VoidsDBContext context = new XYZ.DBContexts.VoidsDBContext();
var results = context.Database.ExecuteSqlCommand("p_XYZDetailsUpsert #RepairID, #RepairLineID"
, new SqlParameter("#RepairID", obj.RepairID)
, new SqlParameter("#RepairLineID", obj.RepairLineID)
);
return 0;
}
I am creating a Pie Chart and its name-value pair are being retrieved from the database.
how to read the row details in order to get the values and store it one property ?
public override void OnApplyTemplate()
{
Ram.DataContext = new List<UsageRAM>()
{ new UsageRAM() { name = "Available" , value =/*how to get the value here*/ },
new UsageRAM() { name = "Used" , value =/*how to get the value here*/ }};
base.OnApplyTemplate();
}
public class UsageRAM
{
public string name { get; set; }
public double value { get; set; }
}
EDIT
--Answer which worked for me--
using (DB db = new DB())
{
var row = (from c in db.UsageRAMs
orderby c.UsageRamID descending
select c).First();
Ram.DataContext = new List<UsageRAM>()
{ new UsageRAM() { name = "Available" , value = row.Available},
new UsageRAM() { name = "Used" , value = row.Used }};
If you're using EF, simply add a new model to your project and include the requried table(s) in this model. Then you can use the newly created Entities object to read your db values as follows:
var Rows = context.YourTableName.Where(YourCondition).ToArray();
You can then iterate over the Rows collection using foreach or something.
If you need to read values from a single row, you may want to use First instead of Where above. That will return a single object whose properties will map to your db fields and can directly be assigned in the example code you posted in the question.
EXAMPLE
Say your model's Entity class is named MyEntities and it contains the table UsageRam, which has two fields Available and Used. Then it will take the following code:
using(MyEntities e = new MyEntities)
{
var Row = e.MyTable.First(x => x.UsageRamID = **[ID]**);
MessageBox.Show("Available=" + Row.Available.ToString() + ",Used=" + Row.Used.ToString();
}
I have just shown values in message box, you can assign them to anything you want.
Another Example
using(MyEntities e = new MyEntities)
{
var Rows = e.MyTable.Where(x => x.UsageRamID > 10 && x.UsageRamID < 20);
foreach(var Row in Rows)
MessageBox.Show("Available=" + Row.Available.ToString() + ",Used=" + Row.Used.ToString();
}
EXAMPLE 3
The code in your updated post appears fine to me, though I do have some doubts about the db design, but given your table is indexed on RamUsageID column, this should give you correct results without much performance impact. I generally prefer lambada expressions over query, so I'd rather write it like:
db.RamUsage.OrderByDescending(x => x.RamUsageID).First()
i am currently working with SQL CE & WPF . in the middle of coding i struck with no idea of converting the dataset of a Database to my observablecollection which is binds to the UI Controllers like Listbox and listview.
plz guide me , if possible with code !!
Let's say your DataSet contains a Table named Person and that Person has columns Id, Name, and Age.
You first create a Person class to hold your Person data:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Then you use LINQ to populate your ObservableCollection:
var people = new ObservableCollection<Person>(
dataset.Tables["Person"].AsEnumerable().Select(p => new Person
{
Id = p.Field<int>("Id"),
Name = p.Field<string>("Name"),
Age = p.Field<int>("Age")
}));
You will need to add the following assembly reference to your project in order to use the AsEnumerable<T>() and Field<T>() extension methods:
System.Data.DataSetExtensions (in System.Data.DataSetExtensions.dll)
Edit
In response to your comment, you would normally process each change you make to the data immediately rather than try to convert the whole ObservableCollection back to the DataSet. So, for example, if you add a new Person to your ObservableCollection, you would also want to add that Person to the DataSet.
Add a person:
var table = dataSet.Tables["Person"];
var row = table.NewRow();
row["Id"] = person.Id;
row["Name"] = person.Name;
row["Age"] = person.Age;
table.Rows.Add(row);
Delete a person:
var table = dataSet.Tables["Person"];
var row = table.AsEnumerable().Where(p => p.Id == person.Id);
row.Delete();
Update a person (say you want to change the age to 37):
var table = dataSet.Tables["Person"];
var row = table.AsEnumerable().Where(p => p.Id == person.Id);
var row["Age"] = 37;
You might also want to look into LINQ to SQL because it automates a lot of this stuff.