I am trying to insert data from frm1 and frm2 into SQL Server at the same time. frm1 contains product information (barcode, qty , price, vat, total etc) and frm2 (contains payments information like cash and change). The idea is that when the user clicks the btnfrm2 the data from frm1 should be passed into frm2 (but not displayed), and in frm2 the user gives the payment info (cash and change) and after clicking btnsave the data from frm1 and frm2 should be inserted into the database.
I created a class, and a method to pass data to frm2.
internal void mbushe(string[] args)
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
arka_data ad = new arka_data();
ad.NR = int.Parse(txtnrfatures.Text);
ad.VLERATVSHTOTAL = float.Parse(textBox1.Text);
ad.BARKODI = int.Parse(dataTable.Rows[i][0].ToString());
ad.EMERTIMI = dataTable.Rows[i][1].ToString();
ad.SASIA = int.Parse(dataTable.Rows[i][2].ToString());
ad.CMIMI = int.Parse(dataTable.Rows[i][3].ToString());
ad.TVSH = int.Parse(dataTable.Rows[i][4].ToString());
ad.NENTOTALI = float.Parse(txttotali.Text);
ad.ZBRITJA = float.Parse(txtzbritja.Text);
ad.TOTALI = float.Parse(totali.Text);
ad.KOHA = DateTime.Now;
ad.KASIERI = lbluser.Text;
ad.KLIENTI = cmbklienti.Text;
ad.VLERAETVSH = float.Parse(dataTable.Rows[i][7].ToString());
ad.VLERAPATVSH = float.Parse(dataTable.Rows[i][6].ToString());
ad.NRATIKUJVE = int.Parse(lblnumri.Text);
ad.TOTALIPCS = float.Parse(dataTable.Rows[i][5].ToString());
}
}
public class arka_data
{
public int NR { get; set; }
public int BARKODI { get; set; }
public string EMERTIMI { get; set; }
public int SASIA { get; set; }
public float CMIMI { get; set; }
public float TVSH { get; set; }
public float TOTAL { get; set; }
public float NENTOTALI { get; set; }
public float ZBRITJA { get; set; }
public float TOTALI { get; set; }
public DateTime KOHA { get; set; }
public string KASIERI { get; set; }
public string KLIENTI { get; set; }
public float VLERAETVSH { get; set; }
public float VLERAPATVSH { get; set; }
public int NRATIKUJVE { get; set; }
public float TOTALIPCS { get; set; }
public float VLERATVSHTOTAL { get; set; }
}
and in the second form I will use the elements of method( from first form)
cmd.Parameters.Add(new SqlParameter("#nrfatures", mbushe.NR);
cmd.Parameters.Add(new SqlParameter("#klienti", mbushe.Barkodi)); etc
while mbushe is the method from first form
Best if your forms use MVP pattern, AKA inherit from interface. Example
public class MyForm1 : Form, IView1
{
public string SomeData { get { return MyControl1.Text } }
. . . .
}
public class MyForm2 : Form, IView2
{
public string SomeOtherData { get { return MyControl1.Text } }
. . . .
}
Then you create persister, which collects the data from both forms and saves
public class FormDataPersister
{
private IView1 _v1;
private IView2 _v2;
public class FormDataPersister(IView1 form1Data, IView2 form2Data)
{
_v1 = form1Data;
_v2 = form2Data;
}
public void Save()
{
// HERE collect your data into parameters and SAVE
// EXAMPLE
. . . . .
cmd.Parameters.Add(new SqlParameter("#klienti", _v1.Barkodi));
cmd.ExecuteNonQuery();
}
}
I would recommend that you build an object from the data on the UI and then either
Pass it along (from form to form) while filling it with more and more information or
Store it in some kind of repository so every part of the code-base has access to (preferred)
When the user then clicks the btnsave button on Form2, you simply call a code that persists that object.
This way you are keeping the form, its data, and the database interaction logic separate from each other.
Related
I am trying to make my code more compromised, and use overall less, however currently I'm running into the problem of not being able to send a list of Objects sorted by linq as a parameter.
the problem is in this part of the code:
List<Afspraken> dataAfspraken = new List<Afspraken>();
public Form1()
{
InitializeComponent();
fillListsForLinq();
loadReceptionData();
}
private void fillListsForLinq()
{
dataAfspraken = data.getAfsprakenData();
//here it fills the list with Afspraken objects
}
private void loadReceptionData()
{
private void loadReceptionGrid
var receptionToFinnish =
(from AFspraken in dataAfspraken
where Afspraken.factuur_betaald == true && Afspraken.volledig_afgerond == false
join Users in dataUsers on Afspraken.gekoppelde_klant equals Users.id
select new
{
Id = Afspraken.id,
Klant = Users.gebruikersnaam,
Betaald = Afspraken.factuur_betaald,
Afgerond = Afspraken.volledig_afgerond
}).ToList();
changeDataviewReception(receptionToFinnish);
}
private void changeDataviewReception(List<Object> listData)
{
dgvReceptionData.DataSource = listData
}
the Afspraken class looks like this
public class Afspraken
{
public int id { get; set; }
public bool bevestigd { get; set; }
public DateTime datum { get; set; }
public int gekoppelde_klant { get; set; }
public int gekoppelde_monteur { get; set; }
public string benodigde_hadelingen { get; set; }
public decimal totaalprijs { get; set; }
public bool klaar { get; set; }
public bool factuur_betaald { get; set; }
public bool volledig_afgerond { get; set; }
public string opmerkingen { get; set; }
}
How do I get receptionToFinnish as a parameter into changeDataviewReception?
receptionToFinnish will be a list full of objects of an anonymous type. But your method requires a List<object>. This is now allowed since a list is not a variant type.
Say for example that you have a list of bananas and want to give it to someone that wants a list of fruits. This will not work since that other person might try to add an orange to the list of bananas.
To fix this, cast the values to object explicitly, for example:
select new
{
Id = Afspraken.id,
Klant = Users.gebruikersnaam,
Betaald = Afspraken.factuur_betaald,
Afgerond = Afspraken.volledig_afgerond
} as object
I always failed to load DataGridView customers. They always freeze on record #8
I have a Customers class under my apps namespace like this
public class Customers
{
public string No { get; set; }
public string ID { get; set; }
public string NoSPU { get; set; }
public string Name { get; set; }
public string Telp { get; set; }
public string Kavling { get; set; }
public string Tipe { get; set; }
public string Pokok { get; set; }
public string Bunga { get; set; }
}
And this is my code to add item to customersBindingSource in my DataGridView and I put in formLoad event
string query = "select * from customer";
customersBindingSource.Clear();
Int32 i = 0;
MySqlDataReader reader = dx.findQuery(query);
while (reader.Read())
{
i++;
customersBindingSource.Add(new Customers() {
No = i.ToString(),
ID = reader.GetString("id"),
NoSPU = reader.GetString("nospu"),
Name = reader.GetString("nama"),
Telp = reader.GetString("telp"),
Kavling = reader.GetString("kavling"),
Tipe = reader.GetString("tipe")
});
MessageBox.Show(i.ToString()+" OKE");
}
reader.Close();
If I'm trying with data less than 8 on customers table it always work, but when I add new customers more than 8 it's always freeze, customers forms doesn't show up. Are there's a limitation or something wrong with my code?
try like this way:
// Create and populate the list of DemoCustomer objects
// which will supply data to the DataGridView.
List<DemoCustomer> customerList = new List<DemoCustomer>();
customerList.Add(DemoCustomer.CreateNewCustomer());
customerList.Add(DemoCustomer.CreateNewCustomer());
customerList.Add(DemoCustomer.CreateNewCustomer());
// Bind the list to the BindingSource.
this.customersBindingSource.DataSource = customerList;
hope it can help you.
I have this error during save on update data in my mongo db.
this is erorr:
Save can only be used with documents that have an Id.
this is my model:
public ModelKorisici () { }
[BsonId(IdGenerator = typeof(CombGuidGenerator))] // posajvljivaa se greška kod BSON tipa podataka kod ID-a,preuzoteo s dokumentacije drivera 1.5
public Guid Id { get; set; }
[BsonElement("ime")]
public string ime { get; set; }
[BsonElement("prezime")]
public string prezime { get; set; }
[BsonElement("lozinka")]
public string lozinka { get; set; }
[BsonElement("email")]
public string email { get; set; }
[BsonElement("kor_ime")]
public string kor_ime { get; set; }
[BsonElement("uloga")]
public string uloga { get; set; }
}
My code for update is here:
public void urediKorisnika(ModelKorisici korisnik)
{
MongoCollection<ModelKorisici> kljenti = GetTasksCollection();
kljenti.Save(kljenti);
}
Can anyone help?
I'm not sure what are you trying to do but your error is in following code block
public void urediKorisnika(ModelKorisici korisnik)
{
MongoCollection<ModelKorisici> kljenti = GetTasksCollection();
kljenti.Save(kljenti);
}
Here are you trying to store collection to itself. I believe GetTasksCollection() return collection from MongoDB and then you are trying to store it into itself again. see kljenti.Save(kljenti);
You need to create instance of ModelKorisici and save it into kljenti
Your code should look something like:
public void urediKorisnika(ModelKorisici korisnik)
{
MongoCollection<ModelKorisici> kljenti = GetTasksCollection();
var model = new ModelKorisici();
model.ime = ...
...
kljenti.Save(model);
}
So I am lost on how to send data back to the object once it is added to the dictionary.
With this data structure that I made http://pastebin.com/HicZMzAt for full code
I have
public class Computer
{
public Computer() { }
public Computer(int _year)
{
dropOffDate = DateTime.Now;
RepairFinished = false;
Year = _year;
}
private DateTime dropOffDate;
public bool RepairFinished;
private readonly int Year;
public static string Plate;
private string make;
public string Make
{
get { return make; }
set { make = value; }
}
public string Model { get; set; }
public string ComputerTicketId { get; set; }
public bool IsLaptop { get; set; }
public Location Location { get; set; }
public int HoursWorked { get; set; }
public double PartsCost { get; set; }
public DateTime DateFinished { get; set; }
// public virtual double TotalCost { get { TotalCost = (this.HoursWorked * 50) + PartsCost; } set; }
public void ComputerPickUp()
{
Console.WriteLine("Cost is {0:C} ", this.HoursWorked);
RepairFinished = true;
}
where I want to calculate the different cost for repairs for each dropped of system.
public class Laptop : Computer
{
public bool HasCharger { get; set; }
public Laptop(int year, bool _HasCharger)
: base(year)
{
HasCharger = _HasCharger;
}
//TODO overide for COST ! + 10
and I have a desktop class also were the cost of repair is cheaper for Desktop systems.
But I am using
public static class Repair
{
public static Dictionary<string, object> RepairLog { get; set; }
}
to track the repairs
and now I am lost in the UI part of the program to get the data to figure out the pricing.
public class RepairUI
{
....edited
Repair.RepairLog = new Dictionary<string, object>();
....
Computer = new Desktop(ComputerYear, HasLcd);
And that is how I am lost about the way to handle the data , the class data for each repair unit (desktop / NBK ) is organized in the dictionary and now I want to get the data and edit the repair cost of the object , but I can't seem to figure out how to reach the object.
So how could I ask upon pick up hours worked and calculate the info for the unit ?
This sounds like a great moment to use an Interface!
public Interface IRepairable
{
double GetRepairCost();
}
Then redefine Computer
public class Computer : IRepairable
{
public double GetRepairCost()
{
return (this.HoursWorked * 50) + PartsCost;
}
}
and Laptop
public class Laptop : Computer
{
public new double GetRepairCost()
{
return base.GetRepairCost() + 10;
}
}
and Repair
public static class Repair
{
public static Dictionary<string, IRepairable> RepairLog { get; set; }
}
And now you have a dictionary of things that you can call GetRepairCost() on! These could be Computers or Laptops or a mix, it doesn't matter to the RepairLog!
I am sorry if it has already been answered but I can't find any solution. Here is my (little) problem. Also all my apologies if the terms I use are approximate, I am far from being a skilled C# developer
Note that I think my problem is similar to this one Entity Framework validation error for missing field, but it's not missing?
I have a table "Tweets" with a tweet_id field (bigint) which is my primary key.
I use the following class to load the table :
class TwitterDbContext : DbContext
{
public TwitterDbContext() : base("Twitter")
{
}
public DbSet<Stream> Streams { get; set; }
public DbSet<StreamParameter> StreamParameters { get; set; }
public DbSet<Tweet> Tweets { get; set; }
}
public class Tweet
{
public Tweet()
{
}
[Key]
public long tweet_id { get; set; }
public string tweet { get; set; }
public long creator { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string language { get; set; }
public DateTime created_at { get; set; }
public DateTime registered_at { get; set; }
public long? in_reply_to { get; set; }
public bool retweeted { get; set; }
}
I have an other class to store within the code execution all the fields used by the Tweet table. For the need here, let's imagine I manually create it that way
private void Test_Button_Click(object sender, RoutedEventArgs e)
{
Twts twtReceived = new Twts();
twtReceived.tweet_id = 1;
twtReceived.tweet = "test";
twtReceived.creator = 1;
twtReceived.latitude = -1;
twtReceived.longitude = -1;
twtReceived.language = "a";
twtReceived.created_at = DateTime.Now;
twtReceived.registered_at = DateTime.Now;
twtReceived.in_reply_to = 1;
twtReceived.retweeted = true;
AddTweet(twtReceived);
}
Now here is the AddTweet method
static public void AddTweet(Twts twtReceived)
{
try
{
// update the tweet data in the database
using (var TwitterDb = new TwitterDbContext())
{
Tweet twt = new Tweet()
{
tweet_id = twtReceived.tweet_id,
tweet = twtReceived.tweet,
creator = twtReceived.creator,
longitude = twtReceived.longitude,
latitude = twtReceived.latitude,
language = twtReceived.language,
created_at = twtReceived.created_at,
registered_at = twtReceived.registered_at,
in_reply_to = twtReceived.in_reply_to,
retweeted = twtReceived.retweeted
};
TwitterDb.Tweets.Add(twt);
TwitterDb.SaveChanges();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.InnerException.ToString());
}
}
I constantly have the same error message:
Cannot insert the value NULL into column 'tweet_id', table
'Twitter.dbo.Tweets'; column does not allow nulls. INSERT fails.
The thing is that when I spy on "TwitterDb.Tweets.Local" after TwitterDb.Tweets.Add(twt); I correctly have tweet_id set to 1.
Any idea where is the issue?
Try marking your tweet_id field with following (instead of just [Key]), if this is a primary key column where you want to provide values yourself
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
If it is an auto-increment, then remove explicit assignments to this field and mark it as 'Identity' instead:
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]