I have a small problem with creating a new table in a database. I create a new table in my DataSet object, but this table is not created in the physical database. The table is created only in cache. Why?
My code:
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Projects\ConsoleApplication6\ConsoleApplication6\Data.sdf");
SqlCeDataAdapter sCEdata = new SqlCeDataAdapter("select * from [Cats]", con);
DataSet ds = new DataSet();
sCEdata.Fill(ds);
DataColumn ID = new DataColumn("ID", typeof(int));
ID.AllowDBNull = false;
ID.AutoIncrementSeed = 0;
ID.AutoIncrement = true;
ID.AutoIncrementStep = 1;
ID.ReadOnly = true;
ID.Unique = true;
DataColumn Name = new DataColumn("Name", typeof(string));
DataColumn Owner = new DataColumn("Owner", typeof(string));
DataColumn Note = new DataColumn("Note", typeof(string));
DataTable Cats2 = new DataTable("Cats2");
Cats2.Columns.AddRange(new DataColumn[]{ID, Name, Hozain, Note});
DataRow dr1 = Cats2.NewRow();
DataRow dr2 = Cats2.NewRow();
DataRow dr3 = Cats2.NewRow();
dr1["Name"] = "Pavel"; dr1["Owner"] = "Sergey"; dr1["Note"] = "Starii";
dr2["Name"] = "Gleb"; dr2["Owner"] = "Inga"; dr2["Note"] = "Tupaya";
dr3["Name"] = "Dusia"; dr3["Owner"] = "Olga"; dr3["Note"] = "Zlaya";
Cats2.Rows.Add(dr1);
Cats2.Rows.Add(dr2);
Cats2.Rows.Add(dr3);
dr2["Note"] = "Guzelle";
ds.Tables.Add(Cats2);
SqlCeCommandBuilder build = new SqlCeCommandBuilder(sCEdata);
sCEdata.Update(ds);
The Database only knows that is has to change something when you use a SQL command. You can create as many DataSets as you like, delete and insert data, but the Database stays the same until you tell it to change via a SQL command.
Related
This question already exists:
c# datagrid sql population
Closed 5 years ago.
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
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
}
}
}
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
Try the InsertAt() method instead of Add() of datatable with the appropriate position parameter.
I have DataTable and I need to add row with default values and save it into database.
BONUS: Would be awesome to auto increment key column.
How can I achieve that?
static int i = 1;
private void CreateDefault()
{
DataColumn column = null;
DataTable table = new DataTable();
column = new DataColumn();
var Col1 = column;
Col1.DataType = System.Type.GetType("System.Int32");
Col1.DefaultValue = i;
Col1.Unique = false;
table.Columns.Add(column);
i = i + 1;
column = new DataColumn();
var Col2 = column;
Col2.DataType = System.Type.GetType("System.String");
Col2.DefaultValue = "Your String";
table.Columns.Add(column);
DataRow row = null;
row = table.NewRow();
table.Rows.Add(row);
}
Variable i will be auto increment key column. Now Insert the DataTable to DataBase.
You can add a new row with default values and save it into database like this.
using (var conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTableName", conn);
SqlDataAdapter da = new SqlDataAdapter() { SelectCommand = cmd };
// Load records to a DataSet
DataSet ds = new DataSet();
da.Fill(ds, "YourTableName");
var table = ds.Tables["YourTableName"];
// Add a new row with default value
table.Rows.Add();
// Reflect the change to database
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.Update(ds, "YourTableName");
}
Also, if you've set an auto increment key like IDENTITY for MS SQL Server (https://msdn.microsoft.com/en-us/library/ms186775.aspx), this works when the new row is inserted.
I have faced a problem that I have a set of data tables in a dataset.I want to show them in a DataGrid view but It can only show one datatable.Is there any way to show more that one data table in a grid view?I mean more than one without any relation defined among tables.
Here is how I have added my data to a dataset
DataSet ds = new DataSet();
DataTable RunoffEnergy = new DataTable();
RunoffEnergy.Columns.Add("RF");
RunoffEnergy.Columns.Add("LD");
RunoffEnergy.Columns.Add("DT");
RunoffEnergy.Columns.Add("K(DT)");
RunoffEnergy.Columns.Add("K(LD)");
RunoffEnergy.Columns.Add("KE");
RunoffEnergy.Rows.Add();
RunoffEnergy.Rows[0][0] = this.RF.ToString();
RunoffEnergy.Rows[0][1] = this.Ld.ToString();
RunoffEnergy.Rows[0][2] = this.Dt.ToString();
RunoffEnergy.Rows[0][3] = this.K_Dt.ToString();
RunoffEnergy.Rows[0][4] = this.K_Ld.ToString();
RunoffEnergy.Rows[0][5] = this.Ke.ToString();
//
DataTable EstimationOfRunoff = new DataTable();
EstimationOfRunoff.Columns.Add("Rc");
EstimationOfRunoff.Columns.Add("Qe");
EstimationOfRunoff.Columns.Add("Q");
EstimationOfRunoff.Rows.Add();
EstimationOfRunoff.Rows[0][0] = this.Rc.ToString();
EstimationOfRunoff.Rows[0][1] = this.Qe.ToString();
EstimationOfRunoff.Rows[0][2] = this.Q.ToString();
//
DataTable DetachmentOfSoilParticles = new DataTable();
DetachmentOfSoilParticles.Columns.Add("Fc", typeof(double));
DetachmentOfSoilParticles.Columns.Add("Fs");
DetachmentOfSoilParticles.Columns.Add("Fz");
DetachmentOfSoilParticles.Columns.Add("F", typeof(double));
DetachmentOfSoilParticles.Columns.Add("Hc");
DetachmentOfSoilParticles.Columns.Add("Hz");
DetachmentOfSoilParticles.Columns.Add("Hs", typeof(double));
DetachmentOfSoilParticles.Columns.Add("H");
DetachmentOfSoilParticles.Rows.Add();
DetachmentOfSoilParticles.Rows[0][0] = this.Fc;
DetachmentOfSoilParticles.Rows[0][1] = this.Fs.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.Fz.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.F.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.Hc.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.Hs.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.Hz.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.H.ToString();
//
DataTable ImidiateDepositionOfSoil = new DataTable();
ImidiateDepositionOfSoil.Columns.Add("Nfc", typeof(double));
ImidiateDepositionOfSoil.Columns.Add("Nfs");
ImidiateDepositionOfSoil.Columns.Add("Nfz");
ImidiateDepositionOfSoil.Columns.Add("DEPc", typeof(double));
ImidiateDepositionOfSoil.Columns.Add("DEPs");
ImidiateDepositionOfSoil.Columns.Add("DEPz");
ImidiateDepositionOfSoil.Rows.Add();
ImidiateDepositionOfSoil.Rows[0][0] = this.Nfc;
ImidiateDepositionOfSoil.Rows[0][1] = this.Nfs.ToString();
ImidiateDepositionOfSoil.Rows[0][2] = this.Nfz.ToString();
ImidiateDepositionOfSoil.Rows[0][2] = this.DEPc.ToString();
ImidiateDepositionOfSoil.Rows[0][2] = this.DEPs.ToString();
ImidiateDepositionOfSoil.Rows[0][2] = this.DEPz.ToString();
//
DataTable DeleveryOfDetachedParticles = new DataTable();
DeleveryOfDetachedParticles.Columns.Add("Gc", typeof(double));
DeleveryOfDetachedParticles.Columns.Add("Gs");
DeleveryOfDetachedParticles.Columns.Add("Gz");
DeleveryOfDetachedParticles.Columns.Add("G", typeof(double));
DeleveryOfDetachedParticles.Rows.Add();
DeleveryOfDetachedParticles.Rows[0][0] = this.Gc;
DeleveryOfDetachedParticles.Rows[0][1] = this.Gs.ToString();
DeleveryOfDetachedParticles.Rows[0][2] = this.Gz.ToString();
DeleveryOfDetachedParticles.Rows[0][2] = this.G.ToString();
//
DataTable TransportCapesity = new DataTable();
TransportCapesity.Columns.Add("Tc", typeof(double));
TransportCapesity.Columns.Add("Ts");
TransportCapesity.Columns.Add("Tz");
TransportCapesity.Columns.Add("T", typeof(double));
TransportCapesity.Rows.Add();
TransportCapesity.Rows[0][0] = this.Tc;
TransportCapesity.Rows[0][1] = this.Ts.ToString();
TransportCapesity.Rows[0][2] = this.Tz.ToString();
TransportCapesity.Rows[0][2] = this.T.ToString();
//
ds.Tables.Add(DeleveryOfDetachedParticles);
ds.Tables.Add(EstimationOfRunoff);
ds.Tables.Add(DetachmentOfSoilParticles);
ds.Tables.Add(ImidiateDepositionOfSoil);
// ds.Tables.Add(DeleveryOfDetachedParticles);
ds.Tables.Add(TransportCapesity);
these data does not have any relations.they are just the results of some calculations
If it is not possible how Can I display these data in a user friendly way?
Thank you so much
One option: Perform Join operation on these tables in Linq, Store result into a data table;then assign this new datatable as datasource of grid.
this might be helpfull to join data tables in linq -LINQ join two DataTables
I have a dataset contains 2 datatables with a relation between them,
in the first table i have an ID (primary key) and MainAreaName and in the second table I have the ID from the first table with 2 other columns
the question is: how to view the MainAreaName from the first table with the other 2 columns from the second table in a gridview
DataSet MyDB = new DataSet("MyDB");
DataTable MainArea = new DataTable("MainArea");
DataTable NameNumber = new DataTable("NameNumber");
DataColumn Col01 = new DataColumn("ID", typeof(int));
Col01.AutoIncrement = true;
Col01.AutoIncrementSeed = 1;
Col01.AutoIncrementStep = 1;
DataColumn Col02 = new DataColumn("MainAreaName", typeof(string));
MainArea.Columns.Add(Col01);
MainArea.Columns.Add(Col02);
MainArea.PrimaryKey =
new DataColumn[] { MainArea.Columns["ID"] };
DataRow MyRow = MainArea.NewRow();
MyRow["MainAreaName"] = "Area1";
MainArea.Rows.Add(MyRow);
MyRow = MainArea.NewRow();
MyRow["MainAreaName"] = "Area2";
MainArea.Rows.Add(MyRow);
DataColumn Col11 = new DataColumn("MainAreaID", typeof(int));
DataColumn Col12 = new DataColumn("Name", typeof(string));
DataColumn Col13 = new DataColumn("Number", typeof(int));
DataColumn Col14 = new DataColumn("Comment", typeof(string));
NameNumber.Columns.Add(Col11);
NameNumber.Columns.Add(Col12);
NameNumber.Columns.Add(Col13);
NameNumber.Columns.Add(Col14);
NameNumber.PrimaryKey =
new DataColumn[] {
NameNumber.Columns["MainAreaID"], NameNumber.Columns["Number"] };
NameNumber.Rows.Add(1, "Test1", 67);
NameNumber.Rows.Add(1, "Test2", 87);
NameNumber.Rows.Add(2, "Test3", 77);
NameNumber.Rows.Add(2, "Test4", 88);
MyDB.Tables.Add(MainArea);
MyDB.Tables.Add(NameNumber);
MyDB.Relations.Add(
MyDB.Tables["MainArea"].Columns["ID"],
MyDB.Tables["NameNumber"].Columns["MainAreaID"]);
I tried to use the following code
DataRelation DR = new DataRelation("MainAreaRelation", MyDB.Tables["MainArea"].Columns["ID"], MyDB.Tables["NameNumber"].Columns["MainAreaID"]);
dataGridView1.DataSource = MyDB.Relations["MainAreaRelation"].ParentTable;
//or
dataGridView1.DataSource = MyDB.Relations["MainAreaRelation"].ParentTable;
but didn't work,
anyone can help please?
I have denormalized data in a DataTable.
The data contains employee names, and the pay they got over a series of pay cycles. i.e.:
My DataTable contains:
Employee 1 Jan-1-2012 $100
Employee 2 Jan-1-2012 $300
Employee 1 Feb-1-2012 $400
Employee 2 Feb-1-2012 $200
Employee 1 Mar-1-2012 $150
Employee 2 Mar-1-2012 $325
How can load this data into a DataSet where the parent DataTable contains the employees name, and the child DataTable contains details of the paycheck?
DataSet is nothing but a collection of DataTables. So to "load" the dataTable into dataSet simple Add it:
DataTable employees = new DataTable();
DataTable payCheckes = new DataTable();
DataSet ds = new DataSet();
ds.Tables.Add(employees);
ds.Tables.Add(payCheckes);
Do you want to "combine" datatables somehow?
Get paycheckes of each employee?
the code without manual insert:
DataSet ds = new DataSet();
DataTable dtemploye = new DataTable();
DataTable dtpayment = new DataTable();
ds.Tables.AddRange(new DataTable[] { dtemploye, dtpayment });
DataColumn dcIdemploye = dtemploye.Columns["ID_EMPLOYEE"];
DataColumn dcIdemployeprice = dtpayment.Columns["ID_EMPLOYEE"];
DataRelation drrelation = new DataRelation("relemploy_payment", dcIdemploye, dcIdemployeprice);
ds.Relations.Add(drrelation);
DataSet ds = new DataSet();
DataTable dtemploye = new DataTable();
DataColumn dcnameemploye = new DataColumn();
DataColumn dcIdemploye = new DataColumn();
dtemploye.Columns.AddRange(new DataColumn[]{dcnameemploye,dcIdemploye});
DataTable dtpayment = new DataTable();
DataColumn dtprice = new DataColumn();
DataColumn dtDate = new DataColumn();
DataColumn dcIdemployeprice = new DataColumn();
dtpayment.Columns.AddRange(new DataColumn[]{dcIdemployeprice,dtprice,dtDate});
DataRow drrowemploy = dtemploye.NewRow();
drrowemploy[0] = "1";
drrowemploy[1] = "Employee 1";
dtemploye.Rows.Add(drrowemploy);
DataRow drrowpayment = dtpayment.NewRow();
drrowpayment[0] = "1";
drrowpayment[0] = "01/01/2012";
drrowpayment[1] = " 300";
ds.Tables.AddRange(new DataTable[]{dtemploye, dtpayment});
DataRelation drrelation = new DataRelation("relemploy_payment", dcIdemploye, dcIdemployeprice);
ds.Relations.Add(drrelation);