4

我想使用 select WHERE 语句从名为 hotel 的 sql server 表中检索数据,但出现上述错误。任何人都可以帮忙吗?

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

5 回答 5

7

改变

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

this.txtHotel.Text = (dsRow["RoomsAvailable"].ToString());
于 2013-08-27T14:21:24.610 回答
2

或更改为

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

如果值为空,您将不会得到异常。

于 2013-08-27T14:25:22.583 回答
1

试试这个代码

 this.txtHotel.Text = Convert.ToString (dsRow["RoomsAvailable"]);
于 2013-08-27T14:26:43.940 回答
0

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

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

文档

于 2013-08-27T14:39:06.840 回答
0

好吧,我看到了这段代码

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

并将this.DropDownList1.Text获取您选择的值而不是 text 。只是你给出HotelNamesdropdown价值观吗?

并为错误尝试

Convert.ToString(dsRow ["RoomsAvailable"]);
于 2013-08-27T14:39:26.913 回答