Exporting data to excel - c#

the code works to a certain extent when I export the data to excel it works fine but if I go back into the application and add, delete or update any of the datagrid when I export the data again it doesn't export the changes. I have deleted the original csv file in case it was an overwriting problem but still get the same problem.
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.SqlClient;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class FormAccounts : Form
{
String constring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Accounts.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
//String cmdselect = #"select * Accounts";
String cmdupdate = #"update Accounts set date = #date, moneyin = #moneyin, retailin = #retailin, rent = #rent, stock = #stock, transport = #transport, misc = #misc, bills = #bills, comments = #comments where ID = #id";
String cmdinsert = #"insert into Accounts (date, moneyin, retailin, rent, stock, transport, misc, bills, comments) values (#date, #moneyin, #retailin, #rent, #stock, #transport, #misc, #bills, #comments )";
String cmddelete = #"delete from Accounts where ID =#ID";
public FormAccounts()
{
InitializeComponent();
}
private void FormAccounts_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'accountsDataSet.Accounts' table. You can move, or remove it, as needed.
this.accountsTableAdapter.Fill(this.accountsDataSet.Accounts);
}
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(cmdinsert, con);
try
{
da.InsertCommand.Parameters.Add("#date", SqlDbType.Date);
da.InsertCommand.Parameters["#date"].Value = dtpaccs.Value;
da.InsertCommand.Parameters.Add("#moneyin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#moneyin"].Value = textmoneyin.Text ;
da.InsertCommand.Parameters.Add("#retailin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#retailin"].Value = textretailin.Text;
da.InsertCommand.Parameters.Add("#rent", SqlDbType.Decimal);
da.InsertCommand.Parameters["#rent"].Value = textrent.Text;
da.InsertCommand.Parameters.Add("#stock", SqlDbType.Decimal);
da.InsertCommand.Parameters["#stock"].Value = textstock.Text;
da.InsertCommand.Parameters.Add("#transport", SqlDbType.Decimal);
da.InsertCommand.Parameters["#transport"].Value = texttransport.Text;
da.InsertCommand.Parameters.Add("#misc", SqlDbType.Decimal);
da.InsertCommand.Parameters["#misc"].Value = textmisc.Text;
da.InsertCommand.Parameters.Add("#bills", SqlDbType.Decimal);
da.InsertCommand.Parameters["#bills"].Value = textbills.Text;
da.InsertCommand.Parameters.Add("#comments", SqlDbType.VarChar);
da.InsertCommand.Parameters["#comments"].Value = textcomments.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
cleartexts();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string date = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string id = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
lbldate.Text = date;
lblID.Text = id;
dtpaccs.Value = Convert.ToDateTime(date);
textmoneyin.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
textretailin.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
textrent.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
textstock.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
texttransport.Text = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
textmisc.Text = dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString();
textbills.Text = dataGridView1.Rows[e.RowIndex].Cells[8].Value.ToString();
textcomments.Text = dataGridView1.Rows[e.RowIndex].Cells[9].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand(cmdupdate, con);
try
{
da.UpdateCommand.Parameters.Add("#ID", SqlDbType.Int).Value = lblID.Text;
da.UpdateCommand.Parameters.Add("#date", SqlDbType.Date).Value = lbldate.Text;
da.UpdateCommand.Parameters.Add("#moneyin", SqlDbType.Decimal).Value = textmoneyin.Text;
da.UpdateCommand.Parameters.Add("#retailin", SqlDbType.Decimal).Value = textretailin.Text;
da.UpdateCommand.Parameters.Add("#rent", SqlDbType.Decimal).Value = textrent.Text;
da.UpdateCommand.Parameters.Add("#stock", SqlDbType.Decimal).Value = textstock.Text;
da.UpdateCommand.Parameters.Add("#transport", SqlDbType.Decimal).Value = texttransport.Text;
da.UpdateCommand.Parameters.Add("#misc", SqlDbType.Decimal).Value = textmisc.Text;
da.UpdateCommand.Parameters.Add("#bills", SqlDbType.Decimal).Value = textbills.Text;
da.UpdateCommand.Parameters.Add("#comments", SqlDbType.VarChar).Value = textcomments.Text;
con.Open();
da.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Accounts Updated");
con.Close();
cleartexts();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
var rindex = dataGridView1.SelectedCells[0].RowIndex;
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.DeleteCommand = new SqlCommand(cmddelete, con);
try
{
DialogResult dr;
dr = MessageBox.Show("Are you sure you want to delete this record", "Confirmation", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
da.DeleteCommand.Parameters.Add("#ID", SqlDbType.Int).Value = accountsDataSet.Accounts[rindex].ID;
con.Open();
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Record Deleted");
con.Close();
cleartexts();
}
else
{
MessageBox.Show("Delete Cancelled");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void cleartexts()
{
//Clears textboxes
textmoneyin.Text = "";
textretailin.Text ="";
textrent.Text = "";
textstock.Text = "";
texttransport.Text = "";
textmisc.Text = "";
textbills.Text = "";
textcomments.Text = "";
}
private void exportToolStripMenuItem_Click(object sender, EventArgs e)
{
int cols;
string directory = #"C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Excel Exports";
string filename = string.Format("{0:dd-MM-yy}__{1}.csv", DateTime.Now, "Accounts");
string path = Path.Combine(directory, filename);
//open file
using (StreamWriter wr = File.CreateText(path))
{
//determine the number of cols and write to file
cols = dataGridView1.Columns.Count;
for (int i = 0; i < cols; i++)
{
wr.Write(dataGridView1.Columns[i].Name.ToString().ToUpper() + ",");
}
wr.WriteLine();
//write rows to excel
for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
wr.Write(dataGridView1.Rows[i].Cells[j].Value + ",");
}
else
{
wr.Write(",");
}
}
wr.WriteLine();
}
wr.Close();
MessageBox.Show("Operation Complete " +path);
}
}
}
}

