ADO.NET :: Converting Datareader To A List?
Feb 17, 2011In C#.I have a list<object>.
I want to convert any datareader result (with data) to a list of objects.
How can I do that?
In C#.I have a list<object>.
I want to convert any datareader result (with data) to a list of objects.
How can I do that?
I have a field in sql select statement that I want to read to a datareader and convert that value from the field to a word to display in a datagrid. i know that sounds confusing but let me give you an example.
I have a field called duration_interval in a sql table and it has data values of 'ww' for Weeks, 'dd' for Days and 'mm' for Months. When I load the Datagrid I want the field for this value to say Weeks instead of ww, how do I convert the 'ww' value to show the word Weeks in the datagrid? Below is the select statement and the code for the datareader I have on my page now that isn't working correct:
[Code]....
I have a wcf service.In many places I am converting business entity list to datacontract list.
So I am trying to write a generalised method.
I have acheived to convert business entities with out list.
But when we give a list of business entity,it is getting failed.
to convert list of Business Entity to List of Datacontracts.
I'm Using a DataReader to Read about 100,000 records, my code look like :
[Code]....
I have a per row computation in reading the rows on GetMyType2Info() method, and this method also another method that I return only one record by ExecuteReader(). the problem is that when the MyTypeList (List<T>) has about 21,000 Items of MyType (<T>) System.OutOfMemoryException is thrown. wanted to know how to resolve this and wanted to know more about the maximum size of List<T> capacity. in addition the execution of the main Query with 100,000 records take about 4 seconds in SQLServer a record has only types of nvarchar , float,datetime and int
- i have two drop down lists- ddl_SelectClient, ddl_SelectApplication
- when a client is selected in ddl_SelectClient, i have to show the list of the clients applications in ddl_SelectApplication
- i have written the below code in the ddl_SelectClient_SelectedIndexChanged routine to do the same
- i am getting the error("Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack") in the catch block when the ddl_SelectApplication gets binded
[Code]....
I'm having a method that exports content from the database to excel files. The method taks as paramaters a DataReader param and a int param - the number of rows. For the number of rows i'm using a dataset, wich i fill using the same query as for the datareader. So I'm executing it twice... Is there a way I can avoid that? get the number of rows from the datareader?
View 1 RepliesI am getting an error that an open DataReader associated with this Command, when I'm not using datareader(though probably executereader() is the same thing) how would I close this if I don't have a datareader present?
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spSelectAllTypes",conn);
cmd.CommandType = CommandType.StoredProcedure;
[code]...
I just want to be able to databind a bunch of dropdownlist in one open connection. (before I had multiple open and closes for each control)
I am using this
List<JobsMeta> JobsMeta= _db.JobsMetas.Where(m => m.int_OrganizationId == null || m.int_OrganizationId == OrganizationInfo.OrganizationId).OrderBy(m => m.int_SortId).ToList();
ViewData["JobMeta"] = JobsMeta;
now using the view i want to loop through ViewData["JobMeta"]
<% foreach (var JobsMeta in ViewData["JobMeta"]))
[Code]....
and XML looks like
[Code]...
and I'm retrieving information using this and it's working fine
[Code]...
Cannot I convert dropThis to a List? When I try to do
List<Contact> contactCollection = dropThis.ToList();
I get this error
Error 1
Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<Models.Contact>'
I'm completely at a loss.I've searched Google,forums anf etc.
I need to convert a SharePoint List to ASP.NET, including its column filters etc.
Aside from the underlying data which will be housed in a SQL Server table, what are good control choices on ASP.NET side for this? (I'm not sure if ASP.NET Gridview will have all the necessary features.)
I am converting my datatable to LISt using LINQ how do I handle nulls coming from database
List<Port> portDetails = new List<Port>();
DataTable dt = ds.Tables[0];
portDetails = (from q in dt.AsEnumerable()
select new Port
{
PortCode = q.Field<string>("Code"),
ExtCode = q.Field<string>("Nb"),
Name = q.Field<string>("Name"))
}).ToList();
In the above query if Code is null I do not want property portcode to be set to the value it should only set if it is not null or not blank
PortCode = q.Field<string>("Code"),
What should be syntax
I was trying somethign like this which doesnt work
Portcode = q.Field<bool>("Code") == null ? null : q.Field<bool>("Code")
I've data which looks something like this.
[code]....
To convert the above data into unordered list based on depth, I'm using the following code
[code]...
But the resulting unordered list doesnt seem to be forming properly(using which i am constructing a tree).For example "Site " with id '180' is supposed to appear as a direct child of "Televisions" with id '1',is appearing as a direct child of 'Flash' with id '191' using my code.so in addition to considering depth,I've decided to consider itemid as well in order to get the treeview properly.Those rows of the table with itemId not equal to null are not supposed to have a child node(i.e.,they are the leaf nodes in the tree) and all the other nodes can have child nodes.
Update:
The 'itemid' column refers to the id of an item which is present in another table.This column just in identifying if an item has any sub items(i.e., 'name' in my data in this case has any other unordered lists under it).
I have the following code which does what it's supposed to do:
objSQLCommand = New SqlCommand("select * from table1", objSQLConnection)
objSQLCommand.Connection.Open()
objSQLDataReader = objSQLCommand.ExecuteReader()[code]....
But I need to loop through the objSQLDataReader 1 more time. How would I do that?
how we can serialize a datareader in webservices.
View 1 RepliesWhat is the difference between DataSet and DataReader in Asp.net with Example..
View 11 RepliesHow to serialize the DataReader in webservices in asp.net?
View 4 RepliesLang-ASP.net using C# and Sql server 2005
i m trying to use the sql datareader to fetch a single row at a time i wanna know can we use it to fetch a single row at a time or not if yes i m unable to figure out what i m doing wrong here bcus its not returning any data
[Code]....
of course data is present in my table bcuz when i m using dataset i m able to the return the single row throuugh dataset
Why can I not call the global variables CatCode and CompanyName which are equated in the first procedure GetCompanyCatID And use their new values in the second procedure UpdateCompanyCounts as parameter values. When I hard code them code their values at the end of the GetCompany CatID procedure the following procedure updates properly.
string CatCode; - delcared global
string CompanyName; - delcared global
protected void GetCompanyCatID()
{
LinkID2 = Request.QueryString["linkid"].ToString();
string L_ID = LinkID2;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString001"].ConnectionString);
SqlCommand cmd = new SqlCommand("GetCID", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@L_ID", L_ID);
try
{
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader["CG_ID"] != System.DBNull.Value)
CatCode = (string)reader["CG_ID"];
CompanyName = (string)reader["CG_Name"];
}
}
}
catch (SqlException exc)
{ }
finally
{ con.Close(); }
// ******* HARD CODED to test below update procedure, it works. When commented out the following update procedure does not update.
CatCode = "55555"
CompanyName = "Test";
UpdateCompanyCounts();
}
protected void UpdateCompanyCounts()
{
LinkID2 = Request.QueryString["linkid"].ToString();
string L_ID = LinkID2;
string CatCode2 = CatCode;
string CompanyName2 = CompanyName;
// string CatCode2 = "23456";
// string CompanyName2 = "TEST";
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString001"].ConnectionString);
SqlCommand cmd2 = new SqlCommand("UpdateCatCounter", con2);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("@L_ID", LinkID2);
cmd2.Parameters.AddWithValue("@CG_ID", CatCode2 );
cmd2.Parameters.AddWithValue("@CG_Name", CompanyName2 );
try
{
con2.Open();
cmd2.ExecuteNonQuery();
}
catch (SqlException exc)
{
// ErrorBox.Text += string.Format("Error: {0}<br/>", exc.Message);
}
finally
{
con2.Close();
}
}
I heard that DataReader works on forward only readonly fashion and at a time it willread a single record.Suppose when i execute the below code
SqlDataReader reader=cmd.ExecuteReader();
gv1.DataSource=reader;
gv.DataBind();
How the does the gridview populate all records?.As the reader is capable of reading one row per read,I thought only the last row is available for GridView to display.
I've got a static class containing a static field which makes reference to a wrapper object of a DataContext.
The DataContext is basically generated by Visual Studio when we created a dbml file & contains methods for each of the stored procedures we have in the DB.
Our class basically has a bunch of static methods that fire off each of these stored proc methods & then returns an array based on a LINQ query.
Example:
public static TwoFieldBarData[] GetAgesReportData(string pct)
{
return DataContext
.BreakdownOfUsersByAge(Constants.USER_MEDICAL_PROFILE_KEY, pct)
.Select(x => new TwoFieldBarData(x.DisplayName, x.LeftValue, x.RightValue, x.TotalCount))
.ToArray();
}
Every now and then, we get the following error:
There is already an open DataReader associated with this Command which must be closed firs
This is happening intermittently and I'm curious as to what is going on. My guess is that when there's some lag between one method executing and the next one firing, it's locking up the DataContext and throwing the error.
Could this be a case for wrapping each of the DataContext LINQ calls in a lock(){} to obtain exclusivity to that type and ensure other requests are queued?
I have an aspx page which allows a user to submit modified entries into the database, but when the user clicks Submit to fire the stored procedure I want to first run a check to see if a modified row with the same relationship exists.I am passing the results of the following query:
SELECT SwitchRoom.ModifiedID FROM SwitchRoom WHERE
SwitchRoomID = @ChkSwitchRmID", constring;
into a DataReader to determine if that relationship exists.I need it to determine whether the reader returns NULL to allow the procedure to execute, if it doesn't, then don't allow the user to save the information.I've tried the following:
if (dbreader = NULL)
{
Fire Procedure
}
else
{
"Error Message"
}
and I've even tried passing the reader into a datatable and running it against that without any luck.
I have put a SQLDataSource on my page and everything is adjusted and it works properly. I read an article
here which was indicating that you can use a DataReader in order to get data from sqldatasource, but it doesn't say how, the only thing that is said is to use DataSourceMode property in order to adjust it for a DataReader.
see i want to fill datatable using datareader.
i have created object like this
SqlDataReader dr=cmd.ExecuteReader();
if(dr.HasRows)
{
}
I have a problem with how to fill an array list from a data reader
string queryDTL = " SELECT * FROM tbl1 ";
connection.Connect();
cmd = new OracleCommand(queryDTL, connection.getConnection());
dr_DTL = qcmd2.ExecuteReader();
ArrayList RecordsInfo = new ArrayList();
while (dr_DTL.Read())
{
RecordsInfo = dr_DTL["number"].ToString();
}
The problem is the datareader contain alot of info other than the number but I don't know how to put them in their correct position.
I am using this line to pull out the date from a datareader linked to an sql statement.
PHP Code:
lbl_wall.Text = "<span style='font-size:12px;color:#555; font-style:italic'>Member since - " + String.Format("{0:ddd, MMM d, yyyy}", dbReaderPr["date_added"].ToString()) +"</span>";
The date format should be like:-
Quote:
"Sun, Mar 9, 2008"
But it appears like this:-
Quote:
"1/28/2010 8:00:16 AM"
How can i fix this?