Datatable columns expression - c#

I am working with an application where user can multiply quantity and price and the results appear in third column using column expression
The code i used is showed under this :
DataTable dt = new DataTable("dtList");
DataTable dataTable = new DataTable();//Created a new DataTable
DataColumn dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Decimal");
dc.ColumnName = "Price";
DataColumn dc1 = new DataColumn();
dc1.DataType = System.Type.GetType("System.Decimal");
dc1.ColumnName = "qty";
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.Decimal");
dc2.ColumnName = "Total";
dc2.Expression = "Price * qty";
dataTable.Columns.Add(dc);//Add them to the DataTable
dataTable.Columns.Add(dc1);
dataTable.Columns.Add(dc2);
object sumObject;
sumObject = dt.Compute("Sum(Total)", "");
I used this code to sum column Total, and show the result in a Text Box, but it's showing an error like this: "Cannot find column [Total]".
My question is what can i change, to make this code work, also sum automatically every time when the user change qty.
Sorry for my English and mistakes at my code I am new to WPF

Giving a fast check to your code I can see one thing.You define a DataTable called dt and then you try to compute the column "dt.Total" but you have never defined a column in you dt.
Try changing your:
sumObject = dt.Compute("Sum(Total)", "");
to
sumObject = dataTable.Compute("Sum(Total)", "");
Edit: By the way, if you do this:
dataTable = new DataTable();//Created a new DataTable
DataColumn dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Decimal");
dc.ColumnName = "Price";
DataColumn dc1 = new DataColumn();
dc1.DataType = System.Type.GetType("System.Decimal");
dc1.ColumnName = "qty";
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.Decimal");
dc2.ColumnName = "Total";
dc2.DefaultValue = 5;
dc2.Expression = "Price * qty";
dataTable.Columns.Add(dc);//Add them to the DataTable
dataTable.Columns.Add(dc1);
dataTable.Columns.Add(dc2);
Your third column already has the value "price * qty".
If you want to show the sum of all your dc Total column just use:
object sumObject = dataTable.Compute("Sum(Total)", "");
And then
yourTextbox.Text = sumObject.ToString();

Related

How to add a new data to a datagrid keeping the previously existed data there too?

