Inserting records from datatable into list - c#

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();

Related

C# simple subtraction from two different database

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);
}
}

C# DataRow from DataTable not reading first value

I'm new to StackOverflow and I have a question here.
When I'm reading my Rows from a DataTable, the first time the result is empty (the app crash) and after if I'm in debug mode, I can see that the first row is read but its too late.
Here is the code.
MySqlDataAdapter da = new MySqlDataAdapter(query, conn);
DataSet ds = new DataSet();
da.Fill(ds);
foreach (DataTable table in ds.Tables)
{
foreach (DataRow myrow in table.Rows)
{
Number.Text = Convert.ToString(myrow[0]);
Text.Text = Convert.ToString(myrow[1]);
I changed the query, shoing the same thing but in a fifferent way and now its working.

Trying to get second row from DataTable

I'm trying to retrieve the second row from a DataTable but this is not returning a value. What could be the problem as the DropDown populates just fine.
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DropDown.DataSource = dt;
DropDown.DataTextField = "FirstName";
DropDown.DataValueField = "FirstName";
DropDown.DataBind();
con.Close();
var secondRow = dt.Rows[2].ToString(); // This should return the second row in my datatable.
}
DataTable.Rows[int] will give you the DataRow object. If you do dt.Rows[2].ToString(), you are going to get the string representation of the object type.
The index starts at 0. Hence for 2nd row, you will query dt.Rows[1]. Further, You can extract the value of a column in the row and for that, you have to mention the column index or name like - dt.Rows[1][0] or dt.Rows[1]["col1"]
You can also loop through all the columns in the row like below:
foreach (DataColumn col in dt.Columns)
{
var columnValue = dt.Rows[1][col];
}

how to fill (write) datacolumn to list<>?

I am trying to get a datacolumn with values (already filled in data table) and write it in an auto property present in access layer. Currently, the method i am using is fetching data from sql and passing the values to gird. I am trying to use that method and already filled datatable but the problem is, auto property is only reading column name and as a result i am getting column name in another control (list box). The below is my method in BLL.
DAL d = new DAL();
public Object getfeechallan(Bal B)
{
sqlcommand cmd = new sqlcommand("select * from tblfee where fee_challan_No like #abc,d.con");
cmd.parameters.addwithvalue("#abc","%"+b.fee_challan_No+"%");
datatable dt=d.getdatafilter(cmd);
foreach(datacolumn dd in dt.columns)
{
if(dd.columnname=="ftid")
{
list<DataColumn> dc = new list<DataColumn>();
dc.Add(dd);
b.abc=dc;
}
} return dt;
}
My method in DAL is
public Datatable getdatafilter(SqlCommand CMD)
{
SqlDataAdapter da = new SqlDataAdapter(CMD);
Datatable dt = new Datatable ();
da.Fill(dt);
return dt;
}
Auto Property is
public list<DataColumn> abc {get; set;}
Ok.. so the below should do it.
public DataTable getfeechallan(Bal b)
{
SqlDataAdapter sdb = new SqlDataAdapter("Select count(*) From reserve", con);
DataTable dt = new DataTable();
List<string> dc = new List<string>();
sdb.Fill(dt);
foreach (DataRow dd in dt.Rows)
{
dc.Add(dd["ftid"].ToString());
}
Bal.abc = dc;
return dt;
}
One other observation. Unless you need the datatable returning, change the return type to "void". I presume all the data you need is now in the "Bal" object.
if you are trying to get a list contains all values in certain column
you can not just ref the column
you need to loop all rows of that column
List<object> values = new List<object>();
for(int i = 0; i < dt.Rows.Count(); i++)
{
values.Add(dt[i]["columnName"]);
}

how to retrieve data table in the form of table into the listbox

i am creating an application of extracting excel in to data table which will display in to list ox. but problem is all the data comes row wise data into list box.
DataTable dt = new DataTable();
DataSet ds = new DataSet();
DataTable sheet = dbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
OleDbCommand selectCmd = new OleDbCommand(String.Format("SELECT * FROM [{0}]", sheet.Rows[0]["TABLE_NAME"]), dbConn);
OleDbDataAdapter dbAdapter = new OleDbDataAdapter(selectCmd);
dbAdapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
ListBox1.Items.Add(row[col].ToString());
}
}
Why donĀ“t you just use the DataGridView class? Then just can set the DataTable as data source directly.
dataGridView1.DataSource = dt;
For a listbox, you'll need to create a string representing each column. Which will be hard to align. And if you would want to modify the cell values it would be quite cumbersome.
foreach (DataRow row in dt.Rows)
{
var sb = new StringBuilder();
foreach (DataColumn col in dt.Columns)
{
sb.Append(row[col] + "\t");
}
ListBox1.Items.Add(sb.ToString());
}

Categories

Resources