PetaPoco in WinForms - c#

How to commit changes done in DataGridView using PetaPoco ? Something like :
namespace PetaPocoTest
{
public partial class Form1 : Form
{
PetaPoco.Database db = new PetaPoco.Database("PgConnection");
IEnumerable<customers> allCustomers;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
allCustomers = db.Query<customers>("SELECT * FROM customers");
mGrid.DataSource = allCustomers .ToList();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
db.Save("customers", "custumer_id", allCustomers);
}
}
}

Try my answer Here
This is the simplest and easiest and can do what you want so far

I finally got it. I just wasted hours on something so obvious :\
namespace PetaPocoTest
{
public partial class Form1 : Form
{
PetaPoco.Database db = new PetaPoco.Database("PgConnection");
IEnumerable<customers> allCustomers;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
allCustomers = db.Query<customers>("SELECT * FROM customers");
mGrid.DataSource = allCustomers .ToList();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
foreach (var a in allCustomers)
{
db.Save("customers", "custumer_id", a);
}
}
}
}

Related

Struggling to add to ListBox

So I'm making this small program for my assignment at university and I'm finding it hard to add to my list in my form. Here is my code:
public partial class WorkOutBeam : Form
{
Check checkLib;
public BindingList<ListBox> list;
public WorkOutBeam()
{
InitializeComponent();
}
public void StartForm(object sender, EventArgs e)
{
list = new BindingList<ListBox>();
listBox1.DataSource = list;
}
private void NewForce_Click(object sender, EventArgs e)
{
NewForceName forceItem = new NewForceName();
forceItem.Show();
}
public void AddToForceList(string name)
{
list.Items.Add(name);
}
}
NewForceName class below:
public partial class NewForceName : Form
{
public WorkOutBeam workOutBeam;
public NewForceName()
{
InitializeComponent();
}
private void OkButton_Click(object sender, EventArgs e)
{
if (NewForceNames.Text != "")
{
ReferToLibs();
workOutBeam.AddToForceList(NewForceNames.Text);
Close();
}
}
private void ReferToLibs()
{
workOutBeam = new WorkOutBeam();
}
private void NewForceName_Load(object sender, EventArgs e)
{
}
}
So I say to my program, "give me a new force." When it does, it initializes a new form of "NewForceName." I type into a text box and click 'Ok', this starts a public method shown below:
The list is a binding list which refers to the listBox as a data source. However the program tells me that the Items part is inaccessible due to its protection but I don't know how to add it as public. I tried looking in the properties of my listBox but to no avail.
Give this a shot:
public partial class WorkOutBeam : Form
{
Check checkLib;
// public BindingList<ListBox> list; // get rid of this for now
public WorkOutBeam()
{
InitializeComponent();
}
/*public void StartForm(object sender, EventArgs e)
{
list = new BindingList<ListBox>();
listBox1.DataSource = list;
}*/
private void NewForce_Click(object sender, EventArgs e)
{
NewForceName forceItem = new NewForceName(this); // pass a reference to this
// instance of WorkoutBeam
forceItem.Show();
}
public void AddToForceList(string name)
{
// we should do some more things here, but let's keep it simple for now
listBox1.Items.Add(name);
}
}
And
public partial class NewForceName : Form
{
public WorkOutBeam workOutBeam;
public NewForceName( WorkoutBeam beam ) // we take a WorkoutBeam instance as CTOR param!
{
InitializeComponent();
workoutBeam = beam;
}
private void OkButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(NewForceNames.Text))
{
workOutBeam.AddToForceList(NewForceNames.Text);
Close();
}
}
// DO NOT create new WorkoutBeams every time. Use the original.
/*private void ReferToLibs()
{
workOutBeam = new WorkOutBeam();
}*/
}
Disclaimer: I did not address each and every problem in this code. This is just enough so that it should "work" as intended.

Can not transfer values in list between classes