I am selecting data from SQL into datagrid, the code works fine, but it is deleting the previous data from my datagrid.
My code (C# WPF SQL datagrid):
private void enter(object sender, KeyEventArgs e)
{
try
{
if (e.Key == Key.Enter)
{
SqlConnection com = new SqlConnection("Server = localhost; database = PrimaSOFT ; integrated security = true");
SqlCommand cmd = new SqlCommand("produktit", com);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Barkodi", txtBarkodi.Text);
//Created a new DataTable
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataColumn dc = new DataColumn();//Made a new DataColumn to populate above DataTable
dc.DataType = System.Type.GetType("System.String");//Defined the DataType inside, this can be [[int]] if you want.
dc.ColumnName = "Barkodi";//Gave it a name (important for the custom expression - can only be one word so use underscores if you need multiple words)
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.String");
dc2.ColumnName = "Emertimi";
DataColumn dc3 = new DataColumn();
dc3.DataType = System.Type.GetType("System.Decimal");
dc3.ColumnName = "Sasia";
DataColumn dc4 = new DataColumn();
dc4.DataType = System.Type.GetType("System.Decimal");
dc4.ColumnName = "Cmimi";
DataColumn dc5 = new DataColumn();
dc5.DataType = System.Type.GetType("System.String");
dc5.Caption = "sds";
dc5.ColumnName = "TVSH";
DataColumn dc6 = new DataColumn();
dc6.DataType = System.Type.GetType("System.String");
dc6.ColumnName = "Total";
dc6.Expression = "Cmimi * Sasia";//Multiplying the Price and Quantity DataColumns
dataTable.Columns.Add(dc);//Add them to the DataTable
dataTable.Columns.Add(dc2);
dataTable.Columns.Add(dc3);
dataTable.Columns.Add(dc4);
dataTable.Columns.Add(dc5);
dataTable.Columns.Add(dc6);
dtgartikujt.ItemsSource = dataTable.DefaultView;//Set the DataGrid ItemSource to this new generated DataTable
com.Open();//Open the SQL connection
SqlDataReader reader = cmd.ExecuteReader();//Create a SqlDataReader
while (reader.Read())//For each row that the SQL query returns do
{
DataRow dr = dataTable.NewRow();//Create new DataRow to populate the DataTable (which is currently binded to the DataGrid)
dr[0] = reader[0];//Fill DataTable column 0 current row (Product) with reader[0] (Product from sql)
dr[1] = reader[1];
dr[2] = reader[2];
dr[3] = reader[3];
dr[4] = reader[4];
dataTable.Rows.Add(dr);//Add the new created DataRow to the DataTable
}
}
}
Sum code
object sumObject;
sumObject = dataTable.Compute("Sum(Totali)",
string.Empty);
txttotali.Text = sumObject.ToString();
I am expecting a new data to be showed in datagrid without deleting previous data.
How should I approach this?
Edited: I also attached the sum code, to sum the datagrid column, and display to textbox
As I think I understand what you are doing : separate dataTable code from Sql(ADO.NET) code and run dataTable part once only. So for run CreateTable in form_load for example :
public void CreateTable()
{
DataColumn dc = new DataColumn();//Made a new DataColumn to populate above DataTable
dc.DataType = System.Type.GetType("System.String");//Defined the DataType inside, this can be [[int]] if you want.
dc.ColumnName = "Barkodi";//Gave it a name (important for the custom expression - can only be one word so use underscores if you need multiple words)
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.String");
dc2.ColumnName = "Emertimi";
DataColumn dc3 = new DataColumn();
dc3.DataType = System.Type.GetType("System.Decimal");
dc3.ColumnName = "Sasia";
DataColumn dc4 = new DataColumn();
dc4.DataType = System.Type.GetType("System.Decimal");
dc4.ColumnName = "Cmimi";
DataColumn dc5 = new DataColumn();
dc5.DataType = System.Type.GetType("System.String");
dc5.Caption = "sds";
dc5.ColumnName = "TVSH";
DataColumn dc6 = new DataColumn();
dc6.DataType = System.Type.GetType("System.String");
dc6.ColumnName = "Total";
dc6.Expression = "Cmimi * Sasia";//Multiplying the Price and Quantity DataColumns
dataTable.Columns.Add(dc);//Add them to the DataTable
dataTable.Columns.Add(dc2);
dataTable.Columns.Add(dc3);
dataTable.Columns.Add(dc4);
dataTable.Columns.Add(dc5);
dataTable.Columns.Add(dc6);
dtgartikujt.ItemsSource = dataTable.DefaultView;//Set the DataGrid ItemSource to this new generated DataTable
}
And the rest of code :
long sum=0;
private void enter(object sender, KeyEventArgs e)
{
try
{
if (e.Key == Key.Enter)
{
SqlConnection com = new SqlConnection("Server = localhost; database = PrimaSOFT ; integrated security = true");
SqlCommand cmd = new SqlCommand("produktit", com);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Barkodi", txtBarkodi.Text);
//Created a new DataTable
SqlDataAdapter da = new SqlDataAdapter(cmd);
com.Open();//Open the SQL connection
SqlDataReader reader = cmd.ExecuteReader();//Create a SqlDataReader
while (reader.Read())//For each row that the SQL query returns do
{
DataRow dr = dataTable.NewRow();//Create new DataRow to populate the DataTable (which is currently binded to the DataGrid)
dr[0] = reader[0];//Fill DataTable column 0 current row (Product) with reader[0] (Product from sql)
dr[1] = reader[1];
dr[2] = reader[2];
dr[3] = reader[3];
dr[4] = reader[4];
// sum+= Convert.ToInt64(reader[4]); // use the total index instead of 4 . or use reader["total"];
dataTable.Rows.Add(dr);//Add the new created DataRow to the DataTable
// or maybe dtgartikujt.Rows.Add(dr);
}
// textbox1.Text=sum.Tostring();
}
}

c# datagrid sql population

I am working with a small application where the user can retrieve specific data from SQL populate the datagrid with the data. The user can retrieve data from SQL Database where he write a barcode in textbox then the data he searched for will appear.
Until now i used this code
try
{
if (e.Key == Key.Enter)
{
SqlConnection con = new SqlConnection("Server = localhost;Database = Bilanc; Integrated Security = true");
SqlCommand cmd = new SqlCommand("product", con); // Using a Store Procedure.
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable("dtList");
cmd.Parameters.AddWithValue("#Barcod", txtcode.Text);
DataTable dataTable = new DataTable();//Created a new DataTable
DataColumn dc = new DataColumn();//Made a new DataColumn to populate above DataTable
dc.DataType = System.Type.GetType("System.String");//Defined the DataType inside, this can be [[int]] if you want.
dc.ColumnName = "#Barcod";//Gave it a name (important for the custom expression - can only be one word so use underscores if you need multiple words)
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.String");
dc2.ColumnName = "#Product";
DataColumn dc3 = new DataColumn();
dc3.DataType = System.Type.GetType("System.Decimal");
dc3.ColumnName = "#QTY";
DataColumn dc4 = new DataColumn();
dc4.DataType = System.Type.GetType("System.Decimal");
dc4.ColumnName = "#Price";
DataColumn dc5 = new DataColumn();
dc5.DataType = System.Type.GetType("System.String");
dc5.ColumnName = "#Tax";
DataColumn dc6 = new DataColumn();
dc6.DataType = System.Type.GetType("System.String");
dc6.ColumnName = "Total";
dc6.Expression = "#Price * #QTY";//Multiplying the Price and Quantity DataColumns
dataTable.Columns.Add(dc);//Add them to the DataTable
dataTable.Columns.Add(dc2);
dataTable.Columns.Add(dc3);
dataTable.Columns.Add(dc4);
dataTable.Columns.Add(dc5);
dataTable.Columns.Add(dc6);
dtg.ItemsSource = dataTable.DefaultView;//Set the DataGrid ItemSource to this new generated DataTable
con.Open();//Open the SQL connection
SqlDataReader reader = cmd.ExecuteReader();//Create a SqlDataReader
while (reader.Read())//For each row that the SQL query returns do
{
DataRow dr = dataTable.NewRow();//Create new DataRow to populate the DataTable (which is currently binded to the DataGrid)
dr[0] = reader[0];//Fill DataTable column 0 current row (Product) with reader[0] (Product from sql)
dr[1] = reader[1];
dr[2] = reader[2];
dr[3] = reader[3];
dr[4] = reader[4];
dataTable.Rows.Add(dr);//Add the new created DataRow to the DataTable
}
}
}
catch (Exception)
{
MessageBox.Show("The product you are searching doesn't exist ");
}
}
The code works fine, but when i got stuck is when i retrieve data from SQL the new data overwrite the previous data.
My question how i can keep the previous data
Thanks to everyone

The report has no tables (DataTable -> Crystal Report)

I'm new to crystal reporting. Is there a way to add a datatable that i made to a crystal report sa datasource?
I've used this datatable to a datagridview, is it possible to use that datatable as source for crystal report?
DataAccess datax = new DataAccess();
DataSet ds = new DataSet("dataset");
DataTable dt = new DataTable();
DataColumn property, minimum, result, maximum, remarks;
public ReportingForm(string resin_type, string resin_code, string batch_num)
{
InitializeComponent();
datax.initialize();
AnalysisReport analysis_rep = new AnalysisReport();
property = new DataColumn();
minimum = new DataColumn();
result = new DataColumn();
maximum = new DataColumn();
remarks = new DataColumn();
property.ColumnName = "Property";
minimum.ColumnName = "Minimum";
result.ColumnName = "Result";
maximum.ColumnName = "Maximum";
dt.Columns.AddRange(new DataColumn[] { property, minimum, result, maximum, remarks });
initialize_data(resin_type, resin_code, batch_num); //sets the rows
ds.Tables.Add(dt);
analysis_rep.SetDataSource(ds.Tables[0]);
crpt.ReportSource = analysis_rep;
}
in the line analysis_rep.SetDataSource(ds.Tables[0]); it throws an error that says "The report has no tables"
I also tried analysis_rep.SetDataSource(dt); where I tried setting the data source as a data table, same results.
ds.Tables.Count = 1

How to merge two datarow cells into one?

I am trying to merge two datarow cells into one. Here is my initializing code:
DataTable dt = new DataTable();
DataColumn dc;
DataRow dr;
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "Col1";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "Col2";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "Col3";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "Col4";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "Col5";
dt.Columns.Add(dc);
This is the code I have for each column in Excel:
dr = dt.NewRow();
dr["Col1"] = "";
dr["Col2"] = "Quarter 1";
dr["Col3"] = "";
dr["Col4"] = "";
dr["Col5"] = "";
dt.Rows.Add(dr);
And it will look like this:
But I want it to look like this:
Any thoughts or ideas on how I can do this? I found it to be rather hard to merge the cells.

Programatically creating DataSet and setting to DataGrid causing blank rows for the number of records that should be shown

I am working on a c# project and I am trying to create a DataSet and set the itemssource of a datagrid to the dataset.
However, when the grid loads, it shows 4 blank lines (4 records being inside the database) and none of the columns are being shown.
Below is the code for how I am calling the dataset creation function and assign it to the DataGrid.
private void loadData()
{
Classes.SoftwareManager softwareManager = new Classes.SoftwareManager();
DataSet dataSet = softwareManager.getDatasetForSoftware();
if (dataSet != null)
{
softwareGrid.AutoGenerateColumns = false;
dataSet.Tables[0].Columns.RemoveAt(0);
softwareGrid.ItemsSource = dataSet.Tables[0].DefaultView;
}
}
Below is the code that creates the dataset which is returned in the function above.
public DataSet getDatasetForSoftware()
{
DataSet ds = new DataSet();
DataTable table = new DataTable();
DataColumn idCol = new DataColumn();
DataColumn softwareCol = new DataColumn("Software Name");
DataColumn serverCol = new DataColumn("DB Server");
DataColumn userNameCol = new DataColumn("DB Username");
DataColumn passwordCol = new DataColumn("DB Password");
DataColumn portCol = new DataColumn("DB Port");
DataColumn webInstallLocationCol = new DataColumn("Web Install Location");
DataColumn softwareInstallLocationCol = new DataColumn("Software Install Location");
DataColumn startScriptNameCol = new DataColumn("Start Script Name");
DataColumn statusCol = new DataColumn("Status");
idCol.DataType = System.Type.GetType("System.Int32");
softwareCol.DataType = System.Type.GetType("System.String");
serverCol.DataType = System.Type.GetType("System.String");
userNameCol.DataType = System.Type.GetType("System.String");
passwordCol.DataType = System.Type.GetType("System.String");
portCol.DataType = System.Type.GetType("System.String");
webInstallLocationCol.DataType = System.Type.GetType("System.String");
softwareInstallLocationCol.DataType = System.Type.GetType("System.String");
startScriptNameCol.DataType = System.Type.GetType("System.String");
statusCol.DataType = System.Type.GetType("System.String");
table.Columns.Add(idCol);
table.Columns.Add(softwareCol);
table.Columns.Add(serverCol);
table.Columns.Add(userNameCol);
table.Columns.Add(passwordCol);
table.Columns.Add(portCol);
table.Columns.Add(webInstallLocationCol);
table.Columns.Add(softwareInstallLocationCol);
table.Columns.Add(startScriptNameCol);
table.Columns.Add(statusCol);
List<SoftwareDetails> softwareDetails = getSoftwareDetails();
if (softwareDetails != null)
{
foreach (SoftwareDetails software in softwareDetails)
{
DataRow dataRow = table.NewRow();
dataRow[idCol] = software.id;
dataRow[softwareCol] = software.softwareName;
dataRow[serverCol] = software.dbServer;
dataRow[userNameCol] = software.dbUsername;
dataRow[passwordCol] = software.dbPassword;
dataRow[portCol] = software.dbPort;
dataRow[webInstallLocationCol] = software.webInstallLocation;
dataRow[softwareInstallLocationCol] = software.softwareInstallLocation;
dataRow[startScriptNameCol] = software.startScriptName;
dataRow[statusCol] = software.status;
table.Rows.Add(dataRow);
}
}
ds.Tables.Add(table);
return ds;
}
Thanks for any help you can provide.
I see softwareGrid.AutoGenerateColumns = false; If your grid does not contain column definition, you should set
softwareGrid.AutoGenerateColumns = true;

Categories