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);
}
}
Related
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 is my code which i'm trying to return records back into a listview by entering different ID's. But i only seem to get the first record back no matter which ID i enter. Any help would be appreciated.
private void FindRecord()
{
List<SprocParameter> paramsSQL = new List<SprocParameter>();
paramsSQL.Add(new SprocParameter("ID", textBoxID.Text) );
DataSet ds = StoredProcedureExecute("get_ID", paramsSQL );
if (null != ds && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
textBoxID.Text = ds.Tables[0].Rows[0]["ID"].ToString();
textBoxName.Text = ds.Tables[0].Rows[0]["Name"].ToString();
textBoxAddress.Text = ds.Tables[0].Rows[0]
["Address"].ToString();
textBoxPhone.Text = ds.Tables[0].Rows[0]["Phone"].ToString();
}
else
{
textBoxID.Text = "Unrecognised ID";
textBoxName.Text = "Incorrect Name";
textBoxAddress.Text = "Wrong Address";
textBoxPhone.Text = "Invalid Number";
}
}
You aim is not entirely clear here, as you appear to be asking how to handle multiple rows but assigning these values to a text box which would suggest you only actually want one at a time. May I suggest executing the command stored procedure is a more readable way:
DataSet ds = new DataSet("peopleData");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("get_ID", conn);
sqlComm.Parameters.AddWithValue("#ID", textBoxID.Text);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
Then the data can be accessed with something like this for a single row outputting to a textbox:
DataRow dr = ds.Tables[0].Rows[0]; // This will access the first row
textBoxName.Text = dr["Name"].ToString();
Or if you are expecting your stored procedure to return many rows, you can iterate through them by doing something like the below. Although, in this case I suspect you wouldn't want to assign each value directly to the textbox, so it may be more appropriate deploy a ListView as suggested in the comments.:
foreach (DataTable dt in ds.Tables) // Only if you're expecting many datatables.
{
foreach (DataRow dr in dt.Rows)
{
textBoxName.Text = dr["Name"].ToString();
}
}
I have a question about DataTable. I retrieve a DataTable from the database, and one of these columns contains either a 1 or a 0. Now I want to retrieve only the rows with a 1 value of 1 in that column.
The name of the column is ACTIVATE.
Here is my DataTable:
DataTable table = new DataTable(TABLE);
//How can I filter here so ACTIVATE == 1?
adapter.Fill(table);
connection.Open();
selectcommand.ExecuteReader();
return table;
Via SQL (preferred)
SELECT * FROM dbo.Table WHERE ACTIVATE = 1
Via Linq-To-Datatable (in memory):
DataTable tblFiltered = table.AsEnumerable()
.Where(r => r.Field<int>("ACTIVATE") == 1)
.CopyToDataTable();
If you're still on .NET 2, you can use DataTable.Select:
DataRow[] filteredRows = table.Select("ACTIVATE = 1");
Apart from that, you don't need selectcommand.ExecuteReader() to fill the table.
DataTable table = new Datatable();
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand("SELECT * FROM dbo.Table WHERE ACTIVATE = 1", con))
using(var da = new SqlDataAdapter(cmd))
{
da.Fill( table );
}
DataTable results = table.Select("ACTIVATE = 1").CopyToDataTable();
That should achieve what you want, basically you can query data tables much like SQL.
You simply use DataTable.Select like this:
foundRows = table.Select("ACTIVATE = '1'");
It returns an array of DataRow objects.
return table;
DataTable results = table.Select("ACTIVATE = 1").CopyToDataTable();
I am using datatable to retrieve 1000 records from mysql database. I want to copy each record as it is to list. But I do not know the exact syntax for that.
Here is the following code I am trying to retrieve:
cmdmysql.CommandText = "select * from marctest.spectrum";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(cmdmysql.CommandText, conn);
//MySqlDataReader reader;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataMember = dt.TableName;
// row = dataGridView1.DataSource.ToString();
//row = dt.TableName;
MySqlDataReader reader;
reader = cmdmysql.ExecuteReader();
List<string> mylist = new List<string>();
foreach(DataRow row1 in dt.Rows)
{
mylist.Add(dt.Rows.ToString());
}
textBox1.Text = mylist.ToString();
Does anybody have an idea regarding the same? This is my actual code...
I'm not sure that doing DataRow.ToString() is going to get you anything useful (most likely just the object type).
If you want the data from each row as a string (perhaps tab-delimited?), you can try:
foreach(DataRow row1 in dt.Rows) {
StringBuilder sb = new StringBuilder();
foreach(DataColumn col in dt.Columns) {
sb.Append(row1[col].ToString();
sb.Append('\t');
}
mylist.Add(sb.ToString());
}
This will croak, if any of your column's have a null value so you may want to handle that.
Assuming that dt is the query result, and If you only need to convert these results to strings, then this should work:
foreach(DataRow row1 in dt.Rows)
mylist.Add(row1.ToString();
Situation:
Hello! I am trying to populate a WPF toolkit DataGrid with a MS Access database.
Here is what I have right now (it works):
//Load the datagrid with the database
private void LoadDataGrid(string filename, string path)
{
string databaseConn = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + path + "\\" + filename,
tableName ="";
OleDbConnection conn = null;
DataTable schemaTable,
table = new DataTable();
try
{
conn = new OleDbConnection(databaseConn);
try
{
conn.Open();
schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] { null, null, null, "TABLE" });
tableName = "[" + schemaTable.Rows[0].ItemArray[2].ToString() + "];";
string sqlQuery = "SELECT * FROM " + tableName;
OleDbCommand command = new OleDbCommand(sqlQuery, conn);
OleDbDataReader reader;
reader = command.ExecuteReader();
table.Load(reader);
DataGrid_.ItemsSource = table.DefaultView;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
The code sample above loads a WPF toolkit DataGrid with the help of a MS Access database.
What I would like to do is be able to insert a column in the DataGrid at the very beginning. This column would be used to write the row number. What I think could work is to modify the table variable (which is a DataTable object).
Question:
So, how can I insert a column in the table variable, add the row number for each rows in that new column, and have all the data from the database in the DataGrid?
An alternative is to create a column on the DataTable before loading the IDataReader into it.
// the rest of your code
//
DataTable table = new DataTable();
DataColumn col = table.Columns.Add("RowNumber", typeof(int));
col.AutoIncrementSeed = 1;
col.AutoIncrement = true;
//
// the rest of your code
//
table.Load(reader)
//
// the rest of your code
The code snippet bellow demonstrates the technique out of the question's context
//Simulates data coming from a database or another data source
DataTable origin = new DataTable();
DataColumnCollection columns = origin.Columns;
columns.Add("Id", typeof(int));
columns.Add("Name", typeof(string));
origin.Rows.Add(55, "Foo");
origin.Rows.Add(14, "Bar");
IDataReader reader = origin.CreateDataReader();
DataTable table = new DataTable();
//Sets up your target table to include a new column for displaying row numbers
//These are the three lines that make it all happen.
DataColumn col = table.Columns.Add("RowNumber", typeof(int));
col.AutoIncrementSeed = 1;
col.AutoIncrement = true;
//Simulates loading data from the database
table.Load(reader);
// Examine table through the debugger. Is will have the contents of "origin" with the column "RowNumber" prepended
Your easiest solution would be to modify your code to include a "virtual" RowNumber field in your original SELECT query, like so:
SELECT ROWNUM AS ROWNUMBER, * FROM TABLE1
Unfortunately, Access doesn't have anything like a ROWNUM function, so I think the easiest solution is to add a RowNumber column in the SELECT query like this:
SELECT 0 AS ROWNUMBER, * FROM TABLE1
which will add a column containing all zeroes at the beginning, and then iterate through the resulting DataTable and set the row number, like this:
int rownumber = 1;
foreach (DataRow row in table.Rows)
{
row["ROWNUMBER"] = rownumber;
rownumber++;
}
and then dump the DataTable into the grid.