BindingNavigator with multiple tables updating problem in Visual Studio 2010 - c#

I have 2 tables 'contract' and 'customer', they have fk relationship. I drag 'contact' onto form then do so with 'customer', both are details type. The data of 2 tables are shown on form accordingly. The problem is when I modify then click save button only data of 'contract' table is updated.

private void button67_Click(object sender, EventArgs e)
{
if (textBox81.Text == "")
{
MessageBox.Show("you must choose table name");
}
if (textBox81.Text != "")
{
connect();
cmd = new OleDbCommand("select * from " + textBox81.Text + " ", conn);
ds = new DataSet();
dp = new OleDbDataAdapter(cmd);
dp.Fill(ds,""+textBox81.Text+"");
cm = (CurrencyManager)this.BindingContext[ds];
textBox79.DataBindings.Add("text",ds,""+textBox81.Text+""+".ProdS_name");
textBox80.DataBindings.Add("text", ds, "" + textBox81.Text + "" + ".rate");
}
}
private void button58_Click(object sender, EventArgs e)
{
cm.Position++;
}
private void button59_Click(object sender, EventArgs e)
{
cm.Position= cm.Count - 1; ;
}
private void button61_Click(object sender, EventArgs e)
{
cm.Position=0;
}

Related

getting an error when try to retrieve datagridview column value "15 digits"

I am trying to code an accounting system into which I should enter a product id, product name and product price. After that it should be stored in a .accdb file
My problem is when I enter more than 10 digits into product id the datagridview gives me an error saying that the value is too large for int32 type.
Error:
Additional information: Value was either too large or too small for an
Int32.Couldn't store <6221060003181> in Item_Code Column. Expected
type is Int32.
When I open the accdb file, I found the data stored; but next time I open the form, it gives me that error!
public partial class Productentry : MetroFramework.Forms.MetroForm
{
public OleDbConnection connection = new OleDbConnection();
public Productentry()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Sama_Software\WindowsFormsApplication1\WindowsFormsApplication1\DB.accdb;Jet OLEDB:Database Password=**************";
}
private void Productentry_Load(object sender, EventArgs e)
{
ViewData();
// TODO: This line of code loads data into the 'dBDataSet.Product' table. You can move, or remove it, as needed.
this.productTableAdapter1.Fill(this.dBDataSet.Product);
ViewData();
}
void ViewData()
{
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Product]",connection);
da.Fill(this.dBDataSet.Product);
}
private void bunifuButton4_Click(object sender, EventArgs e)
{
this.Close();
}
private void bunifuButton3_Click(object sender, EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter("INSERT INTO [Product] (Item_Code, Item_Name, Price) VALUES ('" + Pidn.Text + "','" + name.Text + "','" + price.Text + "')", connection);
da.Fill(dBDataSet)
ViewData();
Pidn.Clear();
name.Clear();
price.Clear();
}
private void Cat_TextChange(object sender, EventArgs e)
{
}
private void bunifuButton1_Click(object sender, EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter("UPDATE [Product] WHERE [Item_Code]=" + Pidn.Text + " SET [Item_Name]='" + name.Text + "',[Price]=" + price.Text + "", connection);
da.Fill(dBDataSet);
ViewData();
Pidn.Clear();
name.Clear();
price.Clear();
}
private void bunifuButton4_Click_1(object sender, EventArgs e)
{
this.Close();
}
private void Pid_TextChange(object sender, EventArgs e)
{
}
}
}
Store the barcode as text.
Even though it is build by digits, it is not a number but a code of fixed length, and it may even have a leading zero.

Refresh Datagrid When Dialog Form Closed

