how to fill (write) datacolumn to list<>? - c#

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

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

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

Data Table Copy not showing properly in GridView

I have a stored procedure which actually concatenates 2 columns and returns a DataTable.
Its as below:
create procedure [dbo].[spEnqIDFyYear]
as
begin
select CONVERT(nvarchar(50),enq_id)+'/'+CONVERT(nvarchar(50),YEAR(fy_year)) as EnqIDFyYear from Sample.dbo.enquiry_details
end
GO
The output is as follows:
EnqIDFyYear
1/2015
2/2014
I have another procedure, whose output is as below:
profile_name
ProfileA
ProfileB
I bind both the procedures to 2 DataTables, merge those 2 DataTables into a 3rd one and bind the resulting DataTable to the gridview.
But the gridview is not showing as proper. It shows as below:
The rows should be aligned to each other. How to achieve it?
Code behind is as below:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt1 = PopulateDashBoardGrid1();
DataTable dt2 = PopulateDashBoardGrid2();
DataTable dt3 = new DataTable();
dt3 = dt1.Copy();
dt3.Merge(dt2);
GridView1.DataSource = dt3;
GridView1.DataBind();
}
//Populate the main DashBoard Grid
public DataTable PopulateDashBoardGrid1()
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter("spEnqIDFyYear", con);
DataTable dt = new DataTable();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
}
public DataTable PopulateDashBoardGrid2()
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter("spClientProfileName", con);
DataTable dt = new DataTable();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
}
Experts please help.
Regards
Anurag
You are getting that kind of output, because Merge works in that way if the columns are not same of two datatables. So you need to write some custom code.
Here is what I have:-
static DataTable MergeDataTables(DataTable dt1, DataTable dt2)
{
DataTable dt3 = dt1.Copy();
foreach (DataColumn dc in dt2.Columns)
{
dt3.Columns.Add(dc.ColumnName).DataType = dc.DataType;
}
for (int i = 0; i < dt3.Rows.Count; i++)
{
foreach (DataColumn dc in dt2.Columns)
{
string col = dc.ColumnName;
dt3.Rows[i][col] = dt2.Rows[i][col];
}
}
return dt3;
}
You can call this method to merge both datatables.

Inserting data into gridView without using SqlDataSource and DataBind from a Sql Table

In my database web application, I am trying to add data to a column in gridView from a SQL table using the following code snippet
public void GetRowHeaders(GridView gridViewSample)
{
string commandstr = #"SELECT ID FROM WhiteBoardTest WHERE ID!=0 ORDER BY ID";
SqlCommand rowHeaderCmd = new SqlCommand(commandstr, sqlcon);
sqlcon.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = rowHeaderCmd;
da.Fill(dt);
for (int i = 0; i < dt.Columns.Count; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
gridViewSample.Rows[0].Cells[j].Text = dt.Rows[j][i].ToString();
}
}
sqlcon.Close();
}
When I ran the above code, I got the error saying
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection
I understand that the exception has occurred because the gridView has no rows or columns available.
Can anyone suggest me how to add rows to a column and also I am not using SqlDataSource because I would like add one more column to the gridView from a different table.
I would just include the extra column in your select statement and just bind to the gridview - unless there's a specific reason for not doing that. note the new sql!
public void GetRowHeaders(GridView gridViewSample)
{
string commandstr = #"SELECT a.*, b.somecolumn FROM tablea as a inner join tableb as b on b.someid= a.someid WHERE ID!=0 ORDER BY ID";
SqlCommand rowHeaderCmd = new SqlCommand(commandstr, sqlcon);
sqlcon.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = rowHeaderCmd;
da.Fill(dt);
gridViewSample.DataSource = dt;
gridviewSample.DataBind();
sqlcon.Close();
}
Or you could populate a collection of some class ( remember to use properties for gridviews databind), a List maybe, and just databind that to the grid.
Dayakar, what you can do is add additional column and data to DataTable itself and then bind it to the gridview. below is a example code.
private void SetupGridView()
{
var dt = GetDataTable();
// add addition column
dt.Columns.Add(new DataColumn() {ColumnName = "Id2", DataType = typeof (int)});
// add additional data
for (var i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["Id2"] = Convert.ToInt32(dt.Rows[i][0])*2;
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can also merge two datatables to create one datatable and then bind it to gridview. Refer http://msdn.microsoft.com/en-us/library/fk68ew7b.aspx

Inserting records from datatable into list

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

Categories

Resources