可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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"]); }
回答1:
Change
this.txtHotel.Text = (dsRow["RoomsAvailable"]);
To
this.txtHotel.Text = (dsRow["RoomsAvailable"].ToString());
回答2:
Or change to
this.txtHotel.Text = dsRow["RoomsAvailable"] as string;
and you won't get an exception if the value is null.
回答3:
Try this Code
this.txtHotel.Text = Convert.ToString (dsRow["RoomsAvailable"]);
回答4:
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
回答5:
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"]);