my problem is that i can't transfer values in the list between two classes in WFA
public partial class Example : Form
{
public List<string> myList = new List<string>();
private void Btn1_Click(object sender, EventArgs e)
{
new Example2().Show();
}
private void Example_Activated(object sender, EventArgs e)
{
if (myList.Count == 0)
{
//...
}
else
{
//...
}
}
public partial class Example2 : Form
{
static Example ex = new Example();
private void Btn2_Click(object sender, EventArgs e)
{
ex.myList.Add("something");
Close();
}
Form "Example" is shown first. Then i click "Btn1" on the screen, and form "Example2" appears. When i click "Btn2" on "Example2" form, myList should get new value of "something" and "Example2" closes. But this part of script
private void Example_Activated(object sender, EventArgs e)
{
if (myList.Count == 0)
{
//...
}
else
{
//...
}
}
shows that myList has no values (myList.Count equals 0).
What can i do?
you need to reference existing Example form with data from Example2 form. static Example ex is another (static) instance, which doesn't have data.
public partial class Example : Form
{
private List<string> myList = new List<string>();
private void Btn1_Click(object sender, EventArgs e)
{
var e2 = new Example2();
e2.SetMainForm(this);
e2.Show();
}
public void AddItem(string item)
{
myList.Add(item);
}
private void Example_Activated(object sender, EventArgs e)
{
if (myList.Count == 0)
{
//...
}
else
{
//...
}
}
}
public partial class Example2 : Form
{
private Example ex;
private void Btn2_Click(object sender, EventArgs e)
{
ex.AddItem("something");
Close();
}
public void SetMainForm(Example e1)
{
ex = e1;
}
}

How I can write code in button's event of a form, from another form in a same name space?

I write code which get my data source data from a gridview in this form. But I can't find a way to change my data and save my context. Because my savebtn is on another form.
Here is my code:
namespace FactorEntity
{
public partial class CustomerResearchForm : MetroFramework.Forms.MetroForm
{
FactorEntities contex;
public CustomerResearchForm()
{
InitializeComponent();
}
private void CustomerResearchForm_Load(object sender, EventArgs e)
{
}
private void CResearchGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
CustomerUpdateAndDelete CustomerUpdateAndDelete = new CustomerUpdateAndDelete();
contex = new FactorEntities();
{ var sendergrid=(DataGridView)sender;
int customercode = Convert.ToInt32(sendergrid.Rows[e.RowIndex].Cells[1].Value);
var customer = from _customer in contex.tblCustomers where
_customer.CustomerCode==customercode select _customer;
CustomerUpdateAndDelete.tblCustomerBindingSource.DataSource = customer.ToList();
CustomerUpdateAndDelete.Show();
if (CustomerUpdateAndDelete.tblCustomerBindingNavigatorSaveItem.CheckOnClick == true)
{
contex.SaveChanges();
}
}
}
}
}
And this is my CustomerUpdateAndDelete form which tblCustomerBindingNavigatorSaveItem is here
namespace FactorEntity
{
public partial class CustomerUpdateAndDelete : MetroFramework.Forms.MetroForm
{
public CustomerUpdateAndDelete()
{
InitializeComponent();
}
private void CustomerUpdateAndDelete_Load(object sender, EventArgs e)
{
}
private void tblCustomerBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
}
}
}

Add items from a listbox to another listbox on another form