Found the problem. The application needs to be shut down and restarted for the new data to copy over. Is there a way to do that once the datagrid has been changed / updated?

Related

Windows Form App (.NET Framework) CRUD Project, changes successfully saves into DataGridView, but not the actual Database Table

This is my first time using C# and SQL. I've managed to get the datagridview to work, be it insert, update or delete. However, all the changes that is reflected in the datagridview is NOT updating in the SQL Table (When I open the database and click "Show Table Data", the Insert, Update and Delete changes are not reflected there.)
Please Help! All the videos I've searched up only shows their datagridview changes being reflected, but doesn't show if their SQL Table is actually updated.
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.Data.SqlClient;
using System.Configuration;
using System.Runtime.InteropServices;
namespace CRUDProj
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
displaydata();
button3.Visible = false;
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
chk.HeaderText = "Select";
chk.ValueType = typeof(bool);
chk.Name = "chkbox";
infoDataGridView.Columns.Insert(0, chk);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'cRUDDBDataSet.Info' table. You can move, or remove it, as needed.
this.infoTableAdapter.Fill(this.cRUDDBDataSet.Info);
}
private void infoBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.infoBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.cRUDDBDataSet);
}
private void displaydata()
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[Info]";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
DataTable dt = new DataTable();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
sdr.Fill(dt);
infoDataGridView.DataSource = dt;
sqlconn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "insert into [dbo].[Info] values (#Id, #FullName, #NRIC, #Phone, #Temperature, #LocationLevel, #Date)";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id", iDTextBox.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
MessageBox.Show("Record Successfully Inserted");
displaydata();
sqlconn.Close();
}
public string message = string.Empty;
private void button2_Click(object sender, EventArgs e)
{
foreach(DataGridViewRow row in infoDataGridView.Rows)
{
bool issellected = Convert.ToBoolean(row.Cells["chkbox"].Value);
if (issellected)
{
message = Environment.NewLine;
message = row.Cells[1].Value.ToString();
}
}
label1.Text = message;
label1.Visible = true;
button3.Visible = true;
button1.Enabled = false;
button2.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
}
private void button3_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "update [dbo].[Info] set Id=#Id, FullName=#FullName, NRIC=#NRIC, Phone=#Phone, Temperature=#Temperature, LocationLevel=#LocationLevel, Date=#Date where Id=#Id";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id" ,label1.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
infoTableAdapter.Update(cRUDDBDataSet.Info);
sqlconn.Close();
MessageBox.Show("Record Updated Successfully! ");
displaydata();
button3.Visible = false;
button1.Enabled = true;
button2.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
DataRowView drv = infoDataGridView.CurrentRow.DataBoundItem as DataRowView;
DataRow[] rowsToUpdate = new DataRow[] { drv.Row };
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM dbo.Info", sqlconn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(rowsToUpdate);
this.infoTableAdapter.Update(this.cRUDDBDataSet.Info);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
List<String> empselect = new List<String>();
DataGridViewRow row = new DataGridViewRow();
for (int i = 0; i<= infoDataGridView.Rows.Count-1; i++)
{
row = infoDataGridView.Rows[i];
if (Convert.ToBoolean(row.Cells [0].Value)==true)
{
string id = row.Cells[1].Value.ToString();
empselect.Add(id);
}
sqlconn.Open();
foreach (string s in empselect)
{
SqlCommand sqlcomm = new SqlCommand("delete from [dbo].[Info] where Id = ' " + s + " ' ", sqlconn);
sqlcomm.ExecuteNonQuery();
}
sqlconn.Close();
}
MessageBox.Show("Record Deleted Successfully! ");
displaydata();
}
private void iDTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
iDTextBox.Clear();
fullNameTextBox.Clear();
nRICTextBox.Clear();
phoneTextBox.Clear();
temperatureTextBox.Clear();
locationLevelTextBox.Clear();
dateTextBox.Clear();
}
}
}
Bind your DGV to Database this will help you to perform crud operations easily.
This is a sample code on DGV to perform some actions may it will help you. but make sure that you bind your DGV to the database table.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
string _name = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string _lname = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
string _sex = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
string _age = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
if (e.ColumnIndex == dataGridView1.Columns["delete"].Index && e.RowIndex >= 0)
{
if(groupBox1.Visible==true)
{
groupBox1.Visible = false;
}
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
DialogResult result = MessageBox.Show("Do You Want to delete?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (result.Equals(DialogResult.OK) && service.deleterecord(_id, _name, _lname, _age, _sex))
{
MessageBox.Show("deleted record");
this.Close();
}
else
{
MessageBox.Show("not deleted");
}
}
if (e.ColumnIndex == dataGridView1.Columns["edit"].Index && e.RowIndex >= 0)
{
groupBox1.Visible = true;
firstname.Text = _name;
lastname.Text = _lname;
gender.Text = _sex;
age.Text = _age;
}
}
private void update_Click(object sender, EventArgs e)
{
string _fname = firstname.Text;
string _lname = lastname.Text;
string _age = age.Text;
string _sex = gender.Text;
try
{
if (string.IsNullOrWhiteSpace(_fname) || string.IsNullOrWhiteSpace(_lname) || string.IsNullOrWhiteSpace(_age) || string.IsNullOrWhiteSpace(_sex) || gender.Equals(null))
{
MessageBox.Show("Please enter the empty fields");
}
else
{
if (Updatedata("Update Query"))
{
MessageBox.Show("Record Updated");
//this.recordTableAdapter.Fill(this.task2DataSet.record);
groupBox1.Visible = false;
this.Size = new Size(595, 258);
this.Close();
}
else
{
MessageBox.Show("Failed to update");
}
}
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
}
}

