Click here to Skip to main content
15,113,057 members
Please Sign up or sign in to vote.
1.04/5 (5 votes)
See more:
Can anyone know this?

This my coding....when execute it produce the error that "Index was outside the bounds of the array."


C#
public void details(string id)
   {
       if (con.State == ConnectionState.Closed)
       {
           con.Open();
       }
           string ids = Request.QueryString["ID"];
       Session["pro_id"] = ids.ToString();
       SqlCommand cmd = new SqlCommand("select pro_id,pro_name,description,pro_img,price from product where pro_id='"+ids+"'", con);
       SqlDataReader dr = cmd.ExecuteReader();
       if (dr.HasRows)
       {
           while (dr.Read())
           {
               lblpro_id.Text = dr[0].ToString();
               lblpro_name.Text = dr[1].ToString();
               description.Text = dr[2].ToString();
               pro_img.Text= dr[7].ToString();
               lblprice.Text = dr[20].ToString();
             }
       }
       dr.Close();
       con.Close();

   }
Posted
Updated 11-Nov-21 18:39pm
v2
Comments
Sergey Alexandrovich Kryukov 23-Nov-11 23:15pm
   
No exception information. How do you imagine helping you?
--SA
sathiyak 23-Nov-11 23:21pm
   
in my database the index position of price is 20 but when i give dr[20] it shows error.....

Exception information is not shown, but most likely the exception is in dr[20]. Or dr[7]. It looks like you have less columns in data reader output than you assume — just look at your query.

The code is generally bad. Immediate constants like 2, 7, 20 make the code hard to support. Also, if you have more than 1 row, you keep assigning the reading to the same variable over and over, loosing the previously assigned values, so the whole block inside data reader reading block makes no sense: the result of it is assigning only the values from the same row. And you should not close connection every time to open it again and again on each call to details. It's much better opening the connection on demand and keep it open, using the lazy evaluation strategy (http://en.wikipedia.org/wiki/Lazy_evaluation[^]).

—SA
   
Comments
thatraja 24-Nov-11 0:11am
   
Right 5!
   
Thank you, Raja.
--SA
Are there a minimum of 21 columns in your table? if not this is the reason for your exception.
   
Comments
sathiyak 23-Nov-11 23:39pm
   
i have 21 colums exactly..but error comes like this....
[no name] 24-Nov-11 0:07am
   
your select query has only five columns and you access the value of 7 and 20 index thats why the error is coming
your select query has only five columns and you access the value of 7 and 20 index thats why the error is coming
   
Hi,
I am totally agree with SA. But if you unable to find the exception cause, you can try this to avoid the exception.
C#
lblpro_id.Text = dr.FieldCount == 1 ? "" : dr[0].ToString();
lblpro_name.Text = dr.FieldCount == 2 ? "" : dr[1].ToString();
description.Text = dr.FieldCount  == 3 ? "" : dr[2].ToString();
pro_img.Text= dr.FieldCount == 8 ? "" : dr[7].ToString();
lblprice.Text = dr.FieldCount == 21 ? "" : dr[20].ToString();

Otherwise instead of repeating the code you can try this:
C#
if(dr.FieldCount >= 21)
{
      lblpro_id.Text = dr[0].ToString();
      lblpro_name.Text = dr[1].ToString();
      description.Text = dr[2].ToString();
      pro_img.Text= dr[7].ToString();
      lblprice.Text = dr[20].ToString();
}



--Amit
   
Replace ur code
C#
SqlCommand cmd = new SqlCommand("select * from product where pro_id='"+ids+"'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
    while (dr.Read())
    {
        lblpro_id.Text = dr[0].ToString();
        lblpro_name.Text = dr[1].ToString();
        description.Text = dr[2].ToString();
        pro_img.Text= dr[7].ToString();
        lblprice.Text = dr[20].ToString();
      }
}

