Sql c#对象引用未设置为对象错误的实例,尝试匹配文本框和数据库值

Sql c#对象引用未设置为对象错误的实例,尝试匹配文本框和数据库值,sql,database,compiler-errors,Sql,Database,Compiler Errors,我的代码中有一个小问题,我试图将我的文本框值与数据库匹配,但我收到一条错误消息 这是我的密码: 我的主要代码 protected void btnAddNewTopic_Click(object sender, EventArgs e) { if (txtbAddNewTopic.Text == "") { MessageBox.Show("Please write topic!"); } else

我的代码中有一个小问题,我试图将我的文本框值与数据库匹配,但我收到一条错误消息

这是我的密码:

我的主要代码

 protected void btnAddNewTopic_Click(object sender, EventArgs e)
    {
        if (txtbAddNewTopic.Text == "")
        {
            MessageBox.Show("Please write topic!");
        }
        else if (goodob.Businness_Layer.AddNewTopic.NewTopicCheckSystem(txtbAddNewTopic.Text) == null)
        {
            MessageBox.Show("Your added topic is already in site!");
        }
        else
        {
            goodob.Businness_Layer.CreateNewTopic.crnewtopic(txtbAddNewTopic.Text);
            MessageBox.Show("Your topic has successfully created!");
        }



    }
和我的支票代码

 public static goodob.Businness_Layer.AddNewTopic NewTopicCheckSystem(string topic)
    {
        goodob.Businness_Layer.AddNewTopic xyz = null;

        string query = @"SELECT [topic_name] 
                       FROM topic
                       WHERE topic_name = @topic";

        goodob.Class1 connection1 = new goodob.Class1();
        connection1.sqlcommand.CommandText = query;

        SqlParameter topicparam = new SqlParameter("@topic_name", SqlDbType.VarChar);
        topicparam.Value = topic;

        connection1.sqlcommand.Parameters.Add(topic);

        System.Data.SqlClient.SqlDataReader reader = connection1.sqlcommand.ExecuteReader();

        if (!reader.HasRows)
        {
            connection1.close_connection();
            return null;
        }




        return xyz;
    }

我在connection1.sqlcommand.CommandText=query中得到一个错误;请帮帮我

您在添加参数时太混乱了,应该添加sqlparameter对象,即topicparam而不是topic

在两个位置都使用@topic varible

或者你也可以试试这个速记

cmd.Parameters.AddWithValue(“@topic”,topic)

代替

 SqlParameter topicparam = new SqlParameter("@topic_name", SqlDbType.VarChar);
    topicparam.Value = topic;

    connection1.sqlcommand.Parameters.Add(topic);

我这样做了,但仍然得到了一条错误消息:(我得到了一条消息,这个错误消息在connection1.sqlcommand.CommandText=query;程序没有传递这个语句…无论我做什么,我都会得到错误消息…我想我的错在这个语句中,如果(goodb.Businness\u Layer.AddNewTopic.NewTopicCheckSystem(txtbAddNewTopic.Text)==null)