I have an application like this:
There's one main form (frmMasuk) with datagrid and "Add New" button
When someone clicks Add New, it shows the dialog form (Form2) to add new data.
When someone clicks "Save" on dialog form, it will be closed and
the datagrid will be refreshed
I got a problem when the dialog form closes, the datagrid must be refreshed.
This is some of my code:
frmMasuk:
public frmMasuk()
{
InitializeComponent();
SqlCommand sql = new SqlCommand("SELECT * FROM kas ORDER BY id_kas, tanggal DESC", koneksi.mykonek);
koneksi.openkonek();
SqlDataReader reader = sql.ExecuteReader();
DataTable a = new DataTable();
a.Load(reader);
koneksi.closekonek();
dgv.DataSource = a;
dgv.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
frmKasNew a = new frmKasNew();
a.ShowDialog();
}
frmKasNew:
private void simpankas()
{
koneksi.openkonek();
DateTime tgl = Convert.ToDateTime(ttanggal.Text);
SqlCommand sql = new SqlCommand("INSERT INTO kas(tanggal, jenis, jumlah, keterangan) VALUES('"+ tgl +"','"+ tjenis.Text +"','" + tjumlah.Text + "','" + tket.Text +"') ",koneksi.mykonek);
int exe = sql.ExecuteNonQuery();
if (exe == 0)
{
MessageBox.Show("Data gagal disimpan ke database", "Aplikasi KAS Usaha", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show("Data berhasil disimpan!", "Aplikasi KAS Usaha", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Dispose();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (ttanggal.Text == "" || tjenis.Text == "" || tjumlah.Text == "" || tket.Text == "")
{
MessageBox.Show("Harap melengkapi data sebelum menyimpan","Aplikasi KAS Usaha",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
simpankas();
}
// end if
}
Add an event to the a.OnClose event:
private void button3_Click(object sender, EventArgs e)
{
frmKasNew a = new frmKasNew();
a.FormClosed += FormClosed;
a.ShowDialog();
}
private void FormClosed(object sender, FormClosedEventArgs e)
{
SqlCommand sql = new SqlCommand("SELECT * FROM kas ORDER BY id_kas, tanggal DESC", koneksi.mykonek);
koneksi.openkonek();
SqlDataReader reader = sql.ExecuteReader();
DataTable a = new DataTable();
a.Load(reader);
koneksi.closekonek();
dgv.DataSource = a;
dgv.Enabled = true;
}
Have you tried showing the form with a DialogResult like
private void button3_Click(object sender, EventArgs e)
{
frmKasNew kas = new frmKasNew();
DialogResult result = kas.ShowDialog():
If (result == DialogReult.OK)
{
CurrencyManager cm = (CurrencyManager)
dgv.BindingContext[a];
cm.Refresh();
}
Then use CurrencyManager to to refresh the datagrid?

Saving Data to a Database (Single Table) C#

I have been following the documentation here:
http://msdn.microsoft.com/en-us/library/0f92s97z%28v=vs.100%29.aspx
However, I cannot get my application to work!
please see my short video: https://www.youtube.com/watch?v=zpOCaT6NaGs
My Application is not working, I am having nightmares trying to get it working.
I want to make a 'Stock management System',
Requirements:
Browse through products (Name, Price)
Add Products to the Table
Edit Existing Products
Remove Existing Products
Save changes to the Table
Create an Order form that will allow for listing selected products and providing a quantity selected and cost displayed
Print the results.
I cannot seem to get the data to save to the database table without problems.
My System:
Windows 7 - SP1
Visual Studio 2010 Professional
Using a Microsoft Access Database (DataSet)
1 Table to connect
3 fields: "ID, proName, proPrice"
Any Help is very welcome, Thanks.
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.Windows.Forms;
using System.Data.OleDb;
namespace KanadaStockControl
{
public partial class frmProducts : Form
{
stockDataSet dsoc;
OleDbConnection conn;
OleDbDataAdapter da;
public frmProducts()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
////Adding the items to the database
//dboKanadaDataSetProducts.ProductsRow newProductsRow;
//newProductsRow = dboKanadaDataSetProducts.Products.NewProductsRow();
////Setting the Product Name
//newProductsRow.ProductName = txtItem.Text;
////Setting the Product Price
//newProductsRow.ListPrice = txtPrice.Text;
////Adding the new row to the table
//this.dboKanadaDataSetProducts.Products.Rows.Add(newProductsRow);
////Saving the new row to the database
//this.productsTableAdapter.Update(this.dboKanadaDataSetProducts.Products);
//Old NON WORKING DATABASE ADD CODE:
//dboKanadaDataSetProductsTableAdapters.ProductsTableAdapter productsTableAdapter = new dboKanadaDataSetProductsTableAdapters.ProductsTableAdapter();
//productsTableAdapter.Insert("9", "NA", "0", txtPrice.Text, "Software");
//lstPrice.Items.Add(txtPrice.Text);
//lstItem.Items.Add(txtItem.Text);
stockDataSetTableAdapters.stockTableAdapter stockTableAdaptor = new stockDataSetTableAdapters.stockTableAdapter();
stockTableAdapter.Insert(txtItem.Text, txtPrice.Text);
}
//private void lstItem_SelectedIndexChanged(object sender, EventArgs e)
//{
// int x = lstItem.SelectedIndex;
// lstPrice.SelectedIndices.Add(x);
//}
//private void lstPrice_SelectedIndexChanged(object sender, EventArgs e)
//{
// int x = lstPrice.SelectedIndex;
// lstItem.SelectedIndices.Add(x);
//}
private void btnRemove_Click(object sender, EventArgs e)
{
if(1==1/*lstItem.SelectedItem == null*/)
{
MessageBox.Show("You must select an Item first, Before you are able to delete it!");
}
else
{
//Finding the row to delete in the database
//dboKanadaDataSetProducts.ProductsRow delProductsRow;
//delProductsRow = dboKanadaDataSetProducts.Products.FindByProductsID(string ProductName);
//START -------
// Locate the row to delete.
//NorthwindDataSet.RegionRow oldRegionRow;
//oldRegionRow = northwindDataSet.Region.FindByRegionID(5);
// Delete the row from the dataset
//oldRegionRow.Delete();
// Delete the row from the database
//this.regionTableAdapter.Update(this.northwindDataSet.Region);
//END -------
//lstPrice.Items.Remove(lstPrice.SelectedItem);
//lstItem.Items.Remove(lstItem.SelectedItem);
}
}
//I cannot be bothered to add spaces to this code, hence the misaligned code.
private void btnClear_Click(object sender, EventArgs e)
{
//lstItem.Items.Clear();
//lstPrice.Items.Clear();
}
private void txtPrice_TextChanged(object sender, EventArgs e)
{
//string context = this.txtPrice.Text;
//for (int i = 0; i < context.Length; i++)
//{
// if (!char.IsNumber(context[i]))
// {
// MessageBox.Show("Only numbers are allowed in this field!");
// txtPrice.Text = txtPrice.Text.Remove(txtPrice.TextLength - 1);
// }
//}
}
private void button2_Click(object sender, EventArgs e)
{
/*
if (MessageBox.Show("Are you sure that you want to DELETE ALL LISTED ITEMS?", "WARNING: Delete All Records",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
== DialogResult.Yes)
{
int j = lstPrice.Items.Count;
for (int i = lstItem.Items.Count; i > 0; )
{
lstItem.Items.Remove(lstItem.Items[--i]);
lstPrice.Items.Remove(lstPrice.Items[--j]);
}
}*/
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
frmOrder makeOrder = new frmOrder();
makeOrder.Show();
}
//private void frmProducts_Load(object sender, EventArgs e)
//{
// // TODO: This line of code loads data into the 'dboKanadaDataSetProducts.Products' table. You can move, or remove it, as needed.
// //this.productsTableAdapter.Fill(this.dboKanadaDataSetProducts.Products);
//}
private void frmProducts_Load_1(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'stockDataSet.stock' table. You can move, or remove it, as needed.
//this.stockTableAdapter.Fill(this.stockDataSet.stock);
dsoc = new stockDataSet();
conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\stock.accdb");
da = new OleDbDataAdapter("Select * from stock", conn);
OleDbCommandBuilder cmdBl = new OleDbCommandBuilder(da);
da.Fill(dsoc, "stock");
dataGridView2.DataSource = dsoc;
dataGridView2.DataMember = "stock";
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//this.Validate();
//this.stockBindingSource.EndEdit();
//this.stockTableAdapter.Update(this.stockDataSet.stock);
//MessageBox.Show("Update successful");
//da.Update(stockDataSet.Tables["stock"]);
System.Data.OleDb.OleDbConnection oledb1 = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\stock.accdb");
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT stock (proName, proPrice) VALUES ("+ txtItem.Text +", " + txtPrice.Text + ")";
cmd.Connection = oledb1;
oledb1.Open();
cmd.ExecuteNonQuery();
oledb1.Close();
}
catch (System.Exception ex)
{
MessageBox.Show("Update failed");
}
//this.dataGridView1.EndEdit();
}
private void btnMenu_Click(object sender, EventArgs e)
{
this.Hide();
frmMenu showMenu = new frmMenu();
showMenu.Show();
}
}
}
cmd.CommandText = "INSERT INTO stock (proName, proPrice) VALUES ("+ txtItem.Text +", " + txtPrice.Text + ")";
It will work. But the data will be saved as a copy of database in the bin/debug folder.
Go to Solution explorer and change the properties of Database. Set "Copy to output Directory=Copy if newer" and then try. Good luck.

A Combobox Population issue

I am using the following function to populate my ComboBox
public static void FillDropDownList(string Query, System.Windows.Forms.ComboBox DropDownName, string AValue, string Adisplay)
{
string Value = AValue;
string display = Adisplay;
using (var CONN = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Test.accdb;"))
{
CONN.Open();
DataTable dt = new DataTable();
try
{
OleDbCommand cmd = new OleDbCommand(Query, CONN);
OleDbDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (OleDbException e)
{
MessageBox.Show(e.ToString());
return;
}
DropDownName.DataSource = dt;
DropDownName.ValueMember = Value;
DropDownName.DisplayMember = display;
}
}
And I'm calling it in the load form:
private void Form1_Load(object sender, EventArgs e)
{
FillDropDownList("select CountryCode,Countryname from Countries", comboBox1, "CountryCode", "Countryname");
}
2.After that I'm using the same Function in the event of Selectedindexchanged event to populate another ComboBox:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
And for the population of the two combobox's everything works fine however here is the issue
I have two combobox's as shown in the pic :
So te first combobox ( country ) loaded in the form perfectly
but what I'm trying to do is to make the the second combobox ( the state ) being selected from Database only when I select the country but what happen is that the code runs and the second combobox goes and select from database whatever is the selected index in the first combo is as the pic shows
So what I basically want to do is to make the second Combo being populated only when I select an index from the first combobox.
Put your code in SelectionChangeCommitted Instead of SelectedIndexChanged
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
I think your problem is being cause because the population of the first combo box fires the event to populate the second one. One way around it is to have something like the following in comboBox1_SelectedIndexChanged(object sender, EventArgs e).
if (comboBox1.Text == string.Empty) { return; }
If that doesn't work try using the "SelectedIndex > 0" or "SelectedValue" property.
As a point of note your code is potentially prone to SQL injection attacks, if anyone was able to modify your combo-box items.
You need to identify wether the item is really changed from Combobox or not by using SelectedIndex property.
Try This:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex >= 0)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
}
Change your following method to
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != -1 && comboBox2.SelectedIndex != -1 )
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
}
Before submitting for query the DB you validate your both comboboxes. Check for any selected item.
Thanks
Srikanth
Remove the SelectedIndexChanged event handler before calling FillDropDownList method, and re-apply it after the ComboBox is populated.
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
FillDropDownList("select CountryCode,Countryname from Countries", comboBox1, "CountryCode", "Countryname");
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}

