4

这是我的桌子:

roomtype, number of rooms
Ac        10

我想从表中检索值并将房间减去 1 并更新上表。如何使用 C# 在 ASP.NET 中编写检索代码?

这是更新的代码。说dt.Rows[0]["no_of_rooms"] > 1对象类型不能与int. 但是在将这个 no_of_rooms 解析为 int 时,错误保持不变。

public partial class Book_Room : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        string type = DropDownList1.SelectedItem.ToString();
        string name = TextBox2.Text;
        string nop = DropDownList2.SelectedItem.ToString();
        int num = int.Parse(nop);
        string connectionString = WebConfigurationManager.ConnectionStrings["HMSConnectionString"].ConnectionString;
        SqlConnection connection = new SqlConnection(connectionString);

        string qry3 = "select * from availiability where RoomType=@type";
        SqlCommand cmd3 = new SqlCommand(qry3, connection);
        cmd3.Parameters.AddWithValue("@type", type);
        cmd3.ExecuteReader();
        SqlDataAdapter ad = new SqlDataAdapter(cmd3);
        DataTable dt = new DataTable();
        if (dt.Rows.Count > 0)
        {    
            if (dt.Rows[0]["no_of_rooms"] > 1)
            {
                string qry = "insert into RoomType values('" + type + "','" + name + "','" + num + "') ";
                SqlCommand cmd = new SqlCommand(qry, connection);
                connection.Open();
                int g = cmd.ExecuteNonQuery();
                if (g != 0)
                    Label5.Text = "Reserved for" + name;
                connection.Close();

                string qry2 = "update availiability set RoomType=@type ,availiable_rooms=@av";
                SqlCommand cmd2 = new SqlCommand(qry2, connection);
                cmd2.Parameters.AddWithValue("@type", type);
                cmd2.Parameters.AddWithValue("@av", dt.Rows[0]["no_of_rooms"] - 1);
                connection.Open();
                cmd2.ExecuteNonQuery();
                connection.Close();
            }
        }

        else
        {
            label5.Text = "No Rooms Availiable in " + type;
        }
    }
}
4

3 回答 3

3

或者你可以试试

dt.Rows[0].Field<int>("no_of_rooms")>1

于 2013-10-14T16:59:32.223 回答
3

把它改成这个(int)dt.Rows[0]["no_of_rooms"] > 1

于 2013-10-14T16:53:23.887 回答
2

You are not using any of the other values returned from your query, so creating a SqlDataAdapater and filling a Table is a bit much.

I would recommend using ExecuteScalar instead. This returns a single value from the database.

string qry3 = "select * from availiability where RoomType=@type";
SqlCommand cmd3 = new SqlCommand(qry3, connection);
cmd3.Parameters.AddWithValue("@type", type);
object objCount = command.ExecuteScalar();
int count = objCount == null ? 0 : (int)objCount;
if (count > 0)
{
    // Do other things
}
于 2013-10-14T17:07:09.093 回答