如何检查值是否存在于数据库中从textbox c# [英] how to check if value exists in database from textbox c#

查看:651
本文介绍了如何检查值是否存在于数据库中从textbox c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定,所以我有一个文本框和一个按钮,我将输入一个数字,然后按按钮。然后,我想要一个消息框,如果值已找到或没有显示。

ok so i have a text box and a button where i will enter a number and press the button. I then want a message box to display if the value has been found or not.

我把所有的函数放在一个模型类中,然后调用它们的GUI部分。
heres我试过这样的sql函数(ticket是表的名称,ID是我试图找到的值):

I put all my functions in a model class then call them for the GUI part. heres what i tried so the sql function (ticket is the name of the table and ID is the value im trying to find):

  public void rebateslip(int ticketID)
    {
        SqlCommand myCommand  = new SqlCommand("SELECT ID FROM ticket WHERE ID = @ticketID", con);
        SqlDataAdapter sqlDa = new SqlDataAdapter(myCommand);

        myCommand.Parameters.AddWithValue("@ID", ticketID);


    }

有这个:

 private void buttonPrintRebateSlip_Click(object sender, EventArgs e)
    {

            if (textBoxRebateSlip = model.rebateslip(ticketID)
            {
                MessageBox.Show("Found ticket");
            }
            else
            {
                MessageBox.Show("Ticket not in database");
            }

    }

但它表示ticketID不存在

but it says ticketID does not exist

推荐答案

您应该更改 model.rebateslip 方法,以便它返回一个 bool ,并执行你的命令,那么它应该看起来更多或更少这样:(没有SqlCommand方法,而根据我的记忆,看起来像这样)

you should change your model.rebateslip method so that it return a bool, and execute your command, then it should look more or less like this: (don't have the SqlCommand methods in mind, nor the reader's ones, but according to my memory it looks like this)

public bool rebateslip(int ticketID)
{
    SqlCommand myCommand  = new SqlCommand("SELECT ID FROM ticket WHERE ID = @ticketID", con);
    SqlDataAdapter sqlDa = new SqlDataAdapter(myCommand);

    myCommand.Parameters.AddWithValue("@ticketID", ticketID);
    var reader = myCommand.Execute();
    return reader.HasRows;    
}

那么你应该做一些像@Ezekiel在他的回答中说:

then you should do something like @Ezekiel said in his answer:

int id;
if (!int.TryParse(textBoxRebateSlip.Text, out id)) return;

if (model.rebateslip(id))
...

这篇关于如何检查值是否存在于数据库中从textbox c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