C# 未将对象引用设置为对象的实例

标签 c# asp.net sql-server

我正在从网站上执行预约功能。它可以在创建新约会之前比较日期和时间,如果数据库中存在用户键入相同的日期和时间,则会弹出消息框。当我尝试插入与数据库不同的不同日期和时间时,它给我错误。 Error

我在这一行遇到错误:

string dtime = time.ExecuteScalar().ToString();

我不知道我的代码有什么问题,有人可以指出我吗?谢谢。 这是我的代码:

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.Configuration;
using System.Windows.Forms;
public partial class MakeAppointment : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
    string appointmentdate = Convert.ToString(DropDownListDay.Text + "-" + DropDownListMonth.Text + "-" + DropDownListYear.Text);
    string appointmenttime = Convert.ToString(DropDownListHour.Text + ":" + DropDownListMinute.Text + ":" + DropDownListSecond.Text + " " + DropDownListSession.Text);

    SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
    con.Open();
    SqlCommand date = new SqlCommand("Select adate from customer_registration where adate='"+ appointmentdate +"'",con);
    string ddate = date.ExecuteScalar().ToString();
    con.Close();
    if (ddate == appointmentdate)
    {
        con.Open();
        SqlCommand time = new SqlCommand("Select atime from customer_registration where atime='"+ appointmenttime +"'", con);
        string dtime = time.ExecuteScalar().ToString();
        con.Close();

        if (dtime == appointmenttime)
        {
            MessageBox.Show("This appointment is not available. Please choose other date & time.");
        }
}
}

最佳答案

ExcuteScalar(); 似乎有问题,因为当查询不存在记录时它返回 null

你可以这样使用

   var data= date.ExecuteScalar();
   if(data!=null)
         ddate =data.ToString();

详情

ExecuteScalar throws NullReferenceException

关于C# 未将对象引用设置为对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14181847/

相关文章:

sql-server - 我应该使用 SqlGeometry 还是 SqlGeography?

asp.net - 将 System.windows.Forms 引用添加到 asp.net 网站

c# - ListView 控件

c# - 此linq查询能否更有效?

c# - 这段代码在做什么?

asp.net - 使用 ASP.Net 缓存客户端图像

asp.net - 一个 .aspx 页面中有两个表单标记

SQL Join on where 条件

sql - 使用变量和索引的 T-SQL LIKE

c# - 交换技巧 : a=b+(b=a)*0;