asp.net错误:无法隐式转换类型';对象';到';字符串';.存在显式转换(是否缺少强制转换

本文关键字:转换 显式转换 存在 字符串 是否 对象 类型 net asp 错误 | 更新日期: 2023-09-27 18:29:15

我想使用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"]);
}

asp.net错误:无法隐式转换类型';对象';到';字符串';.存在显式转换(是否缺少强制转换

更改

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

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

或更改为

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

如果值为null,则不会得到异常。

尝试此代码

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

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

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

单据

我看到了这个代码

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

并且CCD_ 3将获取您所选择的值而不是文本。你只是把HotelNames作为dropdown的值吗?

和错误尝试

Convert.ToString(dsRow ["RoomsAvailable"]);
相关文章: