need to retrieve data and convert to int for IF statement

weirdwolf

New member
Joined
Oct 1, 2015
Messages
1
Programming Experience
Beginner
Okay so, i'm currently trying to read some data from my access database file, to convert it to an int and then use it for an IF statement, but right now if i try to load it i get a "no data in row/column" error, and im not quite sure why.
C#:
[/COLOR][COLOR=#333333]int Niv = 0;[/COLOR]
        try
        {
            conn.Open();
            OleDbDataReader reader = null;
            OleDbCommand cmd = new OleDbCommand("Select Niveau From Tabel1 where ID=" + txt_userID.Text + "", conn);
            reader = cmd.ExecuteReader();
            Niv = Convert.ToInt32(reader["Niveau"].ToString());
            conn.Close();
            MessageBox.Show(Niv.ToString());
        }
        catch(Exception ex) 
[FONT=Verdana]             { MessageBox.Show(ex.Message); }[/FONT][FONT=Verdana]
[/FONT]
 
After creation, a data reader is positioned before the first row of data. You have to call Read to advance it to that first row and then Read again to advance to subsequent rows. Every example on the web that uses a data reader would show that.

There are a couple of other points worth noting with regards to that code too.

1. This:
OleDbCommand cmd = new OleDbCommand("Select Niveau From Tabel1 where ID=" + txt_userID.Text + "", conn);
should be something like this:
OleDbCommand cmd = new OleDbCommand("Select Niveau From Tabel1 where ID=@ID", conn);

cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(txt_userID.Text);
2. This:
Niv = Convert.ToInt32(reader["Niveau"].ToString());
should be something like this::
Niv = reader.GetInt32(reader.GetOrdinal("Niveau"));
If the data represents an integer then it should be stored as an integer and retrieved as an integer, not converted to a String and then to an Int32.
 
Back
Top Bottom