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
Related
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();
}
}
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();
I am trying to build datagridview that consist from two part
one part came from database and the other part is collected information about files on local hard disk and show it as one part but I am getting error message that says
Rows cannot be programmatically added to the datagridview rows
collection when the control is data-bound
Note:
knowing That data within datagridview will be used later to modifies data on oracle database
I had upload imag for more understanding the first two column are from database
private void ListFileToBePatched()
{
try
{
string connstr = "data source=orcl;user id=user;password=pwd";
string cmdstr = #"SELECT OFFICE_CODE as ""Office Code"",
IP_ADDRESS as ""Office IP""
FROM table";
string[] array = Directory.GetFiles(SBankfilespath, "*.txt");
using (OracleConnection conn = new OracleConnection(connstr))
using (OracleCommand cmd = new OracleCommand(cmdstr, conn))
{
conn.Open();
OracleTransaction trans = conn.BeginTransaction();
OracleDataReader OraReader = cmd.ExecuteReader();
DataTable dt = new DataTable();
DataColumn OfficeCodecolumn = new DataColumn();
OfficeCodecolumn.DataType = System.Type.GetType("System.String");
OfficeCodecolumn.ColumnName = "Office Code";
dt.Columns.Add(OfficeCodecolumn);
DataColumn OfficeIPcolumn = new DataColumn();
OfficeIPcolumn.DataType = System.Type.GetType("System.String");
OfficeIPcolumn.ColumnName = "Office IP Address";
dt.Columns.Add(OfficeIPcolumn);
DataColumn FileNamecolumn = new DataColumn();
FileNamecolumn.DataType = System.Type.GetType("System.String");
FileNamecolumn.ColumnName = "File Name";
dt.Columns.Add(FileNamecolumn);
DataColumn FullFilePathcolumn = new DataColumn();
FullFilePathcolumn.DataType = System.Type.GetType("System.String");
FullFilePathcolumn.ColumnName = "Full File Path";
dt.Columns.Add(FullFilePathcolumn);
DataColumn DateCreatedcolumn = new DataColumn();
DateCreatedcolumn.DataType = System.Type.GetType("System.String");
DateCreatedcolumn.ColumnName = "Date Created";
dt.Columns.Add(DateCreatedcolumn);
DataColumn Datemodifiedcolumn = new DataColumn();
Datemodifiedcolumn.DataType = System.Type.GetType("System.String");
Datemodifiedcolumn.ColumnName = "Date modified";
dt.Columns.Add(Datemodifiedcolumn);
foreach (string FullFilePath in array)
{
DataRow row = dt.NewRow();
row[2] = Path.GetFileName(FullFilePath);
row[3] = FullFilePath;
row[4] = File.GetCreationTime(FullFilePath);
row[5] = File.GetLastWriteTime(FullFilePath);
dt.Rows.Add(row);
}
dt.Load(OraReader);
DataView view = new DataView(dt);
DGV_PatchStatus.DataSource = view;
}
FileCount.Text = "File Count ( " + DGV_PatchStatus.Rows.Count.ToString() + " )";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You could use the DataTable.NewRow method to add the row to your DataTable.
foreach (string FullFilePath in array)
{
DataRow r = DT.NewRow();
r[0] = Path.GetFileName(FullFilePath);
r[1] = FullFilePath;
r[2] = File.GetCreationTime(FullFilePath);
r[3] = File.GetLastWriteTime(FullFilePath);
}
Then simply bind the DT again as DataSource
DGV_PatchStatus.DataSource = DT;
EDIT:
what I really need is that for each office has list of files
If you have several files for each office-row you should have a look on this Tree-View-Tutorial this might really be helpful to achieve your desired results.
Here is also a Nested-DataGrid-Example that might also be of help. Good luck.
Make Class For your data after reading from db assign data to that object and put object into List afterwards initialize DGV_PatchStatus.DataSource to that list, when you need to add new row simply add data object to that list and re initialize DGV_PatchStatus DataSource
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;
Q:
I want to rename my data table column names .
I tried this :
dt.Columns[8].ColumnName = "regnum";
dt.AcceptChanges();
but my data is lost after that !!
dt.Columns[8].ColumnName = "regnum";
This just binds your Columns[8] to the non-existing "regnum" column in the Db.
If you want to rename the actuals Db column, execute an SQL script.
But my guess is you actually want to change the Caption:
dt.Columns[8].Caption = "regnum";
Following is the example:
DataTable Dt = new DataTable();
DataColumn Dc = new DataColumn("Name");
DataColumn Dc1 = new DataColumn("ID");
Dt.Columns.Add(Dc);
Dt.Columns.Add(Dc1);
DataRow dr = Dt.NewRow();
dr["name"] = "1";
dr["ID"] = "111";
Dt.Rows.Add(dr);
dr = Dt.NewRow();
dr["name"] = "2";
dr["ID"] = "11112";
Dt.Rows.Add(dr);
Dt.Columns[0].ColumnName = "ddsxsd";
Dt.AcceptChanges();
I did not find any data loss!!!!!!!! Because it will merely change the column name.
EDIT
You can also bring your desired column names from your Stored Procedures.
Try this:
dataTable.Columns["ExistingColumnName"].ColumnName = "regnum";
Also may this code serve someone!
I have a realize that this is the easiest way just like #Henk said:
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
da.SelectCommand = cmd;
da.Fill(dt);
dt.Columns[0].ColumnName = "Item NO";
dt.Columns[1].ColumnName = "LocalCode";
dt.Columns[2].ColumnName = "Currency";
dt.Columns[3].ColumnName = "Menu Flag";
dt.Columns[4].ColumnName = "Item Class";
dt.Columns[4].ColumnName = "Dress Sort";
return dt;
}