使用 asp.net 和 c# 在文本框上进行会话

Session on Textbox with asp.net and c#

我正在尝试在 asp.net 中的文本框上进行会话,该文本框允许用户输入 1-4 之间的值,但每当我单击按钮 "book" 时,它都会给出我是一个空指针异常,我正在使用 C# 后端的 FindControl 函数。

这是我的代码 .aspx 页面

<%@ Page Title="" Language="C#" MasterPageFile="~/Main.Master" AutoEventWireup="true" CodeBehind="hotels_main.aspx.cs" Inherits="Hotel_Mangement.hotels_main" %>
<asp:Content ID="Content1" ContentPlaceHolderID="hotels_main" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<meta name="keywords" content="free website templates, hotel and travel, CSS, XHTML, design layout" />
<meta name="description" content="Hotel and Travel - free website template provided by templatemo.com" />
<link href="/css/templatemo_style.css" rel="stylesheet" type="text/css" />

    <div id="templatemo_container">
    <!-- Free Website Template by www.TemplateMo.com -->
   <div id="templatemo_content">

        <div id="content_left" style="background-color:#2C3E50">
            <div class="content_left_section">
                <div class="content_title_01">Confirm Your Booking</div>
                    <form id="form1" >

                      <div class="form_row">


                          <br /><br />

                          <big>Check in:</big>
                          <asp:Calendar ID="checkin" runat="server" OnDayRender="checkin_DayRender" ></asp:Calendar>
                          <br /><br />

<big>Check out:</big>&nbsp;&nbsp;<asp:Calendar ID="checkout" runat="server" OnDayRender="checkout_DayRender1" ></asp:Calendar>

                          <br /><br />
                           <big>Number of room:</big>&nbsp;&nbsp;<asp:TextBox ID="rooms" runat="server"   ForeColor="black" placeholder="Number of rooms" type="number" min="1" max="2"></asp:TextBox>


                          <br /><br />
                           <big>Number of members per room:</big>&nbsp;&nbsp;<asp:TextBox ID="members" runat="server"   ForeColor="black" placeholder="Number of members" type="number" min="1" max="4"></asp:TextBox>
                         <br /> <br />

                          &nbsp;&nbsp;&nbsp;&nbsp;<asp:Button ID="book" runat="server" Text="Book" ForeColor="Black" Width="200px" Height="30px" OnClick="book_Click"></asp:Button>
                      </div>

                <div class="cleaner">&nbsp;</div>
            </div> <!-- end of booking -->

            <div class="cleaner_h30">&nbsp;</div>
            <div class="cleaner_horizontal_divider_01">&nbsp;</div>
            <div class="cleaner_h30">&nbsp;</div>

            <div class="content_left_section">
            <div class="content_title_01">Contact Details</div>

                <div class="news_title">Address</div>
                    <p>The Taj Mahal Palace<br />Apollo Bunder, Near Gateway Of India, Colaba , Mumbai , Maharashtra , India<br />Pincode- 400001</p>
                <div class="cleaner_h30">&nbsp;</div>

                <div class="news_title">Phone</div>
                    <p>022 6665 3366 </p>
                <div class="cleaner_h20">&nbsp;</div>

                <div class="news_title">Email Support</div>
                <p>reservations@tajhotels.com</p>

                </div>   <!-- end of news section -->
                <div class="cleaner_h30">&nbsp;</div>

            <div class="cleaner_horizontal_divider_01">&nbsp;</div>
            <div class="cleaner_h30">&nbsp;</div>


          <div class="cleaner_h30">&nbsp;</div>
        </div> <!-- end of content left -->

             <asp:Repeater ID="Repeater1" runat="server">     
                 <ItemTemplate>
        <div id="content_right">

            <div class="content_right_section">

                <div class="content_title_01">Welcome to The <asp:Label ID="lblhotelname" runat="server" Text='<%#Eval("hotel_name") %>'></asp:Label> </div>
           <asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("ImagePath") %>'  Height="200px"  width="200px"/>
                <p><%#Eval("d_desc") %>. </p>
          </div>


            <div class="cleaner_h40">&nbsp;</div>

            <div class="content_right_2column_box">
                <div class="content_title_01">Hotel Facilities</div>


                   <p> <%#Eval("hotel_facilties") %></p>



            </div>

            <div class="content_right_2column_box">
                <div class="content_title_01">Policies</div>     

                <ul>
                  <asp:Label ID="lblpolicies" runat="server" Text='<%#Eval("hotel_policies") %>'></asp:Label> 
                  </ul>


                <div class="cleaner_h10">&nbsp;</div>

            </div>    

            <div class="cleaner_h40">&nbsp;</div>


            <div class="content_right_section">
                <div class="content_title_01">Hotel location</div>
                <asp:Label ID="Label1" runat="server" Text='<%#Eval("hotel_location") %>'></asp:Label>
                    <div class="cleaner_h20">&nbsp;</div>


                    <div class="cleaner">&nbsp;</div>
            </div>  

             <div class="content_right_section">
                <div class="content_title_01">Hotel price per room</div>


                 <asp:FormView ID="FormView1" runat="server"></asp:FormView>
                                       <asp:Label ID="lblhotelprice" runat="server" Text='<%#Eval("price")%>'></asp:Label>




                    <div class="cleaner_h20">&nbsp;</div>


                    <div class="cleaner">&nbsp;</div>
            </div>                    
            <div class="cleaner_h20">&nbsp;</div>
        </div> <!-- end of content right -->

 </ItemTemplate>
