Click here to Skip to main content
15,903,385 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear All,
Following error encountered while reading dropdown from MS SQL server database table
Invalid attempt to read when no data is present.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Source Code:
C#
ob.constr();
        string str1 = "SELECT id,floorno,roomno,rate FROM tblRateMaster WHERE floorno='" + DropDownFloor.Text + "'";
        SqlCommand cmd1 = new SqlCommand(str1, ob.con1);
        SqlDataReader dr1 = cmd1.ExecuteReader();

            dr1.Read();
            txtRegRoomNo.Text = dr1["roomno"].ToString();
            txtRegRate.Text = dr1["rate"].ToString();
                 
        
        ob.con1.Close();




Exception Details: System.InvalidOperationException: Invalid attempt to read when no data is present.

Source Error:


Line 52:
Line 53: dr1.Read();
Line 54: txtRegRoomNo.Text = dr1["roomno"].ToString();
Line 55: txtRegRate.Text = dr1["rate"].ToString();
Line 56:

Source File: e:\LiveProject\AdminDreamPanel_HMS\Admin\index.aspx.cs Line: 54

What I have tried:

Invalid attempt to read when no data is present.
Posted
Updated 4-Jan-22 5:04am
v2

1 solution

Two things:
1) Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

2) You don't check the result of the Read method call to check if any rows are returned - since none are, there is no data to access and you get an error.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900