简体   繁体   English

如何检查MS Access数据库文件中是否已存在ID,以及如何在TextBox中使用TextChanged进行检查?

[英]How to check if ID already exists in MS Access database file, and how to check it by using TextChanged in TextBox?

I am working on part of my program where I am deleting entry by using provided Entry ID. 我正在处理我的程序的一部分,我正在使用提供的条目ID删除条目。

As of right now I am deleting any entry specified by user. 截至目前,我正在删除用户指定的任何条目。 This works great but, what I am trying to do is to inform user that there is no such ID to delete. 这很好,但我想要做的是告知用户没有这样的ID要删除。 Also, I am using textbox TextChanged which let me to check for certain things in user input while user is typing. 此外,我正在使用文本框TextChanged ,它允许我在用户输入时检查用户输入中的某些内容。

Now, how do I check if Entry ID already exists? 现在,如何检查条目ID是否已存在? What should I include in my if statement to do this? 我应该在if语句中包含哪些内容来执行此操作?

Also, is there a way I could check that by using TextChanged event handler? 另外,有没有办法通过使用TextChanged事件处理程序检查? I'm not sure about that because I know that if I would have opening and closing connection in TextChanged event, then connection would be opened/closed every time user is typing, so I don't think this is a good idea . 我不确定,因为我知道如果我在TextChanged事件中打开和关闭连接,那么每次用户输入时都会打开/关闭连接, 所以我认为这不是一个好主意 But how can I avoid this and so I can do this in real time? 但是我怎么能避免这种情况,所以我可以实时做到这一点? Perhaps when user stop typing, and then take a second or two to check for entry id? 也许当用户停止输入,然后花一两秒来检查输入ID?

This is a code of my delete entry window: 这是我删除条目窗口的代码:

public partial class DeleteEntryWindow : Form
{
    string user, pass, filePath;

    // Initializing MainWindow form.
    MainWindow mainWindow;

    public DeleteEntryWindow()
    {
        InitializeComponent();

        txtEntryID.TextChanged += new EventHandler(ValidateInput);
    }

    public DeleteEntryWindow(MainWindow viaParameter, 
        string user, string pass, string filePath)
        : this()
    {
        mainWindow = viaParameter;
        this.user = user;
        this.pass = pass;
        this.filePath = filePath;
    }

    private void ValidateInput(object sender, EventArgs e)
    {
        int intNumber;

        if (!string.IsNullOrEmpty(txtEntryID.Text) &&
            int.TryParse(txtEntryID.Text, out intNumber) &&
            intNumber > 0)
        {
            lblMessage.Text = "Entry ID is valid.";
            lblMessage.ForeColor = Color.Green;
            btnDeleteEntry.Enabled = true;
        }
        else
        {
            lblMessage.Text = "You must enter Entry ID number!";
            lblMessage.ForeColor = Color.IndianRed;
            btnDeleteEntry.Enabled = false;
        }
    }

    private void btnDeleteEntry_Click(object sender, EventArgs e)
    {
        DialogResult result = MessageBox.Show
            ("Are you sure you want to remove this entry?",
            "Information", MessageBoxButtons.YesNo,
            MessageBoxIcon.Information);

        if (result == DialogResult.Yes)
        {
            // SQL query which will delete entry by using entry ID.
            string sql = "DELETE FROM PersonalData WHERE DataID = " +
                txtEntryID.Text;

            DeleteData(sql);

            lblMessage.Text = "Entry was deleted!";
            lblMessage.ForeColor = Color.Green;
        }
        else
        {
            // Do nothing.
        }
    }

    private void DeleteData(string sql)
    {
        HashPhrase hash = new HashPhrase();

        string hashShortPass = hash.ShortHash(pass);

        // Creating a connection string. Using placeholders make code
        // easier to understand.
        string connectionString =
            @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};
              Persist Security Info=False; Jet OLEDB:Database Password={1};";

        using (OleDbConnection connection = new OleDbConnection())
        {
            // Creating command object.
            // Using a string formatting let me to insert data into
            // place holders I have used earlier.
            connection.ConnectionString =
                string.Format(connectionString, filePath, hashShortPass);

            using (OleDbCommand command = new OleDbCommand(sql, connection))
            {
                OleDbParameter prmDataID = new OleDbParameter
                    ("@DataID", txtEntryID.Text);

                command.Parameters.Add(prmDataID);

                try
                {
                    connection.Open();
                    command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
        }
    }
}

To check if the ID already exists, you will need to use SQL just as your delete method does. 要检查ID是否已存在,您将需要像删除方法一样使用SQL。 The following may give you a starting point: 以下可能为您提供一个起点:

private bool DoesIDExist(string ID)
{
    string filePath = ""; //TODO
    string hashShortPass = ""; //TODO
    DataTable temp = new DataTable();
    bool result = false;
    string connectionString =""; //TODO

    using (OleDbConnection connection = new OleDbConnection(ConnectionString))
    {

            string sql = @"SELECT * FROM PersonalData WHERE DataID = @DataID";


            using (OleDbCommand command = new OleDbCommand(sql, connection))
            {
                command.Parameters.Add(new OleDbParameter("@DataID", ID));

                using (OleDbDataAdapter oda = new OleDbDataAdapter(command))
                {
                    try
                    {
                        oda.Fill(temp);

                        if (temp != null && temp.Rows.Count > 0)
                            result = true; //ID exists

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message);
                    }
                }
            }
    }
return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM