SQL Interjection Error - c#

What I had tried
I had tried using data adapter but it didn't work I tried using data reader but I am not sure on how to go about using it properly.
I want to get the value 12.0 to be saved and displayed into data grid view at the moment if I key 12.1 it also works only like 12.0 it will be entered and displayed as 12 at the data grid view
private void button1_Click(object sender, EventArgs e)
{
if (comboBoxstaff.Text == string.Empty)
{
MessageBox.Show("Please Select gaugeman"); // not to let thecombobox empty
return;
}
else if (comboBoxcompondrubber.Text == string.Empty)
{
MessageBox.Show("Please Select Compond Rubber");// not to let thecombobox empty
return;
}
else if (textBox1.Text == string.Empty)
{
MessageBox.Show("Please Key in W.S thickness");// not to let thetextbox empty
return;
}
else if (textBox2.Text == string.Empty)
{
MessageBox.Show("Please Key in G.S thickness");// not to let thecombobox empty
}
SQLiteConnection insertsess = new SQLiteConnection("Data Source=|DataDirectory|\\test1db");
string insert12 = "INSERT INTO thickness (GaugeMan,Dateandtime, CompondRubber,GSthickness,WSthicknes) VALUES ('" + comboBoxstaff.Text + "','" + label2.Text + "', '" + comboBoxcompondrubber.Text + "', '" + textBox2.Text + "', '" + textBox1.Text + "')"; //insert statment
SQLiteCommand ins1 = new SQLiteCommand(insert12, insertsess);
insertsess.Open();
ins1.ExecuteNonQuery();
MessageBox.Show("Data had been saved");// showed when the message is being saved
SQLiteConnection sesscheck = new SQLiteConnection("Data Source=|DataDirectory|\\test1db");
SQLiteCommand chk1;
chk1 = sesscheck.CreateCommand();
chk1.CommandText = "SELECT GaugeMan,Dateandtime, CompondRubber,GSthickness,WSthicknes FROM thickness WHERE CompondRubber = '" + comboBoxcompondrubber.Text.Trim() + "'";
sesscheck.Open();
DataTable thicknessTable = new DataTable();
//DataTable thicknessTable = new DataTable();
SQLiteDataReader reader = chk1.ExecuteReader();
thicknessTable.Load(reader);
//SQLiteDataReader reader1 = chk2.ExecuteReader();
//thicknessTable.Load(reader1);
sesscheck.Close();
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}

Related

Why do i have question marks instead of text in DataGridView?

