I'm making a enrollment system using visual studio 2019 and SQL server management studio 2008.When i tried to click insert button 'Inserted Successfully' and there's no errors.When i tried to click registration button 'Record Updated Successfully' and also there's no errors.But when i opened the database and refresh the database table there's no data in the data table.Any support for this issue much appreciated.
private void button2_Click(object sender, EventArgs e)
{
try
{
//taking data from the GUI
string ID = textBox1.Text;
string RegistrationNumber = textBox1.Text;
string StudentName = textBox2.Text;
string DateOfBirth = dateTimePicker1.Text;
String Age = textBox3.Text;
String Gender;
if (radioButton1.Checked == true)
{
Gender = "Male";
}
else
{
Gender = "Female";
}
string ContactNumber = textBox4.Text;
;
if (textBox1.Text == "" && textBox2.Text == "" && textBox3.Text == "" && textBox4.Text == "")
{
MessageBox.Show("Complete the Missing Data");
}
else if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Click on the selected item after selecting a course");
}
else
{
string course = (comboBox1.SelectedItem != null) ? comboBox1.SelectedItem.ToString() : "";
MessageBox.Show("Student Inserted Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
connection = new SqlConnection("Data Source=.\\(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
}
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO dbo.Table_1(ID, Registration Number, Student Name, Date of Birth, Age, Gender, Contact Number, Course Enrolled In) VALUES(#ID,#RegistrationNumber,#StudentName,#DateOfBirth,#Age,#Gender,#ContactNumber)", connection);
com.CommandType = CommandType.Text;
com.Connection = con;
com.CommandText = "SELECT * FROM dbo.Table_1 WHERE ID = #ID;";
com.Parameters.AddWithValue("#ID", textBox1.Text);
com.Parameters.AddWithValue("#RegistrationNumber", textBox1.Text);
com.Parameters.AddWithValue("#StudentName", textBox2.Text);
com.Parameters.AddWithValue("#DateOfBirth", dateTimePicker1.Text);
com.Parameters.AddWithValue("#Age", textBox3.Text);
com.Parameters.AddWithValue("#Gender", Gender);
com.Parameters.AddWithValue("#ContactNumber", textBox4.Text);
com.ExecuteNonQuery();
com.ExecuteReader();
com.Dispose();
}
catch
{
MessageBox.Show("Error");
}
finally
{
con.Close();
}
private void button6_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
if (ID == null) ;
if (textBox1.Text=="" || textBox2.Text=="" || textBox3.Text=="" || textBox4.Text=="")
{
MessageBox.Show("Please Enter Missing Details");
}
else
{
MessageBox.Show("Record Updated Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
if(con.State==ConnectionState.Closed)
{
con.Open();
}
String sql = "SELECT COUNT(*) AS [Count] FROM dbo.Table_1 WHERE ID =#ID";
SqlCommand cmd = new SqlCommand(sql, con) ;
cmd.Parameters.AddWithValue("#ID", ID);
int Id;
if (!int.TryParse(textBox1.Text, out Id))
{
// Report problem to your user
return;
}
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
{
}
}
con.Close();
}
Based on my test, I find that you defined the SqlCommand.CommandText two times.
Please try to modify your code to the following.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth
);
Also, please note that we should place the MessageBox.Show after the code com.ExecuteNonQuery();.
Here is a code example you could refer to, based on my test, it works well.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ID = textBox1.Text;
string StudentName = textBox2.Text;
DateTime DateOfBirth = dateTimePicker1.Value;
string constr = "sttr";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth);
command.ExecuteNonQuery();
MessageBox.Show("success inserted");
connection.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
string constr = "str";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT COUNT(*) AS [Count] FROM Student WHERE ID =#ID";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
MessageBox.Show("Record Updated Successfully!!");
}
After the below line
com.connection = con;
add below code
com.executenonquery();
Related
Building a form application in C# for selling phones as a project. I have two radio buttons which the user checks based on what type of payment method they want cash or card.
How do I insert that data into the database based on what the user selects?
You can try this,
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
SqlConnection cn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into sample values(#payment)";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#payment", payment.SelectedValue);
if (cn.State == ConnectionState.Closed)
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
lblmsg.Text = "Data entered successfully!!!";
}
I found the answer to my own question if someone needs it
try
{
var connection = getConnection();
connection.Open();
if (CashRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText ="INSERT INTO type_payment(cash,card) values(1,0)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succsefully picked type");
}
else
{
MessageBox.Show("error");
}
}
else if (CardRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText = "INSERT INTO type_payment(cash,card) values(0,1)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succesfully picked type");
}
else
{
MessageBox.Show("Error");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Luka,
Try it below.
Add HTML Markup like:
<asp:CheckBox ID="chkCash" runat="server" />
.cs file add below code.
string Cash = chkCash.Checked ? "Y" : "N";
And send or add value like.
SqlCommand cmd = new SqlCommand("INSERT INTO Employees(Cash) VALUES(#Cash)"))
{
cmd.Parameters.AddWithValue("#Cash", Cash);
}
I have a form which updates data. Query is executing but not updating the data. What's wrong? How to fix this?
It was working when I had concatenation but I changed it to parameters and now it's not working
private void button11_Click(object sender, EventArgs e)
{
try
{
if (SId.Text == "" || SellName.Text == "" || SellAge.Text == "" || SellPhone.Text == "" || SellPass.Text == "")
{
MessageBox.Show("Missing info");
}
string query = "UPDATE Sellers SET [SellerName] = #Name, [SellerAge] = #Age, [SellerPhone] = #Phone, [SellerPassword] = #Pass WHERE [SellerId] = #Id";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("#Id", SId.Text);
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Update successful!");
SId.Text = "";
SellName.Text = "";
SellPhone.Text = "";
SellPass.Text = "";
SellAge.Text = "";
Con.Close();
populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have to use a connection for the shortest time possible. Instead of conection.Open() use cmd.connection.Open(). I recommend to use this code:
var result=0;
using (var con= new SqlConnection(connectionString))
{
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Id", SId.Text); //??? if #Id is int or varchar?
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
cmd.Connection.Open();
result=cmd.ExecuteNonQuery();
}
if(result>0) MessageBox.Show("Update successful!");
else ....error
.... your code
I marked with ?? your #Id input parameter. I have some doubts that it is a string type. Check again. If it is int or any another type you will have to convert SId.Text to this type before to create a parameter.The same about #Age.
I'd like to integrate an autocheck that prevent user to forget to save changes with a textbox 'Do you want to save change' Yes-No
If yes - > save
if no - > returns
Here's my code without the checking
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
OleDbConnection conn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
conn = new
OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data
Source=" + #Application.StartupPath + "\\Database1.mdb");
fill_lb();
}
private void fill_lb()
{
listBox1.Items.Clear();
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] ORDER BY firstn";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
listBox1.Items.Add(dr["firstn"].ToString());
}
conn.Close();
}
private void listBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" +
listBox1.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
textBox_fn.Text = dr["firstn"].ToString();
textBox_ln.Text = dr["lastn"].ToString();
}
conn.Close();
}
private void button_savenew_Click(object sender, EventArgs e)
{
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO [table1] ([firstn],[lastn])
values ([#firstn],[#lastn])";
cmd.Parameters.AddWithValue("#firstn", textBox_fn.Text);
cmd.Parameters.AddWithValue("#lastn", textBox_ln.Text);
cmd.ExecuteNonQuery();
fill_lb();
conn.Close();
}
private void button_modify_Click(object sender, EventArgs e)
{
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE [Table1] SET [firstn]=[#firstn],
[lastn]=[#lastn] WHERE firstn = '" +
listBox1.SelectedItem.ToString() + "'";
cmd.Parameters.AddWithValue("#firstn", textBox_fn.Text);
cmd.Parameters.AddWithValue("#lastn", textBox_ln.Text);
cmd.ExecuteNonQuery();
fill_lb();
conn.Close();
}
private void button_new_Click(object sender, EventArgs e)
{
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
}
}
}
What I've done with no success :
Bool modified = false
private void textBox_fn_TextChanged(object sender, EventArgs e)
{
modified = true;
}
private void textBox_ln_TextChanged(object sender, EventArgs e)
{
modified = true;
}
private void listBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
if (modified.Equals(true))
{
DialogResult dialogr = MessageBox.Show("Do you want to
save change ?","", MessageBoxButtons.YesNo);
switch (dialogr)
{
case DialogResult.Yes:
button_savenew.PerformClick();
modifie = false;
break;
case DialogResult.No:
return;
}
}
modified = false;
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
}
This is not working because it ask to save everytime I click on listbox
What Can I do ?
I would look into using a MessageBox. It would greatly simplify what you are trying to do. Perform the check in the background, and if they didn't save do this:
string message = "Are you sure you don't want to save?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, "Are you Sure", buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Save file
}
if (result == System.Windows.Forms.DialogResult.No){
this.Close();
}
Remove the the associate code from listBox1_SelectedIndexChanged event and add to it the end of button_modify_Click. Try like:
private void Check()
{
if (modified.Equals(true))
{
DialogResult dialogr = MessageBox.Show("Do you want to
save change ?","", MessageBoxButtons.YesNo);
switch (dialogr)
{
case DialogResult.Yes:
button_savenew.PerformClick();
modifie = false;
break;
case DialogResult.No:
return;
}
}
modified = false;
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
}
private void button_modify_Click(object sender, EventArgs e)
{
if (conn.State != ConnectionState.Open) { conn.Close();
conn.Open(); }
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE [Table1] SET [firstn]=[#firstn],
[lastn]=[#lastn] WHERE firstn = '" +
listBox1.SelectedItem.ToString() + "'";
cmd.Parameters.AddWithValue("#firstn", textBox_fn.Text);
cmd.Parameters.AddWithValue("#lastn", textBox_ln.Text);
cmd.ExecuteNonQuery();
fill_lb();
Check(); //<--added here
conn.Close();
}
Try resetting modified after DB update, at the end of button_modify_Click
I think I found the right way to do the job using the tag property.
first I add a new boolean that will check if I leave a textbox
bool left_txtbox = false; //when leaving textbox
then I add this code the the Leave property of textboxes
private void textBox_fn_Leave(object sender, EventArgs e)
{
name = listBox1.SelectedItem.ToString();
textBox_fn.Tag = textBox_fn.Text;
left_txtbox = true;
}
private void textBox_ln_Leave(object sender, EventArgs e)
{
name = listBox1.SelectedItem.ToString();
textBox_ln.Tag = textBox_ln.Text;
left_txtbox = true;
}
on listbox selected index change I add the check when leaving textbox
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (left_txtbox == true) Check(); // if txtbox has been left, do the check
textBox_fn.Text = string.Empty;
textBox_ln.Text = string.Empty;
if (conn.State != ConnectionState.Open) { conn.Close(); conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" + listBox1.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
textBox_fn.Text = dr["firstn"].ToString();
textBox_ln.Text = dr["lastn"].ToString();
}
conn.Close();
}
finally the check itself, it will compare the Tag with the value stored in DB
private void Check()
{
if (conn.State != ConnectionState.Open) { conn.Close(); conn.Open(); }
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" + name + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
try // ignore null values
{
if (textBox_fn.Tag.ToString() != dr["firstn"].ToString()) { modified = true; }
if (textBox_ln.Tag.ToString() != dr["lastn"].ToString()) { modified = true; }
}
catch { }
if (modified.Equals(true))
{
DialogResult dialogr = MessageBox.Show("Do you want to save change ? ", "", MessageBoxButtons.YesNo);
switch (dialogr)
{
case DialogResult.Yes:
button_savenew.PerformClick();
modified = false;
break;
case DialogResult.No:
modified = false;
return;
}
}
modified = false;
}
I think the code can be optimized
I am a newbie.
I am attempting to check for duplicate database entries. My problem is:
I would like a success alert shown if the entry is successful.
A notification of duplicates shown if a duplicate exists.
My issue is: the alert for duplicates gets shown multiple times, however, the entry is never created if no duplicates exist.
This is my code:
/// <summary>
/// The following procedure creates the user account in the database The procedure first attempts to
/// perform a check for duplicates before submitting the registration info
/// </summary>
protected void BTN_CreateACNT_Click(object sender, EventArgs e)
{
string InsertQuery = "";
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
InsertQuery = "Insert into TBL_Logins (FirstName, LastName, EmailAddress, Password) VALUES(#FirstName, #LastName, #EmailAddress, #Password)";
String FirstNameSTR = FN.Text.Trim();
String LastNameSTR = LN.Text.Trim();
String EMailAddressSTR = EmailAddress.Text.Trim();
byte[] PassByte = StrToByteArray(PWD.Text.Trim());
// CheckUser(EMailAddressSTR);
while (CheckUser(EMailAddressSTR) == false)
{
SqlConnection CN = new SqlConnection(ConnectionString);
SqlCommand CMD = new SqlCommand(InsertQuery, CN);
CMD.CommandType = CommandType.Text;
CMD.Parameters.AddWithValue("#Firstname", FirstNameSTR);
CMD.Parameters.AddWithValue("#LastName", LastNameSTR);
CMD.Parameters.AddWithValue("#EmailAddress", EMailAddressSTR);
CMD.Parameters.AddWithValue("#Password", PassByte);
CN.Open();
CMD.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('Account created successfully.');</script>");
CN.Close();
}
}
public bool CheckUser(String UserString)
{
String UserSelect = "Select * from TBL_Logins where EmailAddress = #EmailAddress";
int MailCount = 0;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
SqlConnection CN = new SqlConnection(ConnectionString);
UserString = EmailAddress.Text.Trim();
SqlCommand CMD = new SqlCommand(UserSelect, CN);
CMD.Parameters.AddWithValue("#EmailAddress", UserString);
CN.Open();
SqlDataReader dr = CMD.ExecuteReader();
while (dr.Read())
{
if (UserString == dr["EmailAddress"].ToString())
{
Response.Write("<script language='javascript'>alert('This EMail address is already taken. Please try again.');</script>");
// return true;
}
}
CN.Close();
return true;
}
protected void BTN_CreateACNT_Click(object sender, EventArgs e)
{
string InsertQuery = "";
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
InsertQuery = "Insert into TBL_Logins (FirstName, LastName, EmailAddress, Password) VALUES(#FirstName, #LastName, #EmailAddress, #Password)";
String FirstNameSTR = FN.Text.Trim();
String LastNameSTR = LN.Text.Trim();
String EMailAddressSTR = EmailAddress.Text.Trim();
byte[] PassByte = StrToByteArray(PWD.Text.Trim());
// CheckUser(EMailAddressSTR);
while(CheckUser(EMailAddressSTR) == false)
{
SqlConnection CN = new SqlConnection(ConnectionString);
SqlCommand CMD = new SqlCommand(InsertQuery, CN);
CMD.CommandType = CommandType.Text;
CMD.Parameters.AddWithValue("#Firstname", FirstNameSTR);
CMD.Parameters.AddWithValue("#LastName", LastNameSTR);
CMD.Parameters.AddWithValue("#EmailAddress", EMailAddressSTR);
CMD.Parameters.AddWithValue("#Password", PassByte);
CN.Open();
CMD.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('Account created successfully.');</script>");
CN.Close();
}
}
public bool CheckUser(String UserString)
{
String UserSelect = "Select * from TBL_Logins where EmailAddress = #EmailAddress";
int MailCount = 0;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Reimburse"].ConnectionString;
SqlConnection CN = new SqlConnection(ConnectionString);
UserString = EmailAddress.Text.Trim();
SqlCommand CMD = new SqlCommand(UserSelect,CN);
CMD.Parameters.AddWithValue("#EmailAddress", UserString);
CN.Open();
SqlDataReader dr = CMD.ExecuteReader();
while (dr.Read())
{
if (UserString == dr["EmailAddress"].ToString())
{
Response.Write("<script language='javascript'>alert('This EMail address is already taken. Please try again.');</script>");
// return true;
}
}
CN.Close();
return true;
}
Looks like the CheckUser method always returns true and that's why the insertion does not work, update the method to return false by default:
while (dr.Read())
{
if (UserString == dr["EmailAddress"].ToString())
{
Response.Write("<script language='javascript'>alert('This EMail address is already taken. Please try again.');</script>");
return true; // return true if user exists
}
}
CN.Close();
return false; // return false if the user does not exist
It is also recommended to use using block to dispose the DB connection instead of manually invoking the Close() method.
I am 100% sure my listview has data. My program will get the ID from the column 0 of my listview, connects to the database, and using the ID as my reference will get the data from my database and display it to my textboxes/comboboxes. SO when I click an item from my listview, an exception appears and all of my textboxes as well as my comboboxes are empty. I am new to c# and programming, any help will be much appreciated.
using System;
using System.Data.OleDb;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
private string button = null;
private string carID;
public Form1()
{
InitializeComponent();
textDateReg.Text = DateTime.Now.ToString();
lvRefresh();
}
private void lvRefresh()
{
listView1.Items.Clear();
listView1.View = View.Details;
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\genesis\\Documents\\Database2.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand("Select ID, PlateNo from Cars", con);
OleDbDataReader cmdrdr = cmd.ExecuteReader();
if (cmdrdr.HasRows)
{
while (cmdrdr.Read())
{
ListViewItem list = new ListViewItem(cmdrdr["ID"].ToString());
list.SubItems.Add(cmdrdr["PlateNo"].ToString());
listView1.Items.Add(list);
}
}
con.Close();
cmdrdr.Close();
cmd.Dispose();
}
private void buttonNew_Click(object sender, EventArgs e)
{
button = "new";
buttonSub.Enabled = true;
panel1.Enabled = true;
}
private void textBox7_MouseClick(object sender, MouseEventArgs e)
{
textBox7.Text = null;
}
private void buttonSub_Click(object sender, EventArgs e)
{
switch (button)
{
case "new":
DialogResult dialogResult = MessageBox.Show("Are you sure you want to Register?", "Confirm", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
string Adrs = this.textADRS.Text;
string Fname = this.textFN.Text;
string Mname = this.textMN.Text;
string Lname = this.textLN.Text;
string Age = this.textAGE.Text;
string RegDate = this.textDateReg.Text;
string Gender = comboGender.SelectedItem.ToString();
string Phone = this.textPHONE.Text;
string Color = this.textColor.Text;
string Type = this.comboType.SelectedItem.ToString();
string Brand = this.textBrand.Text;
string Model = this.textModel.Text;
string PlateNo = this.textPlateNo.Text;
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\genesis\\Documents\\Database2.accdb";
OleDbCommand cmd = new OleDbCommand("Insert into Drivers (FirstName,MiddleName,LastName,Address,Age,PhoneNo,Gender,RegDate) Values (#FirstName,#MidName,#LastName,#Address,#Age,#Phone,#Gender,#RegDate)", con);
con.Open();
cmd.Parameters.Add(new OleDbParameter("#FirstName", Fname));
cmd.Parameters.Add(new OleDbParameter("#MidName", Mname));
cmd.Parameters.Add(new OleDbParameter("#LastName", Lname));
cmd.Parameters.Add(new OleDbParameter("#Address", Adrs));
cmd.Parameters.Add(new OleDbParameter("#Age", Age));
cmd.Parameters.Add(new OleDbParameter("#Phone", Phone));
cmd.Parameters.Add(new OleDbParameter("#Gender", Gender));
cmd.Parameters.Add(new OleDbParameter("#RegDate", RegDate));
cmd.ExecuteNonQuery();
cmd.Dispose();
cmd = new OleDbCommand("Insert into Cars(Color, Brand, Model, Type, PlateNo) Values(#Color, #Brand, #Model, #Type, #PlateNo)", con);
cmd.Parameters.Add(new OleDbParameter("#Color", Color));
cmd.Parameters.Add(new OleDbParameter("#Brand", Brand));
cmd.Parameters.Add(new OleDbParameter("#Model", Model));
cmd.Parameters.Add(new OleDbParameter("#Type", Type));
cmd.Parameters.Add(new OleDbParameter("#PlateNo", PlateNo));
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
MessageBox.Show("Record Submitted", "Nice!");
lvRefresh(); //refresh listview
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
break;
case "del":
dialogResult = MessageBox.Show("Are you sure you want to Register?", "Confirm", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
string Adrs = this.textADRS.Text;
string Fname = this.textFN.Text;
string Mname = this.textMN.Text;
string Lname = this.textLN.Text;
string Age = this.textAGE.Text;
string RegDate = this.textDateReg.Text;
string Gender = comboGender.SelectedItem.ToString();
string Phone = this.textPHONE.Text;
string Color = this.textColor.Text;
string Type = this.comboType.SelectedItem.ToString();
string Brand = this.textBrand.Text;
string Model = this.textModel.Text;
string PlateNo = this.textPlateNo.Text;
try
{
}
catch
{
}
}
break;
case "edit":
break;
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Enabled = true;//panel that contains my textboxes/comboboxes
buttonDel.Enabled = true;
try
{
ListViewItem item = listView1.SelectedItems[0];
carID = item.Text;
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\genesis\\Documents\\Database2.accdb";
OleDbCommand cmd = new OleDbCommand("Select * from Drivers where ID = #ID", con);
con.Open();
cmd.Parameters.AddWithValue("#ID", carID);
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.HasRows)
{
textFN.Text = rdr["FirstName"].ToString();
textMN.Text = rdr["MiddleName"].ToString();
textLN.Text = rdr["LastName"].ToString();
textADRS.Text = rdr["Address"].ToString();
textPHONE.Text = rdr["PhoneNo"].ToString();
textDateReg.Text = rdr["RegDate"].ToString();
textAGE.Text = rdr["Age"].ToString();
comboGender.Text = rdr["Gender"].ToString();
if (!rdr.HasRows)
{
rdr.Close();
cmd.Dispose();
OleDbCommand cmdc = new OleDbCommand("Select * from Cars where ID = #ID", con);
cmdc.Parameters.AddWithValue("#ID", carID);
OleDbDataReader rdrc = cmdc.ExecuteReader();
while (rdrc.HasRows)
{
textColor.Text = rdr["Color"].ToString();
comboType.Text = rdr["Type"].ToString();
textBrand.Text = rdr["Brand"].ToString();
textModel.Text = rdr["Model"].ToString();
textPlateNo.Text = rdr["PlateNo"].ToString();
}
rdrc.Close();
cmdc.Dispose();
con.Close();
}
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
}
}