Here is my code.
private void PlaceOrder_Click(object sender, EventArgs e)
{
MenuBox.Items.Clear();
TotalBox.Items.Clear();
total.Clear();
ordertotal = 0;
}
I want to add what is in the menu box to a another list box on another form.
Update
(added by jp2code)
Form1 (Main):
namespace WindowsFormsApplication1 {
public partial class RESTAURANT : Form
{
double soup = 2.49;
double ordertotal;
public RESTAURANT()
{
InitializeComponent();
}
private void RESTAURANT_Load(object sender, EventArgs e)
{
}
private void Add_Click(object sender, EventArgs e)
{
MenuBox.Items.Add("Soup");
TotalBox.Items.Add(String.Format("{0:C}", soup));
ordertotal += soup;
total.Text = Convert.ToString(String.Format("{0:C}", ordertotal));
}
private void TotalBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void PlaceOrder_Click(object sender, EventArgs e)
{
new AreYouSure().Show();
this.Show();
MenuBox.Items.Clear();
TotalBox.Items.Clear();
total.Clear();
ordertotal = 0;
}
}
}
Form2 (Confirmation)
namespace WindowsFormsApplication1 {
public partial class Confirmation : Form
{
public Confirmation()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Confirmation_Load(object sender, EventArgs e)
{
}
private void MenuBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
When clicking the 'Send Order' button the items from 'MenuBox' in form 1 need to be sent to the 'MenuBox' in form 2
OtherForm.OtherListbox.Items.Clear();
foreach(var itm in MenuBox.Items)
OtherForm.OtherListbox.Items.Add(itm);
Form1 (Main):
namespace WindowsFormsApplication1 {
public partial class RESTAURANT : Form
{
double soup = 2.49;
double ordertotal;
public RESTAURANT()
{
InitializeComponent();
}
private void RESTAURANT_Load(object sender, EventArgs e)
{
}
private void Add_Click(object sender, EventArgs e)
{
MenuBox.Items.Add("Soup");
TotalBox.Items.Add(String.Format("{0:C}", soup));
ordertotal += soup;
total.Text = Convert.ToString(String.Format("{0:C}", ordertotal));
}
private void TotalBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void PlaceOrder_Click(object sender, EventArgs e)
{
new AreYouSure().Show();
this.Show();
MenuBox.Items.Clear();
TotalBox.Items.Clear();
total.Clear();
ordertotal = 0;
}
}
}
Form2 (Confirmation)
namespace WindowsFormsApplication1 {
public partial class Confirmation : Form
{
public Confirmation()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Confirmation_Load(object sender, EventArgs e)
{
}
private void MenuBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
When clicking the 'Send Order' button the items from 'MenuBox' in form 1 need to be sent to the 'MenuBox' in form 2
It is better that the controls on your other form (ListBox, in this case) are set to Private by default.
In that case, you would either need to set the control's visibility to Public (bad form, in my opinion) or create a method in your other form to accept the parameters from your form.
Consider something like this:
public void ListBoxData(object[] array)
{
listBox1.Clear();
listBox1.AddRange(array);
}
To get the data or selected item information back to your main form, you would likewise create another public object that you could check, like the property below:
public object SelectedItem { get { return listBox1.SelectedItem; } }
I hope that is what you were looking for.
UPDATE:
Using the code you supplied in the post below, I can see you do not have anything in your Confirmation form to send data to, much less a way to pass that information.
If you had a ComboBox, you could do something like follows:
public partial class Confirmation : Form
{
private ComboBox comboBox1;
public void AddRange(object[] array)
{
comboBox1.Items.AddRange(array);
}
}
That does not place the ComboBox anywhere on your form. You would need to work that out.
With that done, I'm guessing you need to edit your PlaceOrder_Click routine:
private void PlaceOrder_Click(object sender, EventArgs e)
{
//new AreYouSure().Show();
//this.Show();
using (var obj = new Confirmation())
{
var list = new List<object>(MenuBox.Items.Count);
foreach (var o in MenuBox.Items)
{
list.Add(o);
}
obj.AddRange(list.ToArray());
if (obj.ShowDialog(this) == DialogResult.OK)
{
MenuBox.Items.Clear();
TotalBox.Items.Clear();
total.Items.Clear();
ordertotal = 0;
}
}
}
If you are struggling with this, you might need to look into some C# Windows "multiple forms" tutorials.
Here is a YouTube (that I did not sit all the way through): https://www.youtube.com/watch?v=qVVtCPDu9ZU

PetaPoco update just modified records in winforms

I have this code :
namespace PetaPocoTest
{
public partial class Form1 : Form
{
PetaPoco.Database db = new PetaPoco.Database("PgConnection");
IEnumerable<customers> allCustomers;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
allCustomers = db.Query<customers>("SELECT * FROM customers");
mGrid.DataSource = allCustomers .ToList();
}
private void saveButton_Click(object sender, EventArgs e)
{
foreach (var a in allCustomers)
{
db.Save("customers", "custumer_id", a);
}
}
}
}
bat this updates all record, no matter if they are changed or not.
So, my question is does anyone know how to update only changed records in petapoco ?
This is how I did it (eventually!) :
namespace PetaPocoTest
{
public partial class Form1 : Form
{
PetaPoco.Database db = new PetaPoco.Database("PgConnection");
Dictionary<string, int> modRows = new Dictionary<string, int>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
bindingSource = db.Fetch<customers>("SELECT * FROM customers");
mGrid.DataSource = bindingSource;
}
private void saveButton_Click(object sender, EventArgs e)
{
db.BeginTransaction();
foreach (customers c in bindingSource)
{
if (modRows.ContainsKey(c.id.ToString()))
{
db.Save("customers", "id", c);
}
}
db.CompleteTransaction();
}
private void mGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
int recId = ((customers)bindingSource.Current).id;
if (!modRows.ContainsKey(recId.ToString()))
{
modRows.Add(recId.ToString(), recId);
}
}
}
}
It functions, but if anyone has better idea pls share!
This is the simplest way from me to do this by db.BeginTransaction on Form_Load
private void Form1_Load(object sender, EventArgs e)
{
studentBindingSource.DataSource = db.Query<student>("SELECT * FROM student");
db.BeginTransaction(); // Begin Transaction here
}
On Update (CellValueChanged) just simply do db.Save() this doesn't commit yet because our transaction is not complete yet
private void studentDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
db.Save((student)studentBindingSource.Current);
}
And yes we can do Insert and Delete as well !!!
Insert
private void buttonInsert_Click(object sender, EventArgs e)
{
student newStudent = new student
{
StudentName = "POCONEW"
}
studentBindingSource.Add(newStudent);
db.Save(newStudent);
}
Delete
private void studentDataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
int rowIndex = e.Row.Index; // We use Gridview row index instead because BindingSource.Current isn't work when user drag then deleting multiple row
db.Delete(studentDataGridView.Rows[rowIndex].DataBoundItem as student);
}
Finally to save change we just do db.CompleteTransaction()
:Just a little note here after user press the Save Button if you don't close the form you have to call db.BeginTransaction() again if not everything user edit after this will be saved automatically because we don't have Transaction anymore
private void btSave_Click(object sender, EventArgs e)
{
db.CompleteTransaction();
db.BeginTransaction(); // everything user edit after this will be saved automatically because we don't have Transaction anymore so we Begin it again
}

Categories

Resources