【问题标题】:Finding Records in a Database using a Textbox and Button使用文本框和按钮在数据库中查找记录
【发布时间】:2011-09-29 22:23:31
【问题描述】:

我一直在向tutorial on Home and Learn 学习有关设置数据库的知识。目前,我正在学习如何在数据库中查找记录。我正在努力让我的 GO!按钮在我的数据表中搜索一种成分,我已经彻底按照教程进行操作,并且我的错误列表中没有错误,但是这行代码:

returnRows = dataRecipe.Tables["CookBookRecipes"].Select("Ingredients = '" + searchOut + "'");

它会停止我的程序,并显示以下消息:

对象引用未设置为 对象的实例。

我已经搜索过含义,我猜这意味着我的 returnRows 变量为空,但我不能确定。有人可以帮我解决这个问题吗?

这是我的“搜索”按钮中的完整代码:

System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter dataAdapt;
DataSet dataRecipe;

private void btnSearch_Click(object sender, EventArgs e)
{

    if (tbSearch.TextLength >= 1)
   {
        MessageBox.Show("This will work when you put it a word!");

        // Search code //

        string searchOut = tbSearch.Text;
        int result = 0;
        DataRow[] returnRows;

        returnRows = dataRecipe.Tables["CookBookRecipes"].Select("Ingredients = '" + searchOut + "'");


        result = returnRows.Length;

        if (result > 0)
        {
            DataRow rowBack;
            rowBack = returnRows[0];
            MessageBox.Show(rowBack[3].ToString());
        }
        else
        {
            MessageBox.Show("No such record");
        }

   }

   else
    {
       MessageBox.Show("Please enter an ingredient to search for!", "Search");
   }
}

这是我的表单的完整代码:

using System; 
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Cookbook {
    public partial class BrowseIngredients : Form {
       public BrowseIngredients() { InitializeComponent(); }
       private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
           if (MessageBox.Show("Exit Cook Book?", "Exit?", MessageBoxButtons.OKCanc

我是一个初学者,如果我不明白真正的问题,请原谅我!

【问题讨论】:

  • 您能否发布将 CookBookRecipes 数据表添加到 dataRecipe 数据集的代码。

标签: c# database search


【解决方案1】:

看起来您可能没有实例化您的数据集。您声明了它,但您没有实例化它,除非您在代码中的其他地方执行它,而您没有向我们展示。

DataSet dataRecipe;

您可以在页面加载事件中将其实例化,这样就可以了。

private void Form_Load(object sender, EventArgs e)
{
    dataRecipe = new DataSet();
}

【讨论】:

    【解决方案2】:

    看看你正在使用的教程,我想我可以看出你哪里出错了(我不怪你——教程并不完全清楚)。

    基于这个阶段:http://www.homeandlearn.co.uk/csharp/csharp_s12p5.html

    您将在您的表单加载方法中有如下语句:

    string sql = "SELECT * From CookBookRecipes";
    dataAdapt = new System.Data.SqlClient.SqlDataAdapter(sql, con);
    

    但是,本教程然后告诉您添加以下内容以将数据从数据适配器获取到数据集中,但实际上并未在上下文中显示代码 - 我怀疑这是您出错的地方。

    您需要在上述行之后立即添加:

    dataAdapt.Fill( dataRecipe, "CookBookRecipes" );
    

    然后,当您尝试从 dataRecipe.Tables["CookBookRecipes"] 获取行时,您将不会返回对空对象的引用。

    【讨论】:

    • 成功了,谢谢!愚蠢的我,我有那个代码,但出于某种原因我把它注释掉了......再次感谢!
    • @C Wong - 没问题。我已经编码了 30 年,但仍然在做这种愚蠢的事情 :)
    猜你喜欢
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    相关资源
    最近更新 更多