So i'm writing a program with C# and Sql, i created a database in visual studio and DataSet, and connected it to DataGridView. But the problem is, when i insert something into DataGridView row, all strings are presented as question marks, but with "int" type everything is okay.
namespace MH
{
public partial class PatientForm : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Admin\source\repos\MH\MH\MH.mdf;Integrated Security=True");
public PatientForm()
{
InitializeComponent();
}
void populate()
{
conn.Open();
string query = "select * from Patient";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
PatientGV.DataSource = ds.Tables[0];
conn.Close();
}
private void label9_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void PatientForm_Load(object sender, EventArgs e)
{
populate();
PatientGV.Columns[0].HeaderText = "ID пациента";
PatientGV.Columns[1].HeaderText = "Имя";
PatientGV.Columns[2].HeaderText = "Адрес";
PatientGV.Columns[3].HeaderText = "Телефон";
PatientGV.Columns[4].HeaderText = "Возраст";
PatientGV.Columns[5].HeaderText = "Пол";
PatientGV.Columns[6].HeaderText = "Группа крови";
PatientGV.Columns[7].HeaderText = "Основная болезнь";
}
private void button4_Click(object sender, EventArgs e)
{
Home h = new Home();
h.Show();
this.Hide();
}
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
string query = "update Patient set PatName = '" + PatName.Text + "', PatAddress = '" + PatAd.Text + "', PatPhone = '" + PatPhone.Text + "', PatAge = '" + PatAge.Text + "', PatGender = '" + GenderCb.SelectedItem.ToString() + "', PatBlood = '" + BloodCb.SelectedItem.ToString() + "', PatDisease = '" + MajorTb.Text + "' where PatId = '" + PatId.Text + "'";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Пациент успешно обновлен");
conn.Close();
populate();
}
private void PatientGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.PatientGV.Rows[e.RowIndex];
PatId.Text = row.Cells[0].Value.ToString();
PatName.Text = row.Cells[1].Value.ToString();
PatAd.Text = row.Cells[2].Value.ToString();
PatPhone.Text = row.Cells[3].Value.ToString();
PatAge.Text = row.Cells[4].Value.ToString();
MajorTb.Text = row.Cells[7].Value.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (PatId.Text == "" || PatName.Text == "" || PatAd.Text == "" || PatPhone.Text == "" || PatAge.Text == "" || MajorTb.Text == "")
MessageBox.Show("Пустые поля не принимаются!");
else
{
conn.Open();
string query = "insert into Patient values(" + PatId.Text + ",'" + PatName.Text + "','" + PatAd.Text + "','" + PatPhone.Text + "'," + PatAge.Text + "," +
"'" + GenderCb.SelectedItem.ToString() + "','" + BloodCb.SelectedItem.ToString() + "','" + MajorTb.Text + "')";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Запись успешно добавлена!");
conn.Close();
populate();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (PatId.Text == "")
MessageBox.Show("Введите ID пациента");
else
{
conn.Open();
string query = "delete from Patient where PatId=" + PatId.Text + "";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Пациент успешно удален");
conn.Close();
populate();
}
}
}
}
I'll be glad to any help!
Edit: added code of the form for clarification
You can try the following steps to solve the problem about question marks in the datagirdview.
First, you could create the following table in your database.
CREATE TABLE [dbo].[Patient] (
[Id] INT NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Age] INT NOT NULL,
[Address] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Second, Please try the following code to use SqlParameters to insert data to database.
SqlConnection conn = new SqlConnection(#"CONNSTR");
void populate()
{
conn.Open();
string query = "select * from Patient";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
populate();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtId.Text == "" || txtName.Text == "" || txtAge.Text == "" || txtAddress.Text == "" )
MessageBox.Show("Пустые поля не принимаются!");
else
{
conn.Open();
string query = "insert into Patient(Id,Name,Age,Address)values(#Id,#Name,#Age,#Address)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#Id",Convert.ToInt32(txtId.Text));
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Age", Convert.ToInt32(txtAge.Text));
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Запись успешно добавлена!");
conn.Close();
populate();
}
}
Result:

Update datagridview from other form in C#

