I have to read an sql table with about 100 columns and then check each cell to verify if the data is not null. Using SQLReader it throws me an IndexOutOfBoundsOfArrway exception at column no 70. Any ideea how shold I reach my goal?
P.S. I am doing this in c#
This is my code:
conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand( "select * from tableName where column1='" +
textBox1.Text+"'", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
for (int i = 3; i < 100; i++)
{
if (reader[i].ToString() != "")
{
listBox2.Items.Add(reader[i].ToString());
}
}
}
EDIT: I am sure that my table has 100 column, but reader.FieldCount is equal to 70
Try this more dynamic approach, it will work no matter the amount of columns:
You might also want to consider moving the null check out of the actual reading procedure since looping through the columns takes a considerable amount of time and your blocking the reader while you do so.
However depending on the amount of rows your reading in this might introduce new challenges in regards to memory consumption.
UPDATE
In order to avoid retrieving each column separately by index, use the
GetValues()batch operation of theDataReaderinstead that returns an object array of all values, also if you expect just one line, use if rather than while to avoid issues: