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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:17:40  来源:igfitidea点击:

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

c#asp.net

提问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

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

dsRow["RoomsAvailable"]是一个类型的对象DataRow,如果你想要 String 值,你需要调用 ToString():

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

Docs

文档

回答by Suraj Singh

Well i saw this code

好吧,我看到了这段代码

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

and this.DropDownList1.Textwill fetch you selected value not text . just have you given HotelNamesas dropdownvalues ?

并且this.DropDownList1.Text将获取你选择的值不是文本。你只是给出HotelNamesdropdown值吗?

and for error Try

和错误尝试

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