How to update items from datagridview in c#

I want to update invoice and invoice has multiple items i retrieve invoice items from Database to DataGridView now user can remove the items and can add the items and user will click on update button to update the invoice in database.
My Code:
try
{
using (SQLiteConnection con = new SQLiteConnection(AppSettings.ConnectionString()))
{
con.Open();
for (int j = 0; j < dgv.Rows.Count; j++)
{
using (SQLiteCommand sc = new SQLiteCommand("Update Orders Set [Order_No] = #Order_No,[Order_Type] = #Order_Type,[Order_Date] = #Order_Date,[Customer_Name] = #Customer_Name,[Contact] = #Contact,[Adress] = #Adress,[Delivery_Address] = #Delivery_Address,[Rider] = #Rider,[Items] = #Items,[Price] = #Price,[Qty] = #Qty,[Item_Total] = #Item_Total,[Item_Cat] = #Item_Cat,[SubTotal] = #SubTotal,[Discount] = #Discount,[Total_Amount] = #Total_Amount,[Paid_Amount] = #Paid_Amount,[Change_Due] = #Change_Due,[Delivery_Charges] = #Delivery_Charges Where Order_No = '" + Order_No.Text + "' ", con))
{
sc.Parameters.AddWithValue("#Order_No", Order_No.Text);
sc.Parameters.AddWithValue("#Order_Type", Order_Type.Text);
sc.Parameters.AddWithValue("#Order_Date", Order_Date.Text);
sc.Parameters.AddWithValue("#Customer_Name", Customer_Name.Text);
sc.Parameters.AddWithValue("#Contact", Contact.Text);
sc.Parameters.AddWithValue("#Adress", Address.Text);
sc.Parameters.AddWithValue("#Delivery_Address", Delivery_Address.Text);
sc.Parameters.AddWithValue("#Rider", "");
sc.Parameters.AddWithValue("#Items", dgv.Rows[j].Cells[1].Value);
sc.Parameters.AddWithValue("#Price", dgv.Rows[j].Cells[2].Value);
sc.Parameters.AddWithValue("#Qty", dgv.Rows[j].Cells[3].Value);
sc.Parameters.AddWithValue("#Item_Total", dgv.Rows[j].Cells[4].Value);
sc.Parameters.AddWithValue("#Item_Cat", dgv.Rows[j].Cells[5].Value);
sc.Parameters.AddWithValue("#SubTotal", SubTotal.Text);
sc.Parameters.AddWithValue("#Discount", Discount.Text);
sc.Parameters.AddWithValue("#Total_Amount", Total_Amount.Text);
sc.Parameters.AddWithValue("#Paid_Amount", Paid_Amount.Text);
sc.Parameters.AddWithValue("#Change_Due", Change_Due.Text);
sc.Parameters.AddWithValue("#Delivery_Charges", Del_Charges.Text);
sc.ExecuteNonQuery();
}
}
SuccessBox sb = new SuccessBox();
sb.lbl_Change.Text = Change_Due.Text;
sb.label1.Text = "Successfully Updated";
sb.ShowDialog();
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if i add new item and click on update button so this query replaces my all old items with new one.
Suppose i add Samsung S8 so it willl replace my old items to Samsung S8.
And the result is:
Samsung S8 1 $750
Samsung S8 1 $750
Samsung S8 1 $750
Samsung S8 1 $750
Is there any way to do this?
You have to Set The OrderID Parameter in order to Update the desired Item
This will do the Insert, Update, and Delete for you, all via a DataGrid object.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertUpdateDeleteDemo
{
public partial class frmMain : Form
{
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int ID = 0;
public frmMain()
{
InitializeComponent();
DisplayData();
}
//Insert Data
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("insert into tbl_Record(Name,State) values(#name,#state)", con);
con.Open();
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Provide Details!");
}
}
//Display Data in DataGridView
private void DisplayData()
{
con.Open();
DataTable dt=new DataTable();
adapt=new SqlDataAdapter("select * from tbl_Record",con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
txt_Name.Text = "";
txt_State.Text = "";
ID = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
//Update Record
private void btn_Update_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("update tbl_Record set Name=#name,State=#state where ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
//Delete Record
private void btn_Delete_Click(object sender, EventArgs e)
{
if(ID!=0)
{
cmd = new SqlCommand("delete tbl_Record where ID=#id",con);
con.Open();
cmd.Parameters.AddWithValue("#id",ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Delete");
}
}
}
}

Database is locked. insert operation

I have no idea what to do anymore with this code. I did review the opening and closing of my connections and I think all connections are okay.
I have to tables here that I'm trying to insert data. The imf table and the imf_products table. My goal is as soon as I have inserted data to my imf table I should insert data again to my imf_products.
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.Windows.Forms;
using System.Data.SQLite;
namespace Natasha_POS
{
public partial class m2 : Form
{
public SQLiteConnection con = new SQLiteConnection(#"Data Source=default.db");
public m2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (combo_compname.Text.Length <= 0)
{
MessageBox.Show("Please specify the company name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (combo_artname.Text.Length <= 0)
{
MessageBox.Show("Please specify the product name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (combo_color.Text.Length <= 0)
{
MessageBox.Show("Please specify the product color.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (combo_size.Text.Length <= 0)
{
MessageBox.Show("Please specify the product size.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (textBox8.Text.Length <= 0)
{
MessageBox.Show("Please specify the product price.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (box_numeric.Text.Length <= 0)
{
MessageBox.Show("Please specify the number of products you're acquiring.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dGrid.Rows.Add(combo_artname.Text,
combo_color.Text,
combo_size.Text,
Convert.ToInt32(box_numeric.Value),
Convert.ToInt32( textBox8.Text),
combo_discount.Text,"","",
Convert.ToInt32(combo_artname.SelectedValue),
Convert.ToInt32(combo_color.SelectedValue),
Convert.ToInt32(combo_size.SelectedValue),
Convert.ToInt32(combo_discount.SelectedValue)
);
////new
combo_compname.Text = "--Select Company--";
combo_cat.Text = "--Select Category--";
combo_artname.Text = "--Select Product--";
combo_color.Text = "--Select Color--";
combo_size.Text = "--Select Size--";
textBox8.Clear();
box_numeric.Value = 0;
combo_custno.Focus();
}
}
private void m2_Load(object sender, EventArgs e)
{
dateTimePicker.Enabled = false;
box_custname.Text = null;
SQLiteConnection conn1 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt = new DataTable();
conn1.Open();
SQLiteCommand cmd = conn1.CreateCommand();
cmd.CommandText = "SELECT * from customer";
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(dt);
combo_custno.DataSource = dt;
combo_custno.ValueMember = "cp_id";
combo_custno.DisplayMember = "customer_no";
combo_custno.Text = "--Select Customer--";
/*IList<string> CustNo = new List<string>();
foreach (DataRow row in dt.Rows)
{
CustNo.Add(row.Field<string>("cp_id"));
}
combo_custno.Items.AddRange(CustNo.ToArray<string>());
combo_custno.AutoCompleteMode = AutoCompleteMode.Suggest;
combo_custno.AutoCompleteSource = AutoCompleteSource.ListItems; */
conn1.Close();
SQLiteConnection conn2 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt2 = new DataTable();
conn2.Open();
SQLiteCommand cmd2 = conn2.CreateCommand();
cmd2.CommandText = "SELECT * from company";
SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(cmd2);
adapter2.Fill(dt2);
combo_compname.DataSource = dt2;
combo_compname.ValueMember = "company_id";
combo_compname.DisplayMember = "company_name";
combo_compname.Text = "--Select Company--";
conn2.Close();
SQLiteConnection conn3 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt3 = new DataTable();
conn3.Open();
SQLiteCommand cmd3 = conn3.CreateCommand();
cmd3.CommandText = "SELECT category_id, category_name FROM category";
SQLiteDataAdapter adapter3 = new SQLiteDataAdapter(cmd3);
adapter3.Fill(dt3);
combo_cat.DataSource = dt3;
combo_cat.ValueMember = "category_id";
combo_cat.DisplayMember = "category_name";
combo_cat.Text = "--Select Category--";
conn3.Close();
SQLiteConnection conn4 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt4 = new DataTable();
conn4.Open();
SQLiteCommand cmd4 = conn4.CreateCommand();
cmd4.CommandText = "SELECT * FROM colors";
SQLiteDataAdapter adapter4 = new SQLiteDataAdapter(cmd4);
adapter4.Fill(dt4);
combo_color.DataSource = dt4;
combo_color.ValueMember = "color_id";
combo_color.DisplayMember = "color_name";
combo_color.Text = "--Select Color--";
conn4.Close();
SQLiteConnection conn5 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt5 = new DataTable();
conn5.Open();
SQLiteCommand cmd5 = conn5.CreateCommand();
cmd5.CommandText = "SELECT * FROM discount";
SQLiteDataAdapter adapter5 = new SQLiteDataAdapter(cmd5);
adapter5.Fill(dt5);
combo_discount.DataSource = dt5;
combo_discount.ValueMember = "discount_id";
combo_discount.DisplayMember = "discount_name";
combo_discount.Text = "";
conn5.Close();
//this.reportViewer1.RefreshReport();
}
private void combo_custno_SelectedIndexChanged(object sender, EventArgs e)
{
// int x = Convert.ToInt32(combo_custno.Text);
//////////textboxes
SQLiteConnection conn4 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt4 = new DataTable();
conn4.Open();
SQLiteCommand cmd4 = conn4.CreateCommand();
cmd4.CommandText = "SELECT * FROM customer where cp_id = '" + combo_custno.SelectedValue + "'";
SQLiteDataReader dr = cmd4.ExecuteReader();
if (dr.Read())
{
//string fname = Convert.ToString(dr["firstname"]);
//string mname = Convert.ToString(dr["firstname"]);
box_custname.Text = Convert.ToString(dr["firstname"]) + " " + Convert.ToString(dr["middlename"]) + " " + Convert.ToString(dr["lastname"]);
box_mse.Text = Convert.ToString(dr["msediscount"]);
box_nfc.Text = Convert.ToString(dr["nfcdiscount"]);
box_rating.Text = Convert.ToString(dr["rating"]);
box_avcredline.Text = Convert.ToString(dr["available_credit_line"]);
}
conn4.Close();
}
private void combo_cat_SelectedIndexChanged(object sender, EventArgs e)
{
//int x = Convert.ToInt32(combo_cat.Text);
SQLiteConnection conn2 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt2 = new DataTable();
conn2.Open();
SQLiteCommand cmd2 = conn2.CreateCommand();
cmd2.CommandText = "SELECT * FROM product where category_id = '" + combo_cat.SelectedValue+ "'";
SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(cmd2);
adapter2.Fill(dt2);
combo_artname.DataSource = dt2;
combo_artname.ValueMember = "product_id";
combo_artname.DisplayMember = "product_name";
combo_artname.Text = "--Select Product--";
conn2.Close();
SQLiteConnection conn3 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt3 = new DataTable();
conn3.Open();
SQLiteCommand cmd3 = conn3.CreateCommand();
cmd3.CommandText = "SELECT * FROM size where category_id = '" + combo_cat.SelectedValue + "'";
SQLiteDataAdapter adapter3 = new SQLiteDataAdapter(cmd3);
adapter3.Fill(dt3);
combo_size.DataSource = dt3;
combo_size.ValueMember = "size_id";
combo_size.DisplayMember = "size_name";
combo_size.Text = "--Select Size--";
conn3.Close();
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void inserttoSO(string custno)
{
con.Open();
SQLiteCommand cmd = con.CreateCommand();
cmd.Parameters.AddWithValue("#custno", combo_custno.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker.Value);
//cmd.Parameters.AddWithValue("#comment", box_commment.Text);
cmd.CommandText = "INSERT INTO sales_order (customer_no,date) VALUES (#custno,#date)";
cmd.ExecuteNonQuery();
con.Close();
}
private void button3_Click(object sender, EventArgs e)
{
//inserttoSO(combo_custno.Text);
var results = MessageBox.Show("Are you sure you want to generate this inventory report?",
"Inventory report is successfully made.",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (results == DialogResult.Yes)
{
inserttoSO(combo_custno.Text);
string StrQuery = "";
using (SQLiteConnection conn = new SQLiteConnection(#"Data Source=default.db"))
{
using (SQLiteCommand cmd1 = new SQLiteCommand())
{
cmd1.Connection = conn;
conn.Open();
for (int i = 0; i < dGrid.Rows.Count; i++)
{
/*"INSERT INTO imf_products(imf_id, company_id,product_id, color_id,size_id,price,qty) VALUES (1,1,1,1,1,1,1)";*/
//(SELECT max(imf_id) FROM imf) StrQuery
cmd1.CommandText =
"INSERT INTO orders(salesorder_id, product_id, quantity,price,cash, discount_id) VALUES ((SELECT max(salesorder_id) FROM sales_order),'"
+ dGrid.Rows[i].Cells["product_id"].Value + "', '" + dGrid.Rows[i].Cells["qty"].Value + "', '"
+ dGrid.Rows[i].Cells["price"].Value + "', '" + dGrid.Rows[i].Cells["cash"].Value + "', '"
+ dGrid.Rows[i].Cells["discount_id"].Value + "')";
// cmd.CommandText = StrQuery;
cmd1.ExecuteNonQuery();
MessageBox.Show("Sales report is successfully made.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
// conn.Close();
}
}
}
else
{ MessageBox.Show("Inventory report is not made.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); }
}
private void textBox8_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
//check if '.' , ',' pressed
char sepratorChar = 's';
if (e.KeyChar == '.' || e.KeyChar == ',')
{
// check if it's in the beginning of text not accept
if (textBox8.Text.Length == 0) e.Handled = true;
// check if it's in the beginning of text not accept
if (textBox8.SelectionStart == 0) e.Handled = true;
// check if there is already exist a '.' , ','
if (alreadyExist(textBox8.Text, ref sepratorChar)) e.Handled = true;
//check if '.' or ',' is in middle of a number and after it is not a number greater than 99
if (textBox8.SelectionStart != textBox8.Text.Length && e.Handled == false)
{
// '.' or ',' is in the middle
string AfterDotString = textBox8.Text.Substring(textBox8.SelectionStart);
if (AfterDotString.Length > 2)
{
e.Handled = true;
}
}
}
//check if a number pressed
if (Char.IsDigit(e.KeyChar))
{
//check if a coma or dot exist
if (alreadyExist(textBox8.Text, ref sepratorChar))
{
int sepratorPosition = textBox8.Text.IndexOf(sepratorChar);
string afterSepratorString = textBox8.Text.Substring(sepratorPosition + 1);
if (textBox8.SelectionStart > sepratorPosition && afterSepratorString.Length > 1)
{
e.Handled = true;
}
}
}
}
private bool alreadyExist(string _text, ref char KeyChar)
{
if (_text.IndexOf('.') > -1)
{
KeyChar = '.';
return true;
}
if (_text.IndexOf(',') > -1)
{
KeyChar = ',';
return true;
}
return false;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dateTimePicker.Enabled = false;
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
inserttoSO(combo_custno.Text);
}
}
}

The connection is open

A few months ago I made a test program for a project and everything worked fine there.
Now I am working on the program itself, so I copied the code from the test program and
changed the the names of the columns,buttons etc. so it would fit the current program.
When I try to add something into the database it does nothing on the first click, on the
second pops up an error which says that the connection is open.. I really got no idea what's
the problem. I tried to check again if I made a mistake in a column name or the database name
but everything seems to be correct.
Note: I also have a function that show data from the database and it works without any problem.
private void InsertData()
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
Connection.Open();
DataAdd.ExecuteNonQuery();
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
string NewRowNum()
{
string Row = RowFind();
int CalcRow = int.Parse(Row) + 1;
Row = CalcRow.ToString();
return Row;
}
The connection that appears to be open is the one in the string RowFind().
Here are the other related things to the database:
public partial class frmShop : Form
{
System.Data.SqlClient.SqlConnection Connection;
public frmShop()
{
string DatabaseConnection = WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1;
Connection = new System.Data.SqlClient.SqlConnection();
Connection.ConnectionString = DatabaseConnection;
InitializeComponent();
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
Connection.Open();
SqlDataReader ReadSentence = null;
Int32 BinaryInt = Int32.Parse(txtBinaryString.Text);
string CommandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
SqlCommand Command = new SqlCommand(CommandString, Connection);
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
ReadSentence = Command.ExecuteReader();
while (ReadSentence.Read())
{
txtSentence.Text = (ReadSentence["Sentence"].ToString());
Fit = 1;
}
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You are getting errors because you are reusing the same connection Connection.Open(); several times.
Your method InsertData() is doing this 3 times in the same method.
You should create a new instance of the connection object and dispose it on your methods.
Using Statement are the way to go.
private void InsertData()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
Connection.Open();
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
DataAdd.ExecuteNonQuery();
//Connection.Close(); no need to close
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You can save one more connection if you store the row returned by RowFind()
string RowFind()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
//Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
So you would connect once instead of twice:
var Row = RowFind();
string NewCode = GenerateCode(Row);
string NewRow = NewRowNum(Row);
string NewSentence = txtSentence.Text;
Declare your connection string variable to a property so you can reuse it:
private string DatabaseConnection {get; set;}
Instead using an instance level SqlConnection you should only provide a common factory for creating a connection:
public partial class frmShop : Form
{
private string ConnectionString
{
get { return WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1; }
}
public frmShop()
{
InitializeComponent();
}
private SqlConnection CreateConnection()
{
var conn = new SqlConnection(ConnectionString);
conn.Open();
return conn;
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
using (var conn = CreateConnection())
{
var BinaryInt = int.Parse(txtBinaryString.Text);
var commandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
using (var Command = new SqlCommand(commandString, conn))
{
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
using (var readSentence = Command.ExecuteReader())
{
while (readSentence.Read())
{
txtSentence.Text = (readSentence["Sentence"].ToString());
Fit = 1;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void InsertData()
{
try
{
using (var conn = CreateConnection())
{
var commandString = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
using (var comm = new SqlCommand(commandString, conn))
{
comm.Parameters.AddWithValue("#NewBinaryString", GenerateCode());
comm.Parameters.AddWithValue("#NewNewSentence", txtSentence.Text);
comm.Parameters.AddWithValue("#NewRowNumber", NewRowNum());
comm.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
using (var conn = CreateConnection())
{
var commandString = "SELECT * FROM ShopSentences";
using (var comm = new SqlCommand(commandString, conn))
{
using (var sda = new SqlDataAdapter(queryString, Connection))
{
using (DataTable dt = new DataTable("ShopSentences"))
{
sda.Fill(dt);
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
}
}
}
string NewRowNum()
{
var Row = RowFind();
var CalcRow = int.Parse(Row) + 1;
return CalcRow.ToString();
}
}
But this is just the beginning you should not have any hard SQL dependency in your Form classes.
When sharing same SqlConnection instance several times in your code, instead of directly opening the you can rather check the connection state first and then open it if not already opened. For example:
if(Connection.State!= ConnectionState.Open)
Connection.Open();

How to retrieve the value of first index through ComboBox in C#.Net?

I kept getting "FormatException was unhandled by user Code"
Following is the Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Eventmanagement
{
public partial class Registration : Form
{
SqlConnection aConnection;
string firstname= string.Empty;
string lastname= string.Empty;
int aid;
string date = DateTime.Now.ToShortDateString();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dta;
public Registration(string fname, string lname, int attID)
{
this.firstname = fname;
this.lastname = lname;
this.aid = attID;
InitializeComponent();
}
//--------------------------------------------//
private void Registration_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'insertEventDataSet.Events' table. You can move, or remove it, as needed.
populateEventSalesPersonList();
populateEventNameIdTypeList();
//+++++++++++++++++++++++++++++++++++++++++++//
txtSalesTaxRate_Registration.Text = Convert.ToString( SalesTaxRate());
txtRegistrationID_Registration.Text = regID().ToString();
//+++++++++++++++++++++++++++++++++++++++++++//
//+++++++++++++++++++++++++++++++++++++++++++//
txtAttendee_Registration.Text = (this.firstname+" "+this.lastname);
txtRegistrationDate_Registration.Text = date.ToString();
}
//--------------------------------------------//
public string getConnectionString()
{
try
{
string sConnection = "";
// Get the mapped configuration file.
System.Configuration.ConnectionStringSettingsCollection ConnSettings = ConfigurationManager.ConnectionStrings;
sConnection = ConnSettings["DBConnectionString"].ToString();
return sConnection;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return "";
}
}
//--------------------------------------------//
public void populateEventNameIdTypeList()
{
try
{
cmbEvent_Registration.DataSource = getDataTable4();
//----------------------------
cmbEvent_Registration.ValueMember = "EventID";
cmbEvent_Registration.DisplayMember = "EventName";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//--------------------------------------------//
public void populateEventSalesPersonList()
{
try
{
cmbSalesPerson_Registration.DataSource = getDataTable5();
cmbSalesPerson_Registration.ValueMember = "EmployeeID";
cmbSalesPerson_Registration.DisplayMember = "SalesPerson";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//-------------------------------------------//
public void populateFeeScheduleByEventList()
{
try
{
cmbFeeSchedule_Registration.DataSource = getDataTable6();
cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID";
cmbFeeSchedule_Registration.DisplayMember = "Fee";
//--------------------------------------------------//
//saleTax();
//txtSalesTax_Registration.Text = Convert.ToString(saleTax());
//txtTotalCharges_Registration.Text = Convert.ToString(totalCharges());
//txtAmountDue_Registration.Text = Convert.ToString(amountDue());
//--------------------------------------------------//
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//------------------------------------------//
//------------------------------------------//
private void btnclose_Registration_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnInsert_Registration_Click(object sender, EventArgs e)
{
try
{
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
//Calling the Stored Procedure
da.InsertCommand = new SqlCommand("RegistrationInsert", aConnection);
da.InsertCommand.CommandType = CommandType.StoredProcedure;
//da.InsertCommand.Parameters.Add(#"RegistrationID", SqlDbType.Int).Value = Convert.ToInt16( txtRegistrationID_Registration.Text);
da.InsertCommand.Parameters.Add(#"AttendeeID", SqlDbType.Int).Value = Convert.ToInt16( aid);
da.InsertCommand.Parameters.Add(#"RegistrationDate", SqlDbType.SmallDateTime).Value = Convert.ToDateTime(txtRegistrationDate_Registration.Text=date.ToString());
da.InsertCommand.Parameters.Add(#"PurchaseOrderNumber", SqlDbType.VarChar).Value = txtPoNumber_Registration.Text;
// da.InsertCommand.Parameters.Add(#"SalesPerson", SqlDbType.Int).Value = Convert.ToInt64(cmbSalesPerson_Registration.SelectedValue.ToString());
da.InsertCommand.Parameters.Add(#"EventID", SqlDbType.Int).Value = cmbEvent_Registration.SelectedValue.ToString();
da.InsertCommand.Parameters.Add(#"FeeScheduleID", SqlDbType.Int).Value = cmbFeeSchedule_Registration.SelectedValue.ToString();
da.InsertCommand.Parameters.Add(#"RegistrationFee", SqlDbType.Money).Value = txtRegistrationFee_Registration.Text;
da.InsertCommand.Parameters.Add(#"EmployeeID", SqlDbType.Int).Value = Convert.ToInt16(cmbSalesPerson_Registration.SelectedValue.ToString());
da.InsertCommand.Parameters.Add(#"SalesTaxRate", SqlDbType.Float).Value = txtSalesTaxRate_Registration.Text;
//da.InsertCommand.Parameters.Add(#"EndTime", SqlDbType.SmallDateTime).Value = Convert.ToDateTime(txtEndTime.Text.ToString());
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Inserted successfully!!!");
aConnection.Close();
da.InsertCommand.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//-------------------------------------------//
public DataTable getDataTable4()
{
try
{
dta = new DataTable();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("EventsSelectAll", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
public DataTable getDataTable5()
{
try
{
dta = new DataTable();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("sp_RegistrationSalesPerson", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
dta.Clear();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
public DataTable getDataTable6()
{
try
{
dta = new DataTable();
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da.SelectCommand = new SqlCommand("sp_FeeScheduleSelectAllByEventID", aConnection);
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
private void cmbEvent_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
populateFeeScheduleByEventList();
txtRemainingSeats_Registration.Text = Convert.ToString(spaces());
}
public double saleTax()
{
double regFee = Convert.ToDouble(cmbFeeSchedule_Registration.SelectedText);
double sTR = Convert.ToDouble(SalesTaxRate());
double sr = regFee * (sTR / 100);
return sr;
}
public int totalRegisteredAttendees()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("RegistrationSelectAllByEventID", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
aConnection.Open();
int val = (int)da.SelectCommand.ExecuteScalar();
aConnection.Close();
return val;
}
public int spaces()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("EventsSelect", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
aConnection.Open();
int spaces = Convert.ToInt16(da.SelectCommand.ExecuteScalar());
aConnection.Close();
int value = totalRegisteredAttendees();
int totalspaces = spaces - value;
return totalspaces;
}
public double SalesTaxRate()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("CompanyInfo", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
aConnection.Open();
double sale = Convert.ToDouble(da.SelectCommand.ExecuteScalar());
aConnection.Close();
return sale;
}
public double totalCharges()
{
double tc = Convert.ToDouble(txtRegistrationFee_Registration.Text) + (saleTax());
return tc;
}
public double amountDue()
{
double aD;
if (txtTotalPaid_Registration.Text == string.Empty)
{
aD = Convert.ToDouble(txtTotalCharges_Registration.Text.ToString());
}
else
{
double a = Convert.ToDouble(txtTotalPaid_Registration.Text.ToString());
double b= (Convert.ToDouble(txtTotalCharges_Registration.Text.ToString()));
aD = b-a;
}
return aD;
}
public int regID()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("RegistrationID", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
aConnection.Open();
int id = ((int)da.SelectCommand.ExecuteScalar())+1;
aConnection.Close();
return id;
}
private void cmbFeeSchedule_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
saleTax();
}
//------------------------------------------//
}
}
When I call SaleTax() Method in following
private void cmbFeeSchedule_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
saleTax();
}
I get "FormatException was unhandled by user Code" Error
I debugged the Code and find out that it is happening because cmbFeeSchedule_Registration is not selecting the first index, hence it is giving the error. I am confused what to do?
How I get around this Problem?
Edit:
Well I resolved the issue. It was the problem of in ` public void populateFeeScheduleByEventList()
{
try
{
cmbFeeSchedule_Registration.DataSource = getDataTable6();
cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID";
cmbFeeSchedule_Registration.DisplayMember = "Fee";
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}`
When SaleTax() was called, pointer leaves the DisplayMember and ValueMember. Hence I readjusted the code little bit and placed cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID"; cmbFeeSchedule_Registration.DisplayMember = "Fee"; before
cmbFeeSchedule_Registration.DataSource = getDataTable6(); and it resolved the Problem. :)
If it is required that index 0 be selected in your ComboBox then you need to do some basic checking. In your SelectedIndexChanged EventHandler wire-up, you need to add:
if (cmbFeeSchedule_Registration.SelectedIndex == 0) {
salesTax();
}
Also if the user is able to change the text in the ComboBox, you are not doing any error handling to handle the FormatException that will be caused by Convert.ToDouble when trying to convert a non-double value that is not parsable.
double regFee = Convert.ToDouble(cmbFeeSchedule_Registration.SelectedText);
double sTR = Convert.ToDouble(SalesTaxRate());
Furthermore, you could actually use double.Parse or double.TryParse instead of ConvertTo, which seems more proper. On another note, if the user cannot edit the text in the ComboBox (say you have it set to DropDownList), you should use the SelectedObject or SelectedValue property instead of SelectedText depending if it is DataBound or not.
Bottom line is you need to make sure you are checking that the correct index is selected before calling salesTax() or any operation that will potentially throw an exception, and do error checking to ensure that your values are what they should be. If regFee is anything but a double, because the correct index is not selected, ConvertTo will fail. (Use double.Parse/TryParse instead, anyway)
A tip of advice when posting questions is to only post the affected segment of code, and provide a StackTrace when one is available. It's too difficult to navigate all of your code on here, and using a StackTrace it is easy to break down.
you have to make selectedindex = 0 in your form
Just do this:
if(((ComboBox)sender).SelectedIndex > -1) saleTax();
instead. If you want to select the first item when the form loads, set SelectedIndex in the Load event.

Categories

Resources