To make it short, I have try solutions from other post but I cannot make it work. I am new to programming and I have been given a task from my work to make a software.
I have created two forms, in which first form is called AddNewUser and the other is called RegistrationPopOut where the latter form will pop out if user clicked Register on AddNewUser form.
I want the datagridview in AddNewUser automatically updated itself if "save" is clicked on RegistrationPopOut
Here is the code for AddNewUser:
private void Register_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || comboBox1.Text == "" || comboBox2.Text == "" || comboBox3.Text == "")
{
MessageBox.Show("Please fill in every fields");
}
else
{
int i = 0;
SqlCommand cmd = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
cmd.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted.
cmd.CommandText = "select * from registration where username='" + textBox3.Text + "' or idno='" + textBox2.Text + "'";
//cmd.CommandText = "select * from registration where username='" + textBox3.Text + "'";
cmd.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0) //If ok nada masalah register
{
SqlCommand cmd1 = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
cmd1.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted.
cmd1.CommandText = "insert into registration values('" + textBox3.Text + "','" + textBox4.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "','" + comboBox3.Text + "')";
cmd1.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; comboBox1.Text = ""; comboBox2.Text = ""; comboBox3.Text = "";
display();
MessageBox.Show("Successfully registered");
}
else //if ada masalah register
{
MessageBox.Show("User already registered");
}
}
}
private void display()
{
SqlCommand cmd = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
cmd.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted.
cmd.CommandText = "select IDNO as 'Employee ID',Username,Name as 'Full Name',Istana,Position,Area from registration";
//cmd.CommandText = "select * from registration where username='" + textBox3.Text + "'";
cmd.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void AddNewUser_Load(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) //apa maksudnya?
{
con.Close();
}
con.Open();
display();
}
private void button2_Click(object sender, EventArgs e)
{
Employees.RegistrationPopOut RegPO = new Employees.RegistrationPopOut();
RegPO.Show();
display();
}
Here is the code for RegisterPopOut
private void BtnRegister_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || comboBox1.Text == "" || comboBox2.Text == "" || comboBox3.Text == "")
{
MessageBox.Show("Please fill in every fields");
}
else
{
int i = 0;
SqlCommand cmd = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
cmd.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted.
cmd.CommandText = "select * from registration where username='" + textBox3.Text + "' or idno='" + textBox2.Text + "'";
//cmd.CommandText = "select * from registration where username='" + textBox3.Text + "'";
cmd.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0) //If ok nada masalah register
{
SqlCommand cmd1 = con.CreateCommand(); //Creates and returns a SqlCommand object associated with the SqlConnection.
cmd1.CommandType = CommandType.Text; //CommandType = Specifies how a command string is interpreted.
cmd1.CommandText = "insert into registration values('" + textBox3.Text + "','" + textBox4.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "','" + comboBox3.Text + "')";
cmd1.ExecuteNonQuery(); //used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; comboBox1.Text = ""; comboBox2.Text = ""; comboBox3.Text = "";
MessageBox.Show("Successfully registered");
}
else //if ada masalah register
{
MessageBox.Show("User already registered");
}
}
}
I put display(); in AddNewUser so that it refreshes, but i didnt work.
Thank you so much!
2 simple way to do this:
1 - just read it again from SQL - very good way if few persons can change it at the same time
2 - databinding - better way with big and quite stable table.
Don't use con.open on form load!. Use it before command and close after execute.
Or even better way is using(SqlConnection connection = new SqlConnection(connectionString))
Prepere some metod for reading from SQL with command as argument(and maybe some DataTable for working with readed data), instead of writing it 3 times. And read about how should app like this look from behind.
The way you're calling RegisterPopOut from the first form is with Show(), which lets you click on the form behind, essentially not freezing it. If you don't need this feature, try this:
RegisterPopOut regPopOut = new RegisterPopOut();
regPopOut.ShowDialog();
This pauses the form and doesn't resume until the newly created form is closed using this.Close(). After the new form is closed, you should safely be able to call display() and the gridview will update
So try changing this:
private void button2_Click(object sender, EventArgs e)
{
Employees.RegistrationPopOut RegPO = new Employees.RegistrationPopOut();
RegPO.Show();
display();
}
to this:
private void button2_Click(object sender, EventArgs e)
{
Employees.RegistrationPopOut RegPO = new Employees.RegistrationPopOut();
regPopOut.ShowDialog();
display();
}

Trouble in C# inventory system update button