updating the datagridview [duplicate]

This question already has an answer here:
how to update data grid view in winforms?
(1 answer)
Closed 9 years ago.
i have 2 forms and dont know how to update the datagridview, if some can simply guide me please. form1 is as follows:
public partial class frmBooking : Form
{
//instance of sqlConnection created
SqlConnection con = new SqlConnection("Data Source=....");
public frmBooking()
{
InitializeComponent();
//sets the time selecter to a time format and selects the hours and mins only in 24 hour format.
TimeOfBooking.CustomFormat = "HH:mm";
TimeOfBooking.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
//combo box get data from database and updates when new customer is added
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
NameOfCustomer.Items.Clear();
SqlCommand cm = new SqlCommand("SELECT GroupName FROM Customer ORDER BY GroupName ASC", con);
try
{
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
NameOfCustomer.Items.Add(dr["GroupName"]);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//ends here
}
//sets the facility name so its copied from the previous(facility to be booked) form into the Facility text box
public void setFacility(string new_facility)
{
Facility.Text = new_facility;
}
//sets the date so its copied from the previous(facility to be booked) form into the date text box
public void setDate(string new_date)
{
Date.Text = new_date;
}
//adding a new customer button, redirects user to the add customer page
private void btnAddCust_Click(object sender, EventArgs e)
{
frmNewCustomer newCust = new frmNewCustomer();
newCust.Show();
this.Close();
}
//cancel button will redirect the user to the main page
private void btnCancel_Click(object sender, EventArgs e)
{
Form3 frm3 = new Form3();
frm3.Show();
this.Close();
}
private void frmBooking_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
}
private void lblBookingForm_Click(object sender, EventArgs e)
{
}
private void btnConfirm_Click(object sender, EventArgs e)
{
//validation - if any of the mandotory fields are empty an error message will apear next to the text box
if (Facility.Text == "")
{
//MessageBox.Show("Please enter valid Facility, Date, Name Of Customer, Time Of Booking and Hours");
errorFacility.SetError(Facility, "Enter A Facility To Book");
}
else if (Date.Text == "")
{
errorDate.SetError(Date, "Enter A Valid Date");
}
else if (NameOfCustomer.Text == "")
{
errorCust.SetError(NameOfCustomer, "Enter A Customer To Book");
}
else if (TimeOfBooking.Text == "")
{
errorTime.SetError(TimeOfBooking, "Enter A Time To Book");
}
else if (Hours.Text == "")
{
errorHours.SetError(Hours, "Enter The Hours To Book");
}
//so if there isnt no error in the fields itll go on and add the data in to the database.
else
{
//instance of sqlConnection
SqlConnection con = new SqlConnection("Data Source=...");
//instance of sqlCommand
String query =
"INSERT INTO [Booking] values ('"
+ Facility.Text
+ "', '" + Date.Text
+ "', '" + NameOfCustomer.Text
+ "', '" + TimeOfBooking.Text
+ "', '" + Hours.Text
+ "', '" + Paid.Text
+ "', '" + Notes.Text
+ "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
//query executed correcty or not
con.Close();
MessageBox.Show("Sucessfully Booked");
Form3 mainPage = new Form3();
mainPage.Show();
this.Close();
}
}
}}
this is the form i am using to add a Booking.
The second form i have is the one with the datagridview, which i want to update when the booking is made the code for that is as follows:
public partial class frmViewBookings : Form
{
public frmViewBookings()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
Form3 mainpage = new Form3();
mainpage.Show();
this.Close();
}
private void frmViewBookings_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
}
}
}
To display data on your datagrid you would have to set it's Datasource first which you would do like this
datagridview1.Datasource = this.usersDataSet1.Booking.DefaultView
Whenever you want to refresh it you will just have to fill your tableadapter again and set your gridview's datasource to it.
(Create a seperate method to load datagridview)

Categories

Resources