Or Replace
C#
SqlCommand cmd = new SqlCommand("select pro_id,pro_name,description,pro_img,price from product where pro_id='"+ids+"'", con);
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {
            while (dr.Read())
            {
                lblpro_id.Text = dr[0].ToString();
                lblpro_name.Text = dr[1].ToString();
                description.Text = dr[2].ToString();
                pro_img.Text= dr[3].ToString();
                lblprice.Text = dr[4].ToString();
              }
        }
   
In first senario:

if you define the fields in your query. then your indexing is depend on your query.for example if you write:


SqlCommand cmd = new SqlCommand("select pro_id,pro_name,description,pro_img,price from product where pro_id='"+ids+"'", con);

then indexing will be according your query.
pro_id on will be 0 index,
pro_name on will be 1 index,
description on will be 2 index,
pro_img on will be 3 index,
price on will be 4 index

and you can access your field according to above indexing

SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
lblpro_id.Text = dr[0].ToString();
lblpro_name.Text = dr[1].ToString();
description.Text = dr[2].ToString();
pro_img.Text= dr[3].ToString();
lblprice.Text = dr[4].ToString();
}
}
dr.Close();
con.Close();

In second scenario:

if you write * in select command. for example:

SqlCommand cmd = new SqlCommand("select * from product where pro_id='"+ids+"'", con);

then it depends on , what is index of perticular field in that table.like if pro_id,pro_name,description,pro_img,price is your 1st,2nd,3rd,7th,20th coloum in your table in database then the indexing will be.
[0],[1],[2],[7],[20].
and you will be write.


SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
lblpro_id.Text = dr[0].ToString();
lblpro_name.Text = dr[1].ToString();
description.Text = dr[2].ToString();
pro_img.Text= dr[7].ToString();
lblprice.Text = dr[20].ToString();
}
}
dr.Close();
con.Close();

I hope that will help you!
Enjoy coding!
   
Comments
sathiyak 24-Nov-11 0:44am
   
here all is fine but for the image we cant give like"pro_img.Text= dr[7].ToString();"it is wrong........i want soln for that one.....instead of text we shoule give other one.......
jeet786 24-Nov-11 1:26am
   
yes you are right, but i am try to clear the Above error logic.when this error comes.
"Index was out of the bound of the array"
Hi Sathya,
I hope this is working fine try it.

SqlConnection connection = new SqlConnection("your connectionstring");
SqlDataReader reader = null;
try

{
connection.Open();
string sql = "select pro_id,pro_name,description,price from Post where pro_id='" + ids + "'";
SqlCommand command = new SqlCommand();
command.CommandText = sql;
command.Connection = connection;
reader = command.ExecuteReader();

while (reader.Read())
{
lblpro_id.Text = dr[0].ToString();
lblpro_name.Text = dr[1].ToString();
description.Text = dr[2].ToString();
pro_img.Text = dr[7].ToString();
lblprice.Text = dr[20].ToString();
}
}
catch (SqlException ex)
{
Console.WriteLine(String.Format("An exception occurred" +
" : {0}. Please contact your system administrator.",
ex.Message));
}
finally
{
if (reader != null) reader.Close();
if (connection != null) connection.Close();
}
   
hi, i also have the problem of Index was outside the bounds of the array. but i don't understand how to amend the above solution in my case. the message error is System.IndexOutOfRangeException {"Index was outside the bounds of the array. Here is the code:

<pre>    Public Function sensorWithinRange() As MicrosensorStruct()

        Dim arrMicrosensor() As MicrosensorStruct                               '
        Dim dblNearestStation As MicrosensorStruct                              '
        Dim intStationCounter As Integer                                        'Counter for stations
        Dim dblStationE As Double                                               'Easting coords of one station
        Dim dblStationN As Double                                               'Northing coords of one station
        Dim intNearestSensor As Integer                                         '
        Dim strNearestSensor() As String                                        '
        Dim intA, intB, IntMaxIndex As Integer                                  '
        Dim dblMaxValue As Double                                               '
        Dim sMax, sTemp As MicrosensorStruct                                    '
        Dim strTextOut As String                                                '

        Dim strArrColumns() As String                                           'Columns within 1 station record
        Dim chrArrDelim() As Char = " ,".ToCharArray()                          'File delimiter

        Dim sReader As IO.StreamReader
        Dim strRecord As String

        intStationCounter = -1
        intNearestSensor = 0
        dblStationE = CDbl(txtEasting.Text)
        dblStationN = CDbl(txtNorthing.Text)

        sReader = IO.File.OpenText(txtFilename.Text)
        strRecord = sReader.ReadLine()

        strRecord = sReader.ReadLine()

        Do While (Not sReader.EndOfStream)

            strRecord = sReader.ReadLine()
            intStationCounter = (intStationCounter + 1)

        Loop

        sReader.Close()

        Dim intNrStations As Integer                                            'Total number of station
        ReDim arrMicrosensor(intNrStations)

        sReader = IO.File.OpenText(txtFilename.Text)
        strRecord = sReader.ReadLine()
        dblNearestStation.dblRngeDist = Double.PositiveInfinity

        For intStationCounter = 0 To intNrStations - 1
            strRecord = sReader.ReadLine()
            strArrColumns = strRecord.Split(chrArrDelim)

            arrMicrosensor(intStationCounter).lngID = CLng(strArrColumns(0))
            arrMicrosensor(intStationCounter).strOUTCORP = strArrColumns(1)
            arrMicrosensor(intStationCounter).strCode = strArrColumns(2)
            arrMicrosensor(intStationCounter).dblNorthing = CDbl(strArrColumns(3))
            arrMicrosensor(intStationCounter).dblEasting = CDbl(strArrColumns(4))
            arrMicrosensor(intStationCounter).dblRngeDist = CalculateDistance(dblStationN, dblStationE, arrMicrosensor(intStationCounter).dblNorthing, arrMicrosensor(intStationCounter).dblEasting)

            If arrMicrosensor(intStationCounter).dblRngeDist &lt; CDbl(txtRangeDist.Text) Then
                intNearestSensor = intNearestSensor + 1

                'string for text in listbox
                lboNearestStation.Items.Add("STATION ID:" &amp; arrMicrosensor(intStationCounter).lngID.ToString &amp; " , " _
                                    &amp; "REFERENCE CODE:" &amp; arrMicrosensor(intStationCounter).strCode &amp; " , NORTHING:" _
                                    &amp; arrMicrosensor(intStationCounter).dblNorthing.ToString("F") &amp; ", EASTING:" _
                                    &amp; arrMicrosensor(intStationCounter).dblEasting.ToString("F") &amp; ", at:" _
                                    &amp; arrMicrosensor(intStationCounter).dblRngeDist.ToString("F") &amp; "m")

            End If

        Next intStationCounter
        sReader.Close()

        ReDim strNearestSensor(intNearestSensor - 1)

        For intStationCounter = 0 To intNrStations - 1
            If arrMicrosensor(intStationCounter).dblRngeDist &lt; CDbl(txtRangeDist.Text) Then
                intNearestSensor = 0
                strNearestSensor(intNearestSensor) = arrMicrosensor(intStationCounter).strCode
            End If

        Next

        Dim intNum As Integer

        intNum = CInt(txtNrSensor.Text)

        'For intNum = 0 To intNum - 1
        For intNum = 0 To intNum - 1
            For intA = arrMicrosensor.GetUpperBound(0) To 1 Step -1

                sMax = arrMicrosensor(0)
                dblMaxValue = sMax.dblRngeDist
                IntMaxIndex = 0

                For intB = 0 To intA
                    If arrMicrosensor(intB).dblRngeDist &gt; dblMaxValue Then
                        dblMaxValue = arrMicrosensor(intB).dblRngeDist
                        IntMaxIndex = intB

                    End If
                Next intB

                sTemp = arrMicrosensor(intA)
                arrMicrosensor(intA) = arrMicrosensor(IntMaxIndex)
                arrMicrosensor(IntMaxIndex) = sTemp

            Next intA

            strTextOut = arrMicrosensor(intNum).strCode

        Next intNum

        Return arrMicrosensor
    End Function</pre>
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900