Error in displaying MS Access Database in C# - 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();
}
}

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:

How to: Add a result to the same database as login

My app shows a menu of a restaurant where, after logging in with an email and password from the database, the client guides you to a computer that calculates Kcal after certain dates. I would like to be able to put the result in the same database and the same data that the client used as the image.
[
This is for an application I have for a contest
private void button1_Click(object sender, EventArgs e)
{
ani = Convert.ToInt32(textBox1.Text);
cm = Convert.ToInt32(textBox2.Text);
kg = Convert.ToInt32(textBox3.Text);
s = ani + cm + kg;
if (s < 250) label_mesaj.Text = "1800";
else if (s >= 250 && s <= 275) label_mesaj.Text = "2200";
else label_mesaj.Text = "2500";
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("insert into Clienti(parola,nume,prenume,adresa,email)values('" + textBox4.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox6.Text + "')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
This is code that add to my database new clients after a registration, so i don't know how to remember that "id_clienti"
I expect that "label_mesaj" to show on the "kcal_zilnice" in the database after LogIn with the same data.
That's how I managed to solve the problem
The LogIn part that I remember the email
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter da = new SqlDataAdapter("Select count(*) from Clienti where email='" + textBox1.Text + "' and Parola='" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
client.email = textBox1.Text;
this.Hide();
Form4 ssss = new Form4();
ssss.Show();
}
else MessageBox.Show("verifica datele");
}
And in the next Form
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter da = new SqlDataAdapter();
con.Open();if (s < 250) label_mesaj.Text = "1800";
da.UpdateCommand = new SqlCommand("Update Clienti set kcal_zilnice= '" + label_mesaj.Text + "' where email= '" + Form3.client.email.ToString() + "'", con);
da.UpdateCommand.ExecuteNonQuery();
da.UpdateCommand.Dispose();
con.Close();
}

SQL Interjection Error

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;
}

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.

how to compare values of a datatable from two datatable and subtract them

I am coding in c# and I want to compare the "quantity" in "sell" datatable with "buy" datatable and if "quantity" in "buy" table is greater then I need to subtract "buy" table from "sell" and "quantity" or else just continue. Please tell how to take the value for comparision. I have made the coding as below but its showing error.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
var sql = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Sell' and scriptname = '" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var sqll = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Buy' and scriptname ='" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var da = new SqlDataAdapter(sqll, conn);
var dataTablebuy = new DataTable();
da.Fill(dataTablebuy);
var dataAdapter = new SqlDataAdapter(sql, conn);
var dataTablesell = new DataTable();
dataAdapter.Fill(dataTablesell);
foreach (DataRow row in dataTablesell.Rows)
{
foreach (DataRow rw in dataTablebuy.Rows)
{
if (rw["Quantity"] > row["Quantity"])
{
rw["Quantity"] = rw["Quantity"] - row["Quantity"];
}
else
{
break;
}
}
}
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
Response.Write("error" + sqlEx.ToString());
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
Try this:
if (double.Parse(rw["Quantity"].ToString()) > double.Parse(row["Quantity"].ToString()))
{
rw["Quantity"] = double.Parse(rw["Quantity"].ToString()) - double.Parse(row["Quantity"].ToString())
}
I just want to provide more feasible option in case you need any alternative.
I just covered your scenario in query itself. I joined tables and got data as per your need
You just get data using this query.
Please frame query for c# code
select T1.scriptname,T1.accnum,(case when (T2.Quantity>T1.Quantity) then (T2.Quantity-T1.Quantity) else T1.Quantity end) as Quantity,T1.price
from transac T1,transac T2
where
T1.transactio = 'Sell'
and
T2.transactio = 'Buy'
and
T1.scriptname = ' TextBox2.Text '
and
T1.accnum =' TextBox1.Text '
and
T2.scriptname ='TextBox2.Text'
and
T2.accnum ='TextBox1.Text'
and
T1.scriptname = T2.scriptname
and
T2.accnum = T2.accnum

Categories