Winform BindingNavigator not saving item to database - c#

I have designed a WinForm which is bound to my database using ADO.Net Entity Framework. On load my details form is populated with data from the database.
I can navigate through the items, however I can not add, save or update the item.
Below is the code for my form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
cpdEntities dbcontext;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dbcontext = new cpdEntities();
cpd_recipientsBindingSource.DataSource = dbcontext.cpd_recipients.ToList();
}
private void cpd_recipientsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
dbcontext = new cpdEntities();
dbcontext.SaveChanges();
}
}
}

Here is a simple example working with EntityFramework 4
How to Load:
using (var con = new cpdEntities())
{
cpd_recipientsBindingSource.DataSource = con.cpd_recipients.ToList();
}
How to Insert and Update:
if (cpd_recipientsBindingSource.Current == null) return;
using (var con = new cpdEntities())
{
var p = new Customer()
{
CustomerId = ((cpd_recipients)cpd_recipientsBindingSource.Current).Id,
CustomerIdNo = IdNoTextBox.Text,
CustomerName = CustomerNameTextBox.Text
};
var cus = new Customer();
if (p.CustomerId > 0)
cus = con.Customers.First(c => c.CustomerId == p.CustomerId);
cus.CustomerId = p.CustomerId;
cus.CustomerIdNo = p.CustomerIdNo;
cus.CustomerName = p.CustomerName;
if (p.CustomerId == 0)
con.Customers.AddObject(cus);
con.SaveChanges();
int i = cus.CustomerId;//SCOPE_IDENTITY
}
}

It looks like your re-instantiating your DbContext class in each of the events. Remove re-insantiating the DbContext from your saveItem event and give it a try again.

Related

Why does ap.Connect(authrequest) return a null value?

I am having a problem with my code where i run into an error when i try to click the join button. It says the ap.Connect(authrequest) is returning a null value so it cannot return a bool value. I am doing this in visual studio in a .net forms i think.
Thanks for you help.
Ps i am a student
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SimpleWifi;
namespace desk_flat
{
public partial class formConnect : Form
{
private static Wifi wifi;
public formConnect()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wifi = new Wifi();
List<AccessPoint> aps = wifi.GetAccessPoints();
foreach (AccessPoint ap in aps)
{
ListViewItem listobj = new ListViewItem(ap.Name);
listobj.SubItems.Add(ap.SignalStrength + "'''");
listobj.Tag = ap;
lstWifi.Items.Add(listobj);
}
}
private bool ConnectWifi(AccessPoint ap, string password)
{
AuthRequest authrequest = new AuthRequest(ap);
authrequest.Password = password;
return ap.Connect(authrequest);
}
private void btnJoin_Click(object sender, EventArgs e)
{
if (lstWifi.Items.Count > 0 && txtbPassword.Text.Length > 0)
{
ListViewItem selectedItem = lstWifi.SelectedItems[0];
AccessPoint ap = (AccessPoint)selectedItem.Tag;
if (ConnectWifi(ap, txtbPassword.Text))
{
lblStatus.Text = "You have connected to " + ap.Name;
}
else
{
lblStatus.Text = "Connection has failed";
}
}
else
{
lblStatus.Text = "Enter a password or select a network";
}
}
}
}

Form.ShowDialog(); trowing a System.OutPfMemoryException C#