I have a problem in the form of my inventory system. Well it worked perfectly when one textbox was involved. But when there are 2 or more textbox involve it shows errors specifically: Truncated incorrect DOUBLE value: 'Knooks and Cranies'.
(Knooks and Cranies is an example of a supplier i inputted.)
I don't really know what's wrong because this is the 1st time I've encountered this error.
here's my code:
namespace SupplyRequestAndInventoryManagementSystem
{
public partial class DI_Assets : Form
{
connection con = new connection();
MySqlCommand cmd;
MySqlDataReader reader;
public DI_Assets()
{
InitializeComponent();
}
//load data from database
private void DI_Assets_Load(object sender, EventArgs e)
{
loadDepartment();
}
//checker
private void ListDelivery_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListDelivery.SelectedItems.Count > 0)
{
ListViewItem itm = ListDelivery.SelectedItems[0];
lblAssetIDChecker.Text = itm.SubItems[4].Text;
}
}
//load data from supplier
private void btnSearch_Click(object sender, EventArgs e)
{
loadtbl();
}
//add button
private void btnAdd_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to add new Delivery Information?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" || txtProdName.Text == "" || txtProdBrand.Text == "" || txtQty.Text == "" || DTPReceived.Text == "")
{
MessageBox.Show("Don't leave blanks!");
}
else
{
con.Close();
cmd = new MySqlCommand("Select * from deliver_mat where Del_MSupplier ='" + SuppNameCombo.Text + "' and Del_MName='" + txtProdName.Text + "' and Del_MBrand ='" + txtProdBrand.Text + "' and Del_MQty= '" + txtQty.Text + "' and Del_MReceived='" + DTPReceived.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
MessageBox.Show("Delivery Information already exist, sepcify a new one!");
}
else
{
addSection();
MessageBox.Show("Delivery Information successfully added!");
loadtbl();
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
}
else
{
MessageBox.Show("Adding new Delivery Information has been cancelled!");
}
}
//update button
private void btnUpdate_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to update the section?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" && txtProdName.Text == "" && txtProdBrand.Text == "" && txtQty.Text == "" && DTPReceived.Text == "")
{
MessageBox.Show("Please choose section to be updated!");
}
else
{
updateSection();
MessageBox.Show("Section has been successfully updated!");
loadtbl();
SuppNameCombo.Text = "";
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
else
{
MessageBox.Show("Updating section has been cancelled!");
}
}
//----------------------------------------------------------------------------------------------
//Retrieving Data from DB to listview
void loadtbl()
{
con.Close();
DataTable table = new DataTable();
cmd = new MySqlCommand("Select * from deliver_assets where Del_ASupplier = '" + SuppNameCombo.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
ListDelivery.Items.Clear();
while (reader.Read())
{
ListViewItem item = new ListViewItem(reader["Del_AName"].ToString());
item.SubItems.Add(reader["Del_ABrand"].ToString());
item.SubItems.Add(reader["Del_AReceived"].ToString());
item.SubItems.Add(reader["Del_AQty"].ToString());
item.SubItems.Add(reader["Del_aID"].ToString());
item.SubItems.Add(reader["Del_ASupplier"].ToString());
ListDelivery.Items.Add(item);
}
}
//Load Data to combo box
void loadDepartment()
{
con.Close();
DataTable table5 = new DataTable();
cmd = new MySqlCommand("Select Supp_Name from supply", con.con);
con.Open();
reader = cmd.ExecuteReader();
table5.Load(reader);
foreach (DataRow row in table5.Rows)
{
SuppNameCombo.Items.Add(row["Supp_Name"]);
}
}
//add function
void addSection()
{
con.Close();
cmd = new MySqlCommand("insert into deliver_assets(Del_AName, Del_ABrand, Del_AReceived, Del_AQty, Del_Asupplier) values('" + txtProdName.Text + "', '" + txtProdBrand.Text + "', '" + DTPReceived.Text + "', '" + txtQty.Text + "', '" + SuppNameCombo.Text + "')", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
//update function
void updateSection()
{
con.Close();
cmd = new MySqlCommand("update deliver_assets set Del_ASupplier ='" + SuppNameCombo.Text + "' and Del_AName ='" + txtProdName.Text + "' and Del_ABrand ='" + txtProdBrand.Text + "' and Del_AQty ='" + txtQty.Text + "' and Del_AReceived ='" + DTPReceived.Text + "' where Del_aID ='" + lblAssetIDChecker.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
}
}
Your code contains many errors that should be avoided in handling a database task:
Use of global variables for disposable object (in particular a
MySqlConnection)
No use of parameters
Incorrect syntax for the Update statement
Use of incorrect methods to Execute insert/update queries
Trying to use a do-it-all method to establish a connection (related
to first)
Thinking that a column with a specific datatype will happily accept a string as its value
To just give an example I will try to rewrite the Update code
//update function
void updateSection()
{
string cmdText = #"update deliver_assets
set Del_ASupplier =#sup.
Del_AName = #name,
Del_ABrand = #brand
Del_AQty = #qty
Del_AReceived = #recv
where Del_aID = #id";
using(MySqlConnection con = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, con))
{
cmd.Parameters.Add("#sup", MySqlDbType.VarChar).Value = SuppNameCombo.Text;
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = txtProdName.Text;
cmd.Parameters.Add("#brand", MySqlDbType.VarChar).Value = txtProdBrand.Text;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = Convert.ToDouble(txtQty.Text);
cmd.Parameters.Add("#recv", MySqlDbType.VarChar).Value = DTPReceived.Text;
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = Convert.ToInt32(lblAssetIDChecker.Text);
con.Open();
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowUpdated > 0)
MessageBox.Show("Record updated");
}
}
Note that I can't be sure about the correct datatype of your columns. You should create the parameter with the DataType compatible for your column changing the MySqlDbType values shown in the example above.

Error in displaying MS Access Database in C#

I think I'm know here as a person who doesn't include a lot of details which I'm sorry about so this time I'll try to be more informative with my problem.
Note: If you're asking why I'm not using exception handle it's because I wanted to work with the codes before handling the exceptions.
As of recent we were taught using MS Access to create a basic databases. So my problem is this. Using this code to display my Database to my listView:
private void Form1_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source =AssetManagement.accdb");//accessItems is the database file
System.Data.OleDb.OleDbDataAdapter adpt = new System.Data.OleDb.OleDbDataAdapter("select * from tbl_Assets", con);
adpt.Fill(ds);
DataTable table = ds.Tables[0];
foreach (DataRow row in table.Rows)
{
lstViewListOfRooms.Items.Add(row[1].ToString()).SubItems.Add(row[2].ToString());
for (int i = 0; i < lstViewListOfRooms.Items.Count; i++)
{
lstViewListOfRooms.Items[i].SubItems.Add(row[3].ToString());
lstViewListOfRooms.Items[i].SubItems.Add(row[4].ToString());
}
}
and this for adding new items for my database from a different form:
private void btnSaveAddAsset_Click(object sender, EventArgs e)
{
if (txtAddFloor.Text == "" || txtAddRoom.Text == "" || string.IsNullOrWhiteSpace(txtAddFloor.Text) == true || string.IsNullOrWhiteSpace(txtAddRoom.Text) == true)
{
MessageBox.Show("Please enter valid information", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
else
{
ths.lstViewListOfRooms.Items.Add(txtAddFloor.Text).SubItems.Add(txtAddRoom.Text);
for (int i = 0; i < ths.lstViewListOfRooms.Items.Count; i++)
{
String date = "dd/MM/yyyy - HH:mm:ss";
ths.lstViewListOfRooms.Items[i].SubItems.Add(txtAddDescriptionDetail.Text);
ths.lstViewListOfRooms.Items[i].SubItems.Add(DateTime.Now.ToString(date));
con = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source =AssetManagement.accdb");
Ds = new DataSet();
string query = "INSERT INTO tbl_Assets(asset_floor, asset_room, asset_description, asset_createdOn)" + " VALUES (" + txtAddFloor.Text + "," + txtAddRoom.Text + ", '" + txtAddDescriptionDetail.Text + "' , '" + DateTime.Now.ToString(date) + "'" + ") ";
con.Open();
Da = new OleDbDataAdapter(query, con);
Da.Fill(Ds, "tbl_Assets");
con.Close();
this.Close();
}
}
}
The problem: Each time I add an item it doesn't just add one but more, every time I add it multiples even more and more. As you can see in this screenshot:
Each time you save, you are adding again every existing room because of this code: for (int i = 0; i < ths.lstViewListOfRooms.Items.Count; i++)
You should insert only new ones and update (if needed) the existing ones. This code will do this:
private void btnSaveAddAsset_Click(object sender, EventArgs e)
{
if (txtAddFloor.Text == "" || txtAddRoom.Text == "" || string.IsNullOrWhiteSpace(txtAddFloor.Text) == true || string.IsNullOrWhiteSpace(txtAddRoom.Text) == true)
{
MessageBox.Show("Please enter valid information", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
else
{
ths.lstViewListOfRooms.Items.Add(txtAddFloor.Text).SubItems.Add(txtAddRoom.Text);
String date = "dd/MM/yyyy - HH:mm:ss";
ths.lstViewListOfRooms.Items[lstViewListOfRooms.Items.Count - 1].SubItems.Add(txtAddDescriptionDetail.Text);
ths.lstViewListOfRooms.Items[lstViewListOfRooms.Items.Count - 1].SubItems.Add(DateTime.Now.ToString(date));
con = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source =AssetManagement.accdb");
Ds = new DataSet();
string query = "INSERT INTO tbl_Assets(asset_floor, asset_room, asset_description, asset_createdOn)" + " VALUES (" + txtAddFloor.Text + "," + txtAddRoom.Text + ", '" + txtAddDescriptionDetail.Text + "' , '" + DateTime.Now.ToString(date) + "'" + ") ";
con.Open();
Da = new OleDbDataAdapter(query, con);
Da.Fill(Ds, "tbl_Assets");
con.Close();
this.Close();
}
}

Local database not refreshing after updating data from C#

I'm working with a local database, and it works well, the whole app. The problem is that I'm facing with some annoying things. If I update, or add new data to my local database, I have to close the whole app and start it again so I can see the new data I have entered. Why is it not refreshing and how can I solve it?
Here is how I add data:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label5.Text = "1";
}
else
{
label5.Text = "0";
}
if (radioButton2.Checked)
{
label5.Text = "2";
}
if (textBox1.Text.Length == 0)
{
textBox1.Text = "Fara";
}
if (textBox2.Text.Length == 0)
{
textBox2.Text = "0";
}
if (textBox3.Text.Length == 0)
{
textBox3.Text = "0";
}
if (numeTextBox.TextLength != 0 && prenumeTextBox.TextLength != 0)
{
var connString = (#"Data Source=" + Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\Angajati.sdf");
//var connString = #"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
using (var conn = new SqlCeConnection(connString))
{
try
{
//deschide conectiunea in db
conn.Open();
//creaza comanda in SQL Server CE
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
cmd.CommandText = "INSERT INTO info(Nume, Prenume, Data, Proiect, Schimburi, Poza, Acord, Baza) VALUES('" + numeTextBox.Text.Trim() + "', '" + prenumeTextBox.Text.Trim() + "', '" + dateTimePicker1.Value.ToShortDateString() + "', '" + textBox1.Text.Trim() + "', " + label5.Text + " , #Poza, " + textBox2.Text + ", " + textBox3.Text + ");";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Salvat cu succes!");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
numeTextBox.Clear();
prenumeTextBox.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Trebuie sa completezi campurile inainte de a salva!");
}
}
Here is how I update it:
private void button1_Click_1(object sender, EventArgs e)
{
//var connString = (#"Data Source= |DataDirectory|\Angajati.sdf");
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
var query = "UPDATE info SET Nume='" + textBox5.Text + "' , Prenume='" + textBox4.Text + "' , Data='" + dateTimePicker1.Value.ToShortDateString() + "', Proiect='" + textBox1.Text + "', Schimburi='" + label10.Text + "', Poza=#Poza, Acord='" + textBox2.Text + "', Baza='" + textBox3.Text + "' WHERE Nume='" + textBox5.Text + "' AND Prenume='" + textBox4.Text + "'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Here is how I search data:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length != 0)
{
var numePrenume = textBox1.Text.Trim().Split(' ');
if (numePrenume.Count() > 1)
{
var nume = numePrenume[0];
var prenume = numePrenume[1];
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT COUNT(*) FROM info WHERE Nume='" + nume + "' AND Prenume='" + prenume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
//checks if there's the searched record is in the db.
int infoCount = (int)command.ExecuteScalar();
if (infoCount > 0)
{
Info form = new Info(nume, prenume);
form.Show();
}
else
{
MessageBox.Show("Nu exista un angajat cu acest nume");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Nu ai introdus prenumele");
}
}
else
{
MessageBox.Show("Nu ai introdus nici un nume!");
}
}
I have solved this problem by changing the path to the db, it was something wrong at it, and by creating a refresh function for my gridView called after the insert. Bellow is the code for the solution:
Getting the path like this now:
string startPath = Application.StartupPath;
var filepath = startPath + "\\" + "Grupe.sdf";
var connString = (#"Data Source=" + filepath +"");
The refresh function:
public void refresh()
{
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM copii";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}

Categories