5

I want to retrieve data from a table in sql server called hotel using select WHERE statement and I get the above error. Can anyone help?

SqlConnection cnn = new
        SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT RoomsAvailable FROM Hotel WHERE HotelName = '" + 
                    this.DropDownList1.Text + "'";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Hotel");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow dsRow = null;
foreach (DataRow dsRow_loopVariable in ds.Tables["Hotel"].Rows)
{
    dsRow = dsRow_loopVariable;
    //This line is where the error comes in.
    this.txtHotel.Text = (dsRow["RoomsAvailable"]);
}
2
  • 3
    Have you tried dsRow["RoomsAvailable"].ToString() ? Commented Aug 27, 2013 at 14:21
  • 1
    Change dsRow["RoomsAvailable"] to dsRow["RoomsAvailable"].ToString() Commented Aug 27, 2013 at 14:21

5 Answers 5

10

Change

this.txtHotel.Text = (dsRow["RoomsAvailable"]);

To

this.txtHotel.Text = (dsRow["RoomsAvailable"].ToString());
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Habib. I encountered this issue while converting from ASP Classic to VB.NET to C#. Everything worked well in the three conversations until I got to this one. Thank you.
2

Or change to

this.txtHotel.Text = dsRow["RoomsAvailable"] as string;

and you won't get an exception if the value is null.

Comments

1

Try this Code

 this.txtHotel.Text = Convert.ToString (dsRow["RoomsAvailable"]);

Comments

0

dsRow["RoomsAvailable"] Is an object of type DataRow, if you want the String value you need to call ToString():

this.txtHotel.Text = (dsRow["RoomsAvailable"].ToString());

Docs

Comments

0

Well i saw this code

cmd.CommandText = "SELECT RoomsAvailable FROM Hotel WHERE HotelName = '" + 
                    this.DropDownList1.Text + "'";

and this.DropDownList1.Text will fetch you selected value not text . just have you given HotelNames as dropdown values ?

and for error Try

Convert.ToString(dsRow ["RoomsAvailable"]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.