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;
                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));
            catch (SqlException e1)
                MessageBox.Show(e1.Message + e1.Source);
            catch (Exception e2)
                MessageBox.Show(e2.Message + e2.Source);

Can anybody tell me what is the error?

Please help me out!

Thanks in advance!

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.