I have a problem in displaying the data in crystal report using left join. When i use "where no_barang = 2" in Phpmyadmin is working. But in crystalreport not working (the data is duplicate, and showing all data).
table "barang"
no_barang | nama_barang | harga_barang
1 | sepatu | 25000
2 | baju | 47000
table "pelanggan"
no_pelanggan | nama_pelanggan
1 | Sugeng Agung Suganda
2 | Babay Azifahmi
table "pembelian"
no_order | no_pelanggan | no_barang | jumlah
1 | 1 | 2 | 2
2 | 2 | 1 | 1
This my code in crystalreport
MySqlParameter p;
MySqlConnection conn = new MySqlConnection("database=cs_reportmultitables;server=localhost;uid=root;pwd=");
public View(string sTitle)
{
InitializeComponent();
try
{
DataSet ds = new DataSet();
string query;
p = new MySqlParameter("#no_order", MySqlDbType.String);
p.Value = sTitle;
query = "SELECT pembelian.no_order, pelanggan.nama_pelanggan, barang.nama_barang, barang.harga_barang, pembelian.jumlah FROM pembelian LEFT JOIN pelanggan ON pembelian.no_pelanggan = pelanggan.no_pelanggan LEFT JOIN barang ON pembelian.no_barang = barang.no_barang WHERE no_order=#no_order";
MySqlDataAdapter dscmd = new MySqlDataAdapter(query, conn);
dscmd.SelectCommand.Parameters.Add(p);
dscmd.Fill(ds);
RPT cryds = new RPT();
cryds.SetDataSource(ds.Tables[0]);
crystalReportViewer1.ReportSource = cryds;
crystalReportViewer1.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
conn.Close();
}
Trying to display number 2 and my output was this:
no_order | nama_pelanggan | nama_barang | harga_barang | jumlah
1 | Sugeng Agung Suganda | sepatu | 25000 | 2
2 | Babay Azifahmi | sepatu | 25000 | 1
It duplicate in "nama_barang" and "harga_barang", should display data like this:
2 | Babay Azifahmi | sepatu | 25000 | 1
Please help me if anyone know?
Related
I have following table in my PostgreSQL database:
Table "public.ads"
Column | Type | Collation | Nullable | Default
----------------------+-----------------------------+-----------+----------+-----------------------------------
idad | integer | | not null | nextval('ads_idad_seq'::regclass)
uidowner | integer | | |
month | integer | | |
year | integer | | |
mileage | integer | | |
idmake | integer | | |
idmodel | integer | | |
idmotor | integer | | |
idbodytype | integer | | |
description | text | | |
createdat | timestamp without time zone | | not null |
optionalequipmentids | character varying[] | | |
photos | character varying[] | | |
price | integer | | |
generaldata | jsonb | | |
vehicledata | jsonb | | |
engineenvironment | jsonb | | |
conditionmaintenance | jsonb | | |
idfueltype | integer | | |
Indexes:
"ads_pk" PRIMARY KEY, btree (idad)
Foreign-key constraints:
"ads_idbodytype_fkey" FOREIGN KEY (idbodytype) REFERENCES bodytype(idbodytype) ON UPDATE CASCADE
"ads_idfueltype_fkey" FOREIGN KEY (idfueltype) REFERENCES fueltype(idfueltype) ON UPDATE CASCADE
"ads_idmake_fkey" FOREIGN KEY (idmake) REFERENCES make(idmake) ON UPDATE CASCADE
"ads_idmodel_fkey" FOREIGN KEY (idmodel) REFERENCES model(idmodel) ON UPDATE CASCADE
"ads_idmotor_fkey" FOREIGN KEY (idmotor) REFERENCES motor(idmotor) ON UPDATE CASCADE
I created method for filling DataGridView with data from table above, and here is the code part:
private void FillDataGridAds()
{
if (!connected) return;
string cmdString = string.Empty;
try
{
cmdString = "SELECT * FROM ads";
NpgsqlCommand command = new NpgsqlCommand(cmdString, conn);
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridAds.DataSource = dt.DefaultView;
}
catch (NpgsqlException ex)
{
textBox1.AppendText("PostgreSQL exception: " + ex.Message + Environment.NewLine);
}
catch (Exception ex)
{
textBox1.AppendText("Exception ex: " + ex.Message + Environment.NewLine);
}
}
Designer part of code of my dataGridAds
//
// dataGridAds
//
this.dataGridAds.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridAds.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridAds.ContextMenuStrip = this.contextMenuStrip1;
this.dataGridAds.Location = new System.Drawing.Point(9, 49);
this.dataGridAds.Name = "dataGridAds";
this.dataGridAds.RowHeadersWidth = 51;
this.dataGridAds.RowTemplate.Height = 29;
this.dataGridAds.Size = new System.Drawing.Size(1326, 549);
this.dataGridAds.TabIndex = 0;
this.dataGridAds.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridAds_CellEndEdit);
//
Problem:
For some reason when method for filling dataGridAds is triggered, dataGridAds is displaying all columns except optionalequipmentids and photos, so does anybody know where can be a problem, I was trying to figured out where problem might be, but unsuccessfully, have same issue with another tables in my appplication and want to fix as soon as possible, thank you all in advance.
The columns are both data-type character varying[] I assume that the columns in other tables with the same problem are the same data-type.
You could try using CAST. Does the following script with a nomnative SELECT with CASE for the problem columns work?
If CAST( ... AS VARCHAR(1000)) doesn't work you could also try
CAST( ... AS VARCHAR)
private void FillDataGridAds()
{
if (!connected) return;
string cmdString = string.Empty;
try
{
cmdString =
"SELECT
idad ,
uidowner ,
month ,
year ,
mileage ,
idmake ,
idmodel ,
idmotor ,
idbodytype ,
description ,
createdat ,
CAST( optionalequipmentids AS VARCHAR(1000)),
CAST( photos AS VARCHAR(1000)),
price ,
generaldata ,
vehicledata ,
engineenvironment ,
conditionmaintenance ,
idfueltype FROM ads";
NpgsqlCommand command = new NpgsqlCommand(cmdString, conn);
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridAds.DataSource = dt.DefaultView;
}
catch (NpgsqlException ex)
{
textBox1.AppendText("PostgreSQL exception: " + ex.Message + Environment.NewLine);
}
catch (Exception ex)
{
textBox1.AppendText("Exception ex: " + ex.Message + Environment.NewLine);
}
}
I have this stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE ClientDelete
#clientid uniqueidentifier
AS
BEGIN
SET NOCOUNT ON;
UPDATE Clients SET enabled=1,editDate=GETUTCDATE() WHERE clientid=#clientid
END
Using this feature file:
Feature: ClientDelete
Scenario: Client Delete
Given a clean database
Given the following Clients table
| clientid | name | url | enabled | lastChangedBy | createDate | editDate |
| 1 | Client1 | https://test | true | test | 2000-01-01 | 2000-01-01 |
| 2 | Client2 | https://test | true | test | 2000-01-01 | 2000-01-01 |
When the "ClientDelete" stored procedure is run with the following parameters
| name | value |
| clientid | 11 |
Then the following is returned
| clientid | name | url | enabled | lastChangedBy | createDate | editDate |
| 1 | Client1 | https://test | false | test | 2000-01-01 | 2000-01-01 |
| 2 | Client2 | https://test | true | test | 2000-01-01 | 2000-01-01 |
C# Code:
[When(#"the ""(.*)"" stored procedure is run with the following parameters")]
public void WhenTheStoredProcedureIsRunWithTheFollowingParameters(string procName, Table table)
{
using (var con = CreateDBConnection())
{
using (var cmd = con.CreateCommand())
{
cmd.CommandText = procName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var row in table.Rows)
{
var param = cmd.CreateParameter();
param.ParameterName = row.Values.First();
if (param.ParameterName == "clientids")
{
param.SqlDbType = SqlDbType.Structured;
param.Value = new List<SqlDataRecord>()
{
ToSqlDataRecord(new Guid(row.Values.Last()))
};
}
else if (param.ParameterName == "docTypes")
{
param.SqlDbType = SqlDbType.Structured;
if (row.Values.Last() != "NULL")
{
param.Value = new List<SqlDataRecord>()
{
ToSqlDataRecord(row.Values.Last())
};
}
}
else if (row.Values.Last() != "NULL")
param.Value = row.Values.Last();
else
param.Value = DBNull.Value;
cmd.Parameters.Add(param);
}
var results = new DataTable();
using (var adapter = new SqlDataAdapter((SqlCommand)cmd))
{
adapter.Fill(results);
}
_context.Add("Results", results);
}
}
}
[Then(#"the following is returned")]
public void ThenTheFollowingIsReturned(Table table)
{
var results = _context.Get<DataTable>("Results");
Assert.AreEqual(table.Rows.Count, results.Rows.Count);
for (int i = 0; i < results.Rows.Count; i++)
{
var expectedRow = table.Rows[i];
var actualRow = results.Rows[i];
for (int j = 0; j < table.Header.Count; j++)
{
var name = table.Header.ElementAt(j);
var type = actualRow[name].GetType();
object expectedValue = expectedRow[name];
if (expectedValue.ToString().IsNullText())
expectedValue = null;
else if (type != typeof(DBNull))
expectedValue = TypeDescriptor.GetConverter(type).ConvertFromInvariantString(expectedRow[name]);
var actualValue = Convert.IsDBNull(actualRow[name]) ? null : actualRow[name];
Assert.AreEqual(expectedValue, actualValue, name);
}
}
}
#Then is not working as it's not returning anything from stored procedure so I want to check if the value updated or exists or not.
I have this too when and then used for multiple stored procedure which returns row data and is working fine, but does not work with add, delete, update.
Note: I need to do without adding output parameter to stored procedure.
After the update in your stored procedure add:
SELECT ##ROWCOUNT AS Result
This will return the number of rows affected by the previous update statement. You can then check in your C# code if the Result is > 0.
##ROWCOUNT documentation:
https://learn.microsoft.com/en-us/sql/t-sql/functions/rowcount-transact-sql?view=sql-server-ver15
You need to query the clients table again in your Then step. The DeleteClient stored procedure does not return anything, nor does it fill an output variable. Your only recourse is the query the clients table again in Then the following is returned. You can use the Table extension method CompareToSet(...) instead of doing the assertions manually yourself.
My SQL query is:
GridView1.DataSource = GetData();
GridView1.DataBind();
DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["OfficeConnection"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Consulting ", con))
{
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);
}
}
return dt;
}
I have a table with a few columns and what I am trying to achieve is to display the data in a GridView. At the moment the data is displayed in my GridView but I would like to replace text in the columns and then display in the gridview
So for example this is my table:
| DisplayName | $_License
+-------------+------------------------
| User 1 | TestLicense:License1 |
| User 2 | TestLicense:License2 |
So in my Gridview I would to display:
| Display Name | License Type |
+--------------+------------------------+
| User 1 | License1 |
| User 2 | License2 |
Note that theDisplay Name has a space and the $_License is changed to License Type and the row is changed from TestLicense:License1 to License1
Any help will be greatly appreciated.
Use this query:
"SELECT DisplayName 'Display Name', Replace($_License,'TestLicense:', '') 'License Type' Name FROM Consulting "
Modify your select query as per required result:
SELECT DisplayName AS 'Display Name' , RIGHT($_License, LEN($_License) - 11) AS 'License Type' FROM Consulting;
I have one database and I want to get last value of column, and each time value will be updated after insertion
here is sample database,
ID | Customer_Name |new_Total | Total
--------------------------------------
1 | Mahesh | 100 | 200
2 | Mahesh | 400 | 600 (200+400)
3 | mahesh | 100 | 700 (600+100)
If i am getting you right you need to get last value of column i assume Total column.Here is you can read last value from database.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
{
SqlCommand cmd = new SqlCommand("select Top 1 Total from tablename order by total desc", con);
SqlDataReader rdr;
con.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int total;
int.TryParse(rdr["Total"].ToString(), out total);
}
}
You will get value in total variable and you can use it.
I am using C#(asp.net). I have two tables(data and details) in a same database.
Table "data"
id | chap | unit |
----------------
1| chap1|unit1 |
2| chap2|unit2 |
3| chap3|unit3 |
Table "details"
id| code| num |
----------------
1|abc |2 |
2|efg |3 |
3|hij |1 |
Now I want to fetch a value from "num" where code="efg" (in table "details"). And use the same value (3) to fetch data from table "data" by id. I am using this code.
OleDbConnection conn = new OleDbConnection(*** ...... *****);
OleDbCommand cmd;
OleDbDataReader reader;
String query = String.Format("select num from details where code="efg");
cmd = new OleDbCommand(query, conn);
reader = cmd.ExecuteReader();
int num = int.Parse(reader.GetValue(0).ToString());
query = String.Format("select chap from data where id={0}",num);
cmd = new OleDbCommand("select lesson from data where id=3", conn);
reader = cmd.ExecuteReader();
Label1.Text = reader.GetValue(0).ToString();
But it shows error. It shows "No data exists for the row/column."
You can use
SELECT d.chap, d.unit
FROM data d INNER JOIN details de
ON d.id = de.num
WHERE de.code = 'efg'
or
SELECT d.chap, d.unit
FROM data d INNER JOIN details de
ON d.id = de.num
AND de.code = 'efg'
More: if you're using SQL-Server, use SqlConnection in place of OleDbConnection.
More: don't format your query joining strings, numbers, dates and so on; use SqlParameter so you don't have to worry about types and formatting!!
Or you can use a subquery
SELECT * FROM data INNER JOIN
(SELECT num FROM details WHERE code='efg') det
ON data.id = det.num