C# asp.net 错误:无法将类型“对象”隐式转换为“字符串”。存在显式转换(您是否缺少演员表?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18468046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
asp.net error: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
提问by user2721914
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?
我想使用 select WHERE 语句从 sql server 中名为 hotel 的表中检索数据,但出现上述错误。任何人都可以帮忙吗?
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"]);
}
回答by Habib
Change
改变
this.txtHotel.Text = (dsRow["RoomsAvailable"]);
To
到
this.txtHotel.Text = (dsRow["RoomsAvailable"].ToString());
回答by Allan Elder
Or change to
或更改为
this.txtHotel.Text = dsRow["RoomsAvailable"] as string;
and you won't get an exception if the value is null.
如果值为空,您将不会收到异常。
回答by sk2185
Try this Code
试试这个代码
this.txtHotel.Text = Convert.ToString (dsRow["RoomsAvailable"]);
回答by Paddyd
回答by Suraj Singh
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 ?
并且this.DropDownList1.Text
将获取你选择的值不是文本。你只是给出HotelNames
了dropdown
值吗?
and for error Try
和错误尝试
Convert.ToString(dsRow ["RoomsAvailable"]);