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.
Related
I have 2 different databases - SQLite and PostgreSQL and i trying to make tiny math on table from this databases.
Both tables contains columns nr_serii and ilosc, SQLite:
And Postgres:
I established a connection to both databases and populate dataset. Maybe i should use different place to store the data?
I need to substraction column ilosc: (sqlite-postgres), but not know how to do that.
For example, for each nr_serii make substraction column ilosc:
nr_serii:222222
ilosc:15-7=8
Finally i want to show output data to datagridview.
When i use messagebox i can see the data in dataset. Here is my part of code:
string cs = #"URI = file:" + Sdatabase;
string csP = conParam;
string sqlP = "select nr_serii, ilosc from stany";
string sql = "select nr_serii, ilosc from przychod";
using var con = new SQLiteConnection(cs);
con.Open();
using var cmd = new SQLiteCommand(sql, con);
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
using var conP = new NpgsqlConnection(csP);
conP.Open();
NpgsqlCommand cmdP = new NpgsqlCommand(sqlP, conP);
NpgsqlDataAdapter DA = new NpgsqlDataAdapter(cmdP);
DataSet dsP = new DataSet();
DA.Fill(dsP);
//----------test-----------
foreach (DataRow row in dsP.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
MessageBox.Show(nr_serii +","+ ilosc);
}
//--------------------------
For example, you can browse data table from first datasource ds and search for a matching row by value of nr_serii column for each row in the datatable in second datasource dsP, and if found, add a new row with the calculation result to the new third result table.
Then you don't forget to solve the problem of what to do with records that are only in the first ds or only in the second dsP datasource, depending on the value of the nr_serii column.
Program code example:
//prepare result third DataTable
DataTable resultDt = new DataTable();
resultDt.Columns.Add("nr_serii");
resultDt.Columns.Add("ilosc");
//add content to result DataTable
foreach (DataRow row in ds.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
DataRow drP = null;
foreach (DataRow dataRow in dsP.Tables[0].Rows)
{
if (nr_serii.ToString() == (string)dataRow["nr_serii"])
{
drP = dataRow;
break;
}
}
if (drP != null)
{
var dr = resultDt.NewRow();
dr["nr_serii"] = nr_serii;
dr["ilosc"] = (int)ilosc - (int)drP["ilosc"];
resultDt.Rows.Add(dr);
}
}
I have a datagridview and I filled with data.
DataTable table = new DataTable();
dataGridView1.DataSource = table;
con = new SqlDataAdapter("SELECT * FROM TABLE "'", con);
ds = new System.Data.DataSet();
con .Fill(ds, "TABLE");
My problem is I have to add rows manually like the code below but it is just add one row.But what I need foreach's count row.
foreach (var a in names.Split(new char[] { ';' }))
{
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
dataGridView2.Rows[i + 1].Cells[3].Value = a.ToString();
i = i +1;
}
Try to use
DataTable dataTable = (DataTable)dataGridView2.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd[3] = a.ToString();
dataTable.Rows.Add(drToAdd);
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.
How do I pass value of my calculated result in datagridview. In the following code I filled the 2 columns of grid by the values fetched from database through DataTable, then I add a new column named "Text". Now I want to pass a value of my calculated hash in this column but there may b some syntax problem or some mistake which causes an error occurred. Following is my code;
SqlDataAdapter sda = new SqlDataAdapter("Select Image,Hash from UserInput where PINCODE = '" + txt_LPin.Text + "'",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
int nOr = dataGridView1.Rows.Count;
if (nOr == 5)
{
LoginCluePoint lcp = new LoginCluePoint();
lcp.dgv_LCP.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
lcp.dgv_LCP.RowTemplate.Height = 101;
lcp.dgv_LCP.DataSource = dt;
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = "Text";
int colIndex = lcp.dgv_LCP.Columns.Add(col);
lcp.dgv_LCP.Columns[2].Visible = false;
}
This problem is resolved by the following code
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = "Text";
int colIndex = lcp.dgv_LCP.Columns.Add(col);
dgv_LCP.Rows[0].Cells[2].Value = hash
lcp.dgv_LCP.Columns[2].Visible = false;
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.