Call dataset from dictionary in foreach loop - c#

How do I call a data set from a dictionary inside of a foreach loop? In the code below .Rows doesn't exist and the dataset is null in the foreach loop.
public class dictWITHdataset
{
public dictWITHdataset()
{
DataSets = new Dictionary<string, DataSet>();
}
public IDictionary<string, DataSet> DataSets { get; private set; }
public DataSet readrows(DataSet dataset)
{
string query = "SELECT * FROM test.dbo.test";
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
adapter.Fill(dataset);
return dataset;
}
}
I later try to call the dataset from a dictionary in a foreachloop but it claims Rows does exist and its null.
dictWITHdataset dict = new dictWITHdataset();
DataSet data = new DataSet();
dict.DataSets("Dictionary1",data) //not sure if correct way to call data set
foreach (System.Data.DataRow row in dict.DataSets["Dictionary1"].Rows)
{
#:row["id"] + " " + row["name"];
}

You have forgot to call dict.readrows call, thus it only adds an empty dataset. Also, readrows does not need to take a parameter, you can create it in the function.
dictWITHdataset dict = new dictWITHdataset();
DataSet data = new DataSet();
dict.DataSets("Dictionary1",dict.readrows(data))
foreach (System.Data.DataRow row in dict.DataSets["Dictionary1"].Rows)
{
#:row["id"] + " " + row["name"];
}

Related

only 1 record coming instead of multiple records in the model in c#

im getting only 1 row multiple times instead of getting multiple records. same record getting multiple times in the datatable and model.
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT
Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
m.DeviceDate =Convert.ToDateTime(deviceDate);
m.Units =Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);
Since the object is created before foreach, The object will be replaced with new entries all the time. Add Trans_energycons_ReportModel m = new Trans_energycons_ReportModel(); inside foreach
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
//Create object here
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
m.DeviceDate = Convert.ToDateTime(deviceDate);
m.Units = Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);

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

Display Json Values using webapi

I have datatable for fetching my datas from mysql table and i using a foreach loop for getting each value.So i want to convert each value to json and need to display all these values.How can i possible?
My Table
public static DataTable GetAlldata()
{
try
{
string connString = "Server=localhost;database=mytable;uid=myid;";
string query = "SELECT Tname FROM `mytable`.`tdetails`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
public string jsonvalues()
{
string s = "";
RootObject ro = new RootObject();
DataTable dtaltheat = GetAlldata();
foreach (DataRow drow in dtaltheat.Rows)
{
string theatnme = drow["TheatreName"].ToString();
JavaScriptSerializer ser = new JavaScriptSerializer();
s = ser.Serialize(theatnme);
List<string> List = new List<string>();
List.Add(s);
}
return s;
}
This is the present status of my code.But it doesn't work..I am new in this field,so help me..

How to add values from Dataset to a List?

string str = "Select bd_id from [Active]";
ds = new DataSet(str);
da = new SqlDataAdapter(str, con);
da.Fill(ds);
I want to add the dataset that i get that is a List of ID'S in the form:
bd_id
1
2
3
Into a generic LIST as Items
How do i go about doing the same?
Makue use of LINQ to DATATABLE will do you task easily.
DataTable dtDetails = ds.Table[0];
List<int> lstExcelCurrencyCode =
(from dr in dtDetails.AsEnumerable()
select dr.Field<int>("bd_id")).ToList<int>();
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
sda.Fill(ds, "table");
IList<T> lists = GetList<T>(ds.Tables["table"]);
//DataTable Convert To List Method
public List<T> GetList<T>(DataTable table)
{
List<T> list = new List<T>();
T t = default(T);
PropertyInfo[] propertypes = null;
string tempName = string.Empty;
foreach (DataRow row in table.Rows)
{
t = Activator.CreateInstance<T>();
propertypes = t.GetType().GetProperties();
foreach (PropertyInfo pro in propertypes)
{
tempName = pro.Name;
if (table.Columns.Contains(tempName))
{
object value = row[tempName];
if (value.GetType() == typeof(System.DBNull))
{
value = null;
}
pro.SetValue(t, value, null);
}
}
list.Add(t);
}
return list;
}

C# DataTable Update Multiple Lines

how can i do multiple update using datatable ?
i found this Update 1 row
my code:
public void ExportCSV(string SQLSyntax, string LeFile, bool Is_Ordre, int TypeDonne)
{
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
SqlDataAdapter da = new SqlDataAdapter(SQLSyntax, connectionWrapper.conn);
DataSet ds = new DataSet();
da.Fill(ds, "Emp");
DataTable dt = ds.Tables["Emp"];
CreateCSVFile(dt, LeFile, Is_Ordre, TypeDonne);
//Update all lines, it not save in Database
foreach (DataRow row in dt.Rows)
{
row["IS_IMPORT"] = true;
}
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
the problem is :
foreach (DataRow row in dt.Rows)
{
row["IS_IMPORT"] = true;
}
it not save it into database.
Thanks you in advance,
Stev
You need to first set the UpdateCommand property on the DataAdapter to the UPDATE statement that will be executed to update a row in the database.
Then, after updating values in the DataTable, you need to pass it to DataAdapter.Update().
This will then execute the UpdateCommand for each updated row in the DataTable.
References:
MSDN - SqlDataAdapter.Update
MSDN - SqlDataAdapter.UpdateCommand
You are updating the value in-memory. The DataTable class is not a sql view, but a memory representation. The Sql Data Adapter only copy the data.
You have to write back the changes to the DB. Try this :
public void ExportCSV(string SQLSyntax, string LeFile, bool Is_Ordre, int TypeDonne)
{
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
SqlDataAdapter da = new SqlDataAdapter(SQLSyntax, connectionWrapper.conn);
da.UpdateCommand = connectedConnection.CreateCommand();
da.UpdateCommand.XXXX = YYYY; // construct the SQL Command
DataSet ds = new DataSet();
da.Fill(ds, "Emp");
DataTable dt = ds.Tables["Emp"];
CreateCSVFile(dt, LeFile, Is_Ordre, TypeDonne);
//Update all lines, it not save in Database
foreach (DataRow row in dt.Rows)
{
row["IS_IMPORT"] = true;
}
da.Update(dt);
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
This should works.
You will have to call da.Update()

Categories

Resources