asp.net error: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

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"]); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!