asp.net 错误:无法将类型"对象"隐式转换为"字符串"。存在显式转换(您是否缺少强制转换?



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

更改

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

相关内容

最新更新