0

Hi

I want to store value from a row into a variable.

I have used the following coding but it is not working properly.

It is generating the following error:

Index was outside the bounds of the array.System.Data

Please note that the table contains only one row.

objSqlConnection.ConnectionString = connectionStringSetting;
            try
            {
                objSqlConnection.Open();
                SqlCommand objSqlCommand = new SqlCommand("select FineCharges from FINECHARGES where FineID = 1", objSqlConnection);
                SqlDataReader objDataReader = objSqlCommand.ExecuteReader();
                int ChargeFine; 
                while (objDataReader.Read())
                {
                    ChargeFine = Convert.ToInt32(objDataReader[1].ToString());
                    MessageBox.Show("Fine" + Convert.ToString(ChargeFine));
                }
                objSqlConnection.Close();
            }
            catch (SqlException e1)
            {
                MessageBox.Show(e1.Message + e1.Source);
                objSqlConnection.Close();
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message + e2.Source);
                objSqlConnection.Close();
            }

Can anybody tell me what is the error?

Please help me out!

Thanks in advance!

2
Contributors
1
Reply
5
Views
7 Years
Discussion Span
Last Post by adamdk
0

If you are only reading one row from one column, you would be better to use

int myVariable = (int) mySqlCommand.ExecuteScalar();

(might have to use int.parse I cannot remember)

Scalar takes only 1 value from 1 row

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.