I'm developing a form to my college project to show a product but when I call that form with the formName.ShowDialog() the Visual Studio trows me a OutOfMemoryException. The weird part is that I have other forms that do the same thing with more steps and none of them throws that error. The code is bellow.
This is where I call the form.
private void dtgProduzir_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
int id = Convert.ToInt32(dtgProduzir.Rows[dtgProduzir.CurrentRow.Index].Cells["clIdProducao"].Value);
ExibicaoProducao fepc = new ExibicaoProducao();
fepc.IdProducao = id;
fepc.ShowDialog();
CarregarGrids();
}
This is the form class:
using ERP_Serralheria.Dal;
using ERP_Serralheria.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ERP_Serralheria.Desktop_Chapa
{
public partial class ExibicaoProducao : Form
{
public ExibicaoProducao()
{
InitializeComponent();
}
public int IdProducao = 0;
private void ExibicaoProducao_Load(object sender, EventArgs e)
{
try
{
if (IdProducao == 0)
{
//Cadastro de produção
}
else
{
//Vizualização de uma produção
ProducaoChapa pc = new ProducaoChapa();
ProducaoChapaDal pcdal = new ProducaoChapaDal();
pc = pcdal.RetornaProducaoChapa(IdProducao);
lblIdProducao.Text = pc.Id.ToString();
lblIdVenda.Text = pc.Venda.Id.ToString();
cmbPatio.SelectedValue = pc.Patio.Id;
txtProdutor.Text = pc.Produtor.Nome;
txtVendedor.Text = pc.Venda.Usuario.Nome;
txtValor.Text = pc.ValorVenda.ToString();
txtPeso.Text = pc.Peso.ToString();
txtQuantidade.Text = pc.Quantidade.ToString();
txtLargura.Text = pc.Largura.ToString();
txtAltura.Text = pc.Altura.ToString();
txtObservacao.Text = pc.Observacao;
dtEntrega.Value = pc.Venda.DataEntrega;
if (pc.DataProducao.Year > 2019)
dtProducao.Value = pc.DataProducao;
cmbUrgencia.SelectedIndex = pc.Urgencia - 1;
//Carregar a imagem
txtIdChapa.Text = pc.Chapa.Id.ToString();
txtNomeCHapa.Text = pc.Chapa.Descricao;
pctImagem.BackgroundImage = pc.Chapa.Imagem;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

Windows Forms database auto generate ID column using LINQ

Created an application to insert data into the database using LINQ. I kept the ID column in the database. I am looking for guidance on how to have the ID column automatically add the next ID number each time a new entry is made into the data base?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Week4_2_
{
public partial class Form1 : Form
{
LinqsqlinsertdataDataContext objcontxt = new LinqsqlinsertdataDataContext();
public Form1()
{
InitializeComponent();
}
private void buttonInsert_Click(object sender, EventArgs e)//Inserts Records
{
using (objcontxt = new LinqsqlinsertdataDataContext())
{
TblSoccer name = new TblSoccer
{
FirstName = txtFirstName.Text,
LastName = textBox2.Text,
Address = textBox1.Text,
Id = textBoxID.Text
};
objcontxt.TblSoccers.InsertOnSubmit(name);
objcontxt.SubmitChanges();
}
getAllRecords();
}
private void getAllRecords() //Show all records
{
using (objcontxt = new LinqsqlinsertdataDataContext())
{
dataGridView1.DataSource = objcontxt.TblSoccers;
}
}
private void Form1_Load(object sender, EventArgs e)
{
getAllRecords();
}
}
}
In LinqToSQL, it requires primary key to insert or update the row in the Table. So your ID Column will be PK and Identity auto incremented column.
In DBML, you have to select your ID Column go to properties and set below properties:
Auto Generated Value : true and Auto-Sync : OnInsert

Select printer name without showing PrintDialog

I have this code. When I need to print my report, it shows me a Print Dialog. I want to select my print name by code, and print my report without showing PrintDialog.
This is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
namespace POS.Reports
{
public partial class ProductsReceiptPreview : Form
{
BindingSource _data;
string _total, _cashr, _cashc;
public ProductsReceiptPreview(BindingSource data, string total,
string cashr, string cashc)
{
InitializeComponent();
_total = total; _cashr = cashr; _cashc = cashc;
_data = data;
}
private void ProductsReceipt_Load(object sender, EventArgs e)
{
DataReceiptBindingSource.DataSource = _data;
Microsoft.Reporting.WinForms.ReportParameter[] param = new
Microsoft.Reporting.WinForms.ReportParameter[]
{
new Microsoft.Reporting.WinForms.ReportParameter("ptotal",
_total),
new Microsoft.Reporting.WinForms.ReportParameter("pcashr",
_cashr),
new Microsoft.Reporting.WinForms.ReportParameter("pcashc",
_cashc),
new Microsoft.Reporting.WinForms.ReportParameter
("pdate",DateTime.Now.ToString())
};
this.rptProductsReceipt.LocalReport.SetParameters(param);
this.rptProductsReceipt.RefreshReport();
this.rptProductsReceipt.ZoomMode =
Microsoft.Reporting.WinForms.ZoomMode.PageWidth;
}
private void btnReports_Click(object sender, EventArgs e)
{
rptProductsReceipt.PrintDialog();
}
}
}
i never use your method but i use this
rptProductsReceipt.PrintToPrinter(1, false, 0, 0);
after using adapter and data table

Trying to read a text file into classes then cycle through

Hi am a fairly novice when it comes to c# and I have being trying to read out a text file then splitting it into sections with classes but have trouble with where to declare them an then how to cycle through the records. here's my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Windows.Forms;
namespace Assignment_3
{
public partial class Form1 : Form
{
string s;
string ss;
int i = 1;
string infilename;
int num;
SortedList sList = new SortedList();
int x = 0;
public Form1()
{
InitializeComponent();
student myself = new student();
infilename = "text.txt";
StreamReader sr1 = new StreamReader(infilename);
sList.Clear();
while ((s = sr1.ReadLine()) != null)
{
string[] strs = s.Split(',');
myself.firstname = strs[0];
myself.middlename = strs[1];
myself.surname = strs[2];
myself.dob = DateTime.Parse(strs[3]);
myself.dob.ToString(strs[3]);
myself.sex = strs[4];
ss = myself.dob.ToString("u");
sList.Add(myself.firstname, myself);
}
sr1.Close();
num = sList.Count;
student[] pArray = new student[num];
string[] keys = new string[num];
foreach (DictionaryEntry d in sList)
{
keys[x] = (string)d.Key;
pArray[x] = (student)d.Value;
x++;
}
if (i == 0)
{lblmessage.Text = "Already at the first record."; i = 1; }
if (i == num)
{lblmessage.Text = "Already at the last record.";i = num-1; }
lbllastname.Text = pArray[i].surname;
lblfirstname.Text = pArray[i].firstname;
lblsecondname.Text = pArray[i].middlename;
lbldob.Text = pArray[i].dob.ToString();
lblsex.Text = pArray[i].sex;
}
private void btnlast_Click(object sender, EventArgs e)
{
i = num;
}
private void btnfirst_Click(object sender, EventArgs e)
{
i = 0;
}
private void btnnext_Click(object sender, EventArgs e)
{
i++;
}
private void btnprev_Click(object sender, EventArgs e)
{
i--;
}
}
}
and my class file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment_3
{
class student
{
public string firstname;
public string middlename;
public string surname;
public DateTime dob;
public string sex;
}
}
anyone have any ideas where am going wrong?? I have no errors but find that the text fields do not update with the new record's and then when stepped through the array class holds the correct amount of records and fields, I feel its going to be something very obvious put cant put my finger on it.
Any help would be very appreciated.
You should create new instance of student inside for loop. Because at the moment you have only one instance of student class and all items in SortedList are pointing to same object.

Categories