read access database and bind to label - c#

I am having trouble from binding the data retrieved into the label. which i will create a session variable from the label the data is the supplierid of the recent new record
Here the .cs file
protected void InsertSupplier(object sender, EventArgs e)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/IESDatabase.accdb");
OleDbCommand cmd;
string strSQLInsert = "INSERT INTO "
+ " Supplier (sName, sPhone, sAddress, sCompany, sStatus)"
+ " VALUES (#name, #phone, #add, #co, #status)";
mDB.Open();
cmd = new OleDbCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#name", txtfullname.Text);
cmd.Parameters.AddWithValue("#phone", Phone.Text);
cmd.Parameters.AddWithValue("#add", txtaddress.Text);
cmd.Parameters.AddWithValue("#co", CompanyNameBox.Text);
cmd.Parameters.AddWithValue("#status", lblStatus.Text);
cmd.ExecuteNonQuery();
mDB.Close();
/*
OleDbDataReader rdr;
string strSQLSelect = "SELECT sSupplierId FROM Supplier ORDER BY sSupplierId";
mDB.Open();
cmd = new OleDbCommand(strSQLSelect, mDB);
rdr = cmd.ExecuteReader();
while (rdr.Read() == true)
{
lblSupplier.Text = rdr["sSupplierId"].ToString();
}
Session["sSupplierId"] = (string)lblSupplier.Text;
*/
MessageBox.Show("Insert New Supplier is successful", "Admin");
Response.Redirect("Adminpage.aspx");
}

Related

Connection was not closed. Connection's current State was open

