C# Error: Index was outside the bounds of the array
Solution 1
The dr1[x]
value relates to the position of the column it has read from the database.
The SQL you specify SELECT amount FROM contribution_master
will return the amount
column, however the data in this can only be accessed either using dr1[0]
or dr1["amount"]
.
while (dr1.Read())
will iterate through each row of data in a loop until there is no more. However, if you need to access each row specifically, you might be better off filling the data into a datatable and assigning the values from there.
For example:
SqlDataAdapter da = new SqlDataAdapter(SQLCmd1);
DataTable dt = new DataTable();
da.Fill(dt);
employer_epf = Convert.ToDouble(dt.Rows[0][0].ToString());
employer_admin = Convert.ToDouble(dt.Rows[1][0].ToString());
employer_edli = Convert.ToDouble(dt.Rows[2][0].ToString());
employer_admin_edli = Convert.ToDouble(dt.Rows[3][0].ToString());
employer_esi = Convert.ToDouble(dt.Rows[4][0].ToString());
Hopefully this helps, but would it not be easier to have the axis of your table the other way around?
Solution 2
You're only returning one field from your query (amount) so there is only one field in the datareader (field 0)
Each call to datareader.Read()
returns a single row. If you want subsequent rows, call Read()
again.
So, in your code...
if (dr1.Read())
{
employer_epf = Convert.ToDouble(dr1[0].ToString());
if (dr1.Read())
{
employer_admin = Convert.ToDouble(dr1[0].ToString());
// etc...
}
}
Or you can populate a DataTable
that will return all the rows at once.
user1557308
Updated on June 27, 2022Comments
-
user1557308 almost 2 years
i am getting an "Index was outside the bounds of the array." at dr1[1].ToString().
I have table contribution_master with 3 columns: type_id (int), name (varchar(20), amount (float). I want to extract all the amount rows.
SqlConnection SQLCon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["PayrollConnStr"].ConnectionString.ToString()); SqlCommand SQLCmd1 = new SqlCommand("SELECT amount FROM contribution_master", SQLCon1); try { SQLCon1.Open(); SqlDataReader dr1 = SQLCmd1.ExecuteReader(); while (dr1.Read()) { employer_epf = Convert.ToDouble(dr1[0].ToString()); employer_admin = Convert.ToDouble(dr1[1].ToString()); employer_edli = Convert.ToDouble(dr1[2].ToString()); employer_admin_edli = Convert.ToDouble(dr1[3].ToString()); employer_esi = Convert.ToDouble(dr1[4].ToString()); } } catch (SqlException ex) { string errorMessage = "Error "; errorMessage += ex.Message; lblWarn.Text = errorMessage; lblWarn.Visible = true; } finally { SQLCon1.Close(); }