</asp:Repeater>


</div> 

</div>
</asp:Content>

.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace Hotel_Mangement
{
    public partial class hotels_main : System.Web.UI.Page
    {

        int id;
        int t1main, t2main, totalmain;
        public static List<DateTime> list = new List<DateTime>();


        SqlConnection con = new SqlConnection(@"Data Source=RISHIK\SQLEXPRESS;Initial Catalog=Register;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] == null)
            {
                Response.Redirect("hotels.aspx");
            }
            else
            {

                id = Convert.ToInt32(Request.QueryString["id"].ToString());
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from hotels_main where hotel_id=" + id + "";
                cmd.ExecuteNonQuery();
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                Repeater1.DataSource = dt;
                Repeater1.DataBind();
                con.Close();

            }

        }

        protected void checkin_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date < DateTime.Now.Date)
            {
                e.Day.IsSelectable = false;
                e.Cell.ForeColor = System.Drawing.Color.Red;
                e.Cell.Font.Strikeout = true;
            }
            Session["checkinmain"] = list;
        }

        protected void checkout_DayRender1(object sender, DayRenderEventArgs e)
        {

            if ((e.Day.Date < DateTime.Now.Date) || (e.Day.Date < checkin.SelectedDate))
            {
                e.Day.IsSelectable = false;
                e.Cell.ForeColor = System.Drawing.Color.Red;
                e.Cell.Font.Strikeout = true;
            }
            Session["checkoutmain"] = list;
        }

        protected void book_Click(object sender, EventArgs e)
        {

            if (Session["USER_ID"] == null)
            {
                Response.Redirect("login.aspx");
            }
            else
            {
                TextBox rooms = (TextBox)FindControl("rooms");
                Session["roomsmain"] = rooms.Text;
                TextBox members = (TextBox)FindControl("members");
                Session["membersmain"] = members.Text;
                Label lblhotelprice = (Label)FindControl("lblhotelprice");
                Session["initialprice"] = lblhotelprice.Text;
                t1main = Convert.ToInt32(Session["roomsmain"].ToString());
                t2main = Convert.ToInt32(Session["initialprice"].ToString());
                totalmain = t1main * t2main;
                Session["totalpricemain"] = totalmain;


                con.Open();

                string insertQuery = "insert into hotel_booking_details(username,hotel_name,hotel_location,check_in,check_out,members,rooms,initial_price,total_price) values('" + Session["USER_ID"].ToString() + "','" + Session["hotel_name"].ToString() + "','" + Session["hotel_location"].ToString() + "','" + Session["checkinmain"].ToString() + "','" + Session["checkoutmain"].ToString() + "','" + Session["membersmain"].ToString() + "','" + Session["roomsmain"].ToString() + "','" + Session["initialprice"].ToString() + "','" + Session["totalpricemain"].ToString() + "')";

                SqlCommand cmd1 = new SqlCommand(insertQuery, con);
                cmd1.ExecuteNonQuery();
                con.Close();
                Response.Redirect("pay.aspx");

            }

        }

     }
    }

首先,您不能在ASP.Net中使用其他表单标签。您将需要删除 <form id="form1" >

it gives me an null pointer exception, I am using FindControl function from my c# backend.

TextBox rooms = (TextBox)FindControl("rooms");

关于代码试图在 Page[ 中找到 rooms 文本框控制。房间控件不是页面控件的直接子

您将需要递归查找控件。这是辅助方法 -

public static Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
        return root;

    return root.Controls.Cast<Control>()
        .Select(c => FindControlRecursive(c, id))
        .FirstOrDefault(c => c != null);
}

用法

TextBox rooms = (TextBox)FindControlRecursive(Page, "rooms");