I'm currently finishing my payroll system with ms access database used to connect with my program. CRUD is one of our main requirements to finish this project but ADD button said that my connection was not closed. Connection's current State was open.
private void btnAddDB_Click(object sender, EventArgs e)
{
try
{
Connection.Open();
OleDbCommand command1 = new OleDbCommand();
OleDbCommand command2 = new OleDbCommand();
OleDbCommand command3 = new OleDbCommand();
command1.Connection = Connection;
command2.Connection = Connection;
command3.Connection = Connection;
command1.CommandText = "Select* from employeeinfo where Employee ID = '" + txtEID.Text + "'";
OleDbDataReader reader1 = command1.ExecuteReader();
command2.CommandText = "Select* from employeeinfo where Email Address = '" + txtEA.Text + "'";
OleDbDataReader reader2 = command2.ExecuteReader();
command3.CommandText = "Select* from employeeinfo where Contact Number = '" + txtCN.Text + "'";
OleDbDataReader reader3 = command3.ExecuteReader();
string conn1, conn2, conn3;
while (reader1.Read())
{
con1.Text = reader1["Employee ID"].ToString();
}
while (reader2.Read())
{
con2.Text = reader2["Email Address"].ToString();
}
while (reader3.Read())
{
con3.Text = reader3["Contact Number"].ToString();
}
conn1 = con1.Text;
if (conn1 != con1.Text)
{
conn2 = con2.Text;
if (conn2 != con2.Text)
{
conn3 = con3.Text;
if (conn3 != con3.Text)
{
OleDbCommand command = new OleDbCommand();
command.Connection = Connection;
command.CommandText = "INSERT INTO employeeinfo ([Employee ID], [Employee Name], [Department], [First Name], [Middle Name, [Surname], [Address], [Contact Number], [Email Address], [Salary]) values(#empid, #empname, #dep, #fname, #mname, #sname, #address, #connum, #emadd, #sal)";
command.Parameters.AddWithValue("#empid", txtEID.Text);
command.Parameters.AddWithValue("#empname", txtEN.Text);
command.Parameters.AddWithValue("#dep", txtDep.Text);
command.Parameters.AddWithValue("#fname", txtFN.Text);
command.Parameters.AddWithValue("#mname", txtMN.Text);
command.Parameters.AddWithValue("#sname", txtSN.Text);
command.Parameters.AddWithValue("#address", txtAdd.Text);
command.Parameters.AddWithValue("#connum", txtCN.Text);
command.Parameters.AddWithValue("#emadd", txtEA.Text);
command.Parameters.AddWithValue("#sal", textBox2.Text);
command.ExecuteNonQuery();
MessageBox.Show("Employee Information Created");
}
else if (conn3 == txtCN.Text)
{
MessageBox.Show("Contact Number Already exist");
con3.Text = "";
}
}
else if (conn2 == txtEA.Text)
{
MessageBox.Show("Email Address Already exist");
con2.Text = "";
}
}
else if (conn1 == txtEID.Text)
{
MessageBox.Show("Email ID Already exist");
con1.Text = "";
}
Connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
}

How to open next form base on select query base on flag

I am creating one application my requirement is what when column name Status is N in Registration table, then current form should hide and Login form should be open.
If Status is not N then its should be open Registration_Form. I'm trying but it's causing
Error creating window handle
on the rf.Show() call.
on insert button code
string status = "Y";
//Random random = new Random();
//int randomNumber = random.Next(0, 100);
string random1 = System.Web.Security.Membership.GeneratePassword(10, 0);
string concate = textBox1.Text + "-" + textBox2.Text + "-" + textBox3.Text.Substring(textBox3.Text.Length - 4) + "-" + random1;
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string SqlString = "Insert Into Registration (Name,Last_Name,Contact_No,Address,Insert_Date,Registration_key,Status) Values (?,?,?,?,?,?,?)";
//using (OleDbCommand cmd = new OleDbCommand(SqlString, con))
//{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Last_Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Contact_No", textBox3.Text);
cmd.Parameters.AddWithValue("#Address", textBox4.Text);
cmd.Parameters.AddWithValue("#Insert_Date", textBox5.Text);
cmd.Parameters.AddWithValue("#Registration_key", concate);
cmd.Parameters.AddWithValue("#Status", status);
//}
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully,NOW PLEASE ACTIVATE APPLICATION PUTTING ACTIVATE KEY ", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
on update button code --
string Status = "N";
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string recover = "SELECT Registration_key from Registration where Registration_key='" + textBox6.Text + "'";
OleDbCommand cmd = new OleDbCommand(recover, con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox6.Text = reader["Registration_key"].ToString();
if (con.State == ConnectionState.Open)
{
con.Close();
}
string cmd1 = "update Registration set Status=#Status where Registration_key=#Registration_key";
cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#Registration_key", textBox6.Text);
con.Open();
int n2 = cmd.ExecuteNonQuery();
con.Close();
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Invalid Activated Key", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
con.Close();
on load event--
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
i got a solution i remove e
lse if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
this and instead that normal use else condition
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Pls Register yourself");
}
this code giving me what requirement i want

How to make dependent combo boxes work correctly

I have two combo boxes "Year" & "Amount" on the top of them I do get values for user info, because there are text boxes when called with user ID text boxes fill up with correct data.
The two combo boxes are also filled with correct data but I have to manually select year and the amount corresponding to it.
I need help in when I call the data "Year" & "Amount" should appear visible in the combo box. When I select a Year then the Amount should change accordingly. Last but not the least my reset is not clearing the combo boxes.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace dss
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Data Source=USER-PC\\sqlexpress;Initial Catalog=JG_Test;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
cmbYear.Items.Clear();
string sql = "";
con.Open();
SqlCommand cmd = new SqlCommand();
try
{
sql += "SELECT m.MemberId, m.Name, m.Address, m.Cellular, m.Email, p.PaymentId, p.Year, p.Amount from Members as m";
sql += " INNER JOIN Payments as p ON m.MemberId = p.MemberId";
sql += " WHERE m.MemberId = '" + tbID.Text + "' ORDER BY p.Year ASC";
cmd.Connection = con;
cmd.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if(dt.Rows.Count >0)
{
for(int i = 0; i<=dt.Rows.Count -1;i++)
{
tbID.Text = dt.Rows[i]["MemberId"].ToString();
tbName.Text = dt.Rows[i]["Name"].ToString();
tbCellular.Text = dt.Rows[i]["Cellular"].ToString();
tbEmail.Text = dt.Rows[i]["Email"].ToString();
tbAddress.Text = dt.Rows[i]["Address"].ToString();
cmbAmount.Items.Add(dt.Rows[i]["Amount"].ToString());
cmbYear.Items.Add(dt.Rows[i]["Year"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
//This part displaying og the existing data from all the fileds corrssponding within the database//
private void btnAdd_Click(object sender, EventArgs e)
{
{
con.Open();
string Sql = "INSERT INTO Members ( MemberId, Name, Cellular, Email, Address ) VALUES " + " (#Id, #name, #cell, #email, #address)";
using (SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#name", tbName.Text);
cmd.Parameters.AddWithValue("#cell", tbCellular.Text);
cmd.Parameters.AddWithValue("#email", tbCellular.Text);
cmd.Parameters.AddWithValue("#address", tbAddress.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Payments ( MemberId, [Year], [Amount] ) VALUES " + " (#Id, Amount, Year)";
cmd.Parameters.Clear();
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#year", cmbYear.Text);
cmd.Parameters.AddWithValue("#amount", cmbAmount.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
tbID.Clear(); tbName.Clear(); tbCellular.Clear(); tbEmail.Clear(); tbAddress.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
con.Close();
}
}
}
//This part represents adding of new input data from all the fileds into the database//
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "UPDATE Members SET MemberId = '" + tbID.Text + "', Name = '" + tbName.Text + "', Cellular = '" + tbCellular.Text + "', Email = '" + tbEmail.Text + "', Address = '" + tbAddress.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "UPDATE Payments SET MemberId = '" + tbID.Text + "', Year = '" + cmbYear.Text + "', Amount = '" + cmbAmount.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Updated");
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents deleteing of input data from all the fileds into the database//
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "DELETE FROM Members WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "DELETE FROM Payments WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
MessageBox.Show("Data Deleted");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents clearing of input data from all the fileds//
private void btnReset_Click(object sender, EventArgs e)
{
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
//This part represents shuting down the application//
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
I would be inclined to simplify things a bit. Treat the personal data and the finance data as 2 parts.
Firstly, request the personal data - keep it simple
private void btnSearch_Click(object sender, EventArgs e)
{
string sql = "SELECT MemberId, Name, Address, Cellular, Email FROM Members WHERE MemberId = #Id";
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
tbID.Text = dt.Rows[0]["MemberId"].ToString();
tbName.Text = dt.Rows[0]["Name"].ToString();
tbCellular.Text = dt.Rows[0]["Cellular"].ToString();
tbEmail.Text = dt.Rows[0]["Email"].ToString();
tbAddress.Text = dt.Rows[0]["Address"].ToString();
}
Once thats done, move on to second part - the years/amounts combo (which is almost identical code)
string sql = "SELECT Year, Amount FROM Payments WHERE MemberId = #Id"
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
cmbYear.DataSource = dt;
cmbYear.DisplayMember = "Year";
cmbYear.ValueMember = "Amount";
And finally, tell the textbox what it needs to read by using
private void cmbYear_SelectionChangeCommitted(object sender, EventArgs e)
{
amountTxt.Text = cmbYear.SelectedValue.ToString();
}
in the combobox's SelectionChangeCommitted event
And that should have you sorted!

Why won't my labels stay changed

when i run my code the labels stay the same but when i debug it i can see the text changes and then changes back when it is done runnning
public void getData(string a)
{
SqlConnection conn = new SqlConnection(#"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
label1.Text = reader["UserID"].ToString();
label2.Text = reader["UserName"].ToString();
label3.Text = reader["Email"].ToString();
}
conn.Close();
}
Just in case, try this:
public void getData(string a) {
SqlConnection conn = new SqlConnection(#"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
SqlDataReader reader = command.ExecuteReader();
string id, name, email;
while (reader.Read())
{
id = reader["UserID"].ToString();
name = reader["UserName"].ToString();
email = reader["Email"].ToString();
}
conn.Close();
label1.Text = id;
label2.Text = name;
label3.Text = email;
}
}
Hope, it helps.

MS Access database not updating

Can anybody tell me why my database isn't updating? Here's my code:
protected void editSection_selected(object sender, EventArgs e) {
int index = grdPhone.SelectedIndex;
GridViewRow row = grdPhone.Rows[index+1];
string values = ((DropDownList)sender).SelectedValue;
int tempVal = Convert.ToInt32(values);
int caseage = Convert.ToInt32(keyId);
int value = tempVal;
/*OleDbConnection con = new OleDbConnection(strConnstring);
//string query = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
string query = "Delete HRS_LEVEL_AMOUNT from Categories where parent_id=65 and id=" + caseage;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Dispose();
cmd.Dispose();
con.Close();
accPhoneNumbers.UpdateCommand = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
*/
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = ? WHERE ID=?";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("HRS_LEVEL_AMOUNT", tempVal);
cmd.Parameters.AddWithValue("ID", caseage);
con.Open();
cmd.ExecuteNonQuery();
}
}
Label1.Text += " editSection Success! (B) " + tempVal;
}
The commented part is my first solution (including the accPhoneNumbers.UpdateCommand).
I really need your help guys.
I hope this can help you:
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = #value1 WHERE ID=#value2";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value1", tempVal);
cmd.Parameters.AddWithValue("#value2", caseage);
con.Open();
cmd.ExecuteNonQuery();
con.close();
}
}
For more information you can visit this video

Categories

Resources