.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Post New Web Links

Get ArrayList value in SqlDataReader

Posted By:      Posted Date: September 24, 2010    Points: 0   Category :ASP.Net

I'm trying to convert some code from VB to C# on a site i'm working on and can't seem to get the arraylist to function properly.

Here is what we currently have in the codebehind:

    Public objSDR As System.Data.SqlClient.SqlDataReader
    Public objCommand As System.Data.SqlClient.SqlCommand
    Public objConnection As System.Data.SqlClient.SqlConnection

    Public Sub OpenDB(ByVal SQLString)
        objConnection = New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True")
        objCommand = New System.Data.SqlClient.SqlCommand()
        objCommand.Connection = objConnection
        objCommand.CommandText = SQLString
        objSDR = objCommand.ExecuteReader()
    End Sub

    Public Sub CloseDB()
        objSDR = Nothing
        objCommand = Nothing
        objConnection = Nothing
    End Sub

    Public Function GetContent(ByVal pageID)
        Dim contentArray As New ArrayList()


        OpenDB("SELECT * FROM Content WHERE id = '" & pageID & "'")
        While objSDR.Read
            contentArray.Item(0) = objSDR.Item("heading&qu

View Complete Post

More Related Resource Links

How to bind TemplateField DropDownList with ArrayList?


Hi Expert!

  I'm trying gridview templateField DropDownList bind with arraylist. When i set bindsource i got this error. "//Error Object reference not set to an instance of an object."

My Sample .aspx

<asp:TemplateField HeaderText="Type">
                        <asp:DropDownList ID="_grvcboType" runat="server" Width="117px" DataTextField="Display" DataValueField="Value">
                        <asp:Label ID="Label7" runat="ser

sqlDataReader dos not get results


I am trying to run a stored proc from this function. When I run it thorugh the debugger I can see that myReader.HasRows = true and myReader.FieldCount =14.

But the control does not go in the loop while (myReader.Read()) where I am trying to read Version field returned by the stored proc.

Pls check me code and suggest correction. Thank You.

private static int Get_CaseInfo(string CaseNum)
            int Ver = 0;
            String myConn = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();
            SqlConnection conn = new SqlConnection(myConn);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = System.Data.CommandType.Text;

            SqlDataReader myReader = null;
            String stmt1 = "EXEC [REPORTS].[CaseInfoByCaseNo_Get] @CaseNo = '" + CaseNum + "'"; 
            cmd.CommandText = stmt1;
            cmd.Connection = conn;
                myReader = cmd.ExecuteReader();
                while (myReader.Read())
                    Ver = (int)myReader["Version"];

            catch (Exception)
            return Ver;         

Query an arraylist of array list using linq


I have an array list called Customer. I t holds a list of array list which has the account details.

proj.customer -> collection of arraylist of type customer

proj.customer.account -> collection of arraylist of type account

Account array list holds type account and it has a poperty account balance. How can I query all accounts which has account balance  >100

I tried the following one

var Accountlist= from Account accountdetails in proj.customer.account

where accountid.balance >100

select accountdetails.id

But it is always throwing an error saying cannot cast type customer to type account

Please help

ArrayList.ToArray fails!


In my app, I have code similar to the following:



               ArrayList alStartFrames = new ArrayList();
                byte[] abytTest = { 1, 2 };


                byte[] abytCombinedFrame = (byte[])alStartFrames.ToArray(typeof(byte));

            catch (Exception ex)

The call to ToArray always fails and the exception is caught even though I'm pretty sure alStartFrames is an array list of byte arrays. Anyone have any insight on why this is happening?! TIA

ArrayList indexes not set properly


I have some basic code to fill items in an ArrayList as follows:

Dim intSteps As ArrayList = New ArrayList()
Select Case Session("type")
Case 1
Case 2
Case Else
End Select

Dim j As Integer
	For j = 0 To intSteps.Count - 1
        Response.Write(intSteps.IndexOf(j) & " : " & intSteps.Item(j) & "<br />")

The issue is that for Case 1 the output is:

0 : 0
1 : 1
2 : 2
-1 : 6
-1 : 11
-1 : 12

For Case 2, it's:

0 : 0
1 : 1
2 : 2
-1 : 5
-1 : 6
3 : 11
4 : 12

And for Else, it's:

0 : 0
1 : 1
2 : 2
3 : 3
4 : 4
5 : 5
6 : 6
7 : 7
8 : 8
9 : 9
10 : 10
11 : 11
12 : 12

Why is the index being set as -1 for a few items?

SQLDataAdapter/SQLDataReader takes lot of time for executing a query

All, I have a webpage with 6 drop down lists. User can start with selecting any drop down list first, and then proceed in any order.  1. Assume when the 1st dropdown is selected first, rest 5 drop downs (except 1st) are filtered/updated based on the selected value in the 1st dropdown. 2. Assume user selects the 4th dropdown second, rest 5 drop downs (except 4th) will be filtered/updated but the condition would be based on both 1st drop down and 4th drop down. But while filtering the first drop down, only the 4th drop down is used as filter (self-filter will be ignored). The code works fine but I see a very bad performance hit in time when the user selects the fourth dropdown after selecting three drop downs. I tried using both SQLDataAdapter and SQLDataReader but neither used to solve the issue. The code takes a lot of time on one line in either of the code (which is highlighted below). When I run the query in SQLServer Mgmt Studio, the query completes in a few seconds.Using SQLDataReader: SqlConnection conn = new SqlConnection(CONNECTION); SqlCommand ObjCmd = new SqlCommand(query, conn); ObjCmd.CommandTimeout = 600; conn.Open(); SqlDataReader daSelTools = ObjCmd.ExecuteReader(); //This line takes a lot of time ddl.Items.Clear(); // Call Read before accessing data. while (daSelTools.Read()) { ddl.Items.Add(new ListItem(String.Format("{0}",daSelTools[0])));

Have some error using arraylist in session to store multiple value

i have two buttons in user control, button1 is (like) and second is (dLike). if i click any button the count will increased in my database table by 1. our table have id,title,url,imagegalary,articleid. in everypage i take the article id as in sessioni alredy disable the links when you click once , after i went to next page and come back to the same page the button will visible how to solve this problem. how to store the multiple session values in the arraylist and display it . please anybody replay me protected void ImageButton1_Click(object sender, ImageClickEventArgs e){string ArticleID1 = GenerateArticleID();COLTools.DB.DataBaseType = COLTools.DataBaseType.SqlServer;COLTools.DB.ConnectionString = ConfigurationSettings.AppSettings["COLCMS"].ToString();string updateQuery = "update Article set Alike = Alike + 1 where Articleid =" + ArticleID1;COLTools.DB.RunSql(updateQuery);disablebutton();addtovotelist(ArticleID1);likedislike();}protected void ImageButton2_Click(object sender, ImageClickEventArgs e){string ArticleID1 = GenerateArticleID();COLTools.DB.DataBaseType = COLTools.DataBaseType.SqlServer;COLTools.DB.ConnectionString = ConfigurationSettings.AppSettings["COLCMS"].ToString();string updateQuery = "update Article set Dlike = Dlike + 1 where Articleid =" + ArticleID1;COLTools.DB.RunSql(updateQuery);disablebutton();addtovotelist(A

Extension Method ForEach for ArrayList class

Hi,I need to create an extension method(ForEach) for arraylist classI have created an extension method for Array class but cannot do that for arraylist.Please help me namespace MyExtension { public static class IEnumerableExtension { public static void ForEach<T>(this IEnumerable<T> list, Action<T> action) { if (action == null) throw new ArgumentNullException("action"); foreach (T item in list) { action(item); } } } } Any Help Shall be appreciatedThanks

using SqlDataReader in Linq

Hi,In normal way of write the code as follows in DAL.DataSet ds=db.executedataset();IEnumerable<datarow>= ds.tables[0].asEnumerable();For better performance can use datareader in Linq instead of DataSet

How do I count occurences of an item in an ArrayList?

Hi All- Please help, I'm stuck!  After executing a query with LINQ to SQL, the result I have is an arraylist (.ToList)  of items with ID numbers.  The number of items and their occurences will vary with each query.  I would simply like to count the occurences of each specific ID in the list.  How do I do that??  The only count function I know of (.count() ) is for a count on the entire list.   I've also I've been reading on how to loop through the list items but I don't understand how I can do that if I don't know how many specific ID's there will be from each query result.    

How to remove data from arrayList with Linq?

Hi All-This arrayList produced by the Linq query returns data pairs of an ID and count.  I would like to keep pairs that have a high enough count.  For example, keep all that have a count of 5 and higher so if the arraylist contains:userID    Count1               102               93                94                35                1the remaining data in the arraylist would be userId 1,2, and 3 (with their counts).  How can I do this? Dim customerCount = (From c In results Group c By key = c.userID Into Group _ Select New With _ { _ .userID = key, _ .Count = Group.Count() _ } _ ).ToList().OrderByDescending(Function(a) a.Count)

Use arrayList elements as parameter for Linq Where condition

Hi all-I have a list of customer Id's as the result of a Linq Query named "localCustomers" which contains 100 or so Customer ID's.I'm would like use this list to  query and access customers' info on the whole group.  Been searching on how to do this but no luck.  It's easy enough with one customer ID, but how do I do it with an arrayList as the parameter? Here's my latest attempt but it's not working.  Dim areaCustomers = (From a In dc.CustomerTable _ From b In localCustomers _ Where a.customerID = b.customerID _ Select New With { _ a.customerAddress, _ a.customerFirstName, _ a.customerLastName}).ToList()

converting datatable data to arraylist

hi friends pl tell me how  to convert datatable data to arraylistthanks in advance

How can Serialize ArrayList ?

Hi code sample?????????public class Employee :ISerializable { private int version =1; //ADD emoployee name in this list private ArrayList employeeList; private void  AddEmployee(){ // Adding employee to Employee List}protected TestData(SerializationInfo info,StreamingContext context) { this.version = info.GetInt32("version"); this.name = info.GetString("list"); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("version", this.version); info.AddValue("list", this.employeeList); } }   Thanks in Advance nayakam

CS1061: 'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Item' and no ex

I'm making the switch from vb.net to C#, and am just trying to do a simple sql query and bind some of the data returned to a label.  BUT, I'm getting this error.. CS1061: 'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Data.SqlClient.SqlDataReader' could be found (are you missing a using directive or an assembly reference?) Here's my code behind:    What am I doing wrong??? using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; using System.Configuration; public partial class Section : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { getSectionContent(); } protected void getSectionContent() { SqlConnection conn = default(SqlConnection); SqlCommand comm = default(SqlCommand); SqlDataReader reader = default(SqlDataReader); string connectionString = ConfigurationManager.ConnectionStrings["123"].ConnectionString; conn = new SqlConnection(connectionString); comm = new SqlCommand(); comm.Connection = conn; comm.CommandType = System.Data.CommandType.StoredPr

Multi ArrayList (C#)

HiI want to pass just the first "nested" ArrayList, which I created in MultiDataArray (with Add) to a function: MultiDataArray.Add(new ArrayList()); XGetData(ref MultiDataArray[1]); // this version does not work Thanks for your advice. Patrick    

Help: SqlDataReader dr = command.ExecuteReader();

Hi,   I downloaded the code of  this great article  "GridView with Thumbnail Images - Part 1" http://www.codedigest.com/Articles/ArticleFiles/ZIPS/102.zip   I have no problem uploading the images. but I have problem to load it intoGridView. The reason is : Incorrect syntax near '='. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '='.Source Error: Line 13: connection.Open(); Line 14: SqlCommand command = new SqlCommand("select Image from Image where ImageID="+imageid, connection); Line 15: SqlDataReader dr = command.ExecuteReader(); Line 16: dr.Read(); Line 17: context.Response.BinaryWrite((Byte[])dr[0]);   I am using sqlexpress. Table name is Image with columns ImageID(Identity), ImageName(Varchar(50)) and Image(image). Any help is appreciated.   Juvan   Here is the code;   <%@ WebHandler Language="C#" Class="FullImage" %> using System; using System.Web; using System.Data.SqlClient; using System.Configuration; public class FullImage : IHttpHandler { public void ProcessRequest (HttpContext context) { string imageid = context.Request.QueryString["ImID"
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend