提供されたエントリ ID を使用してエントリを削除するプログラムの一部に取り組んでいます。
現在、ユーザーが指定したエントリを削除しています。これはうまく機能しますが、私がやろうとしているのは、削除する ID がないことをユーザーに通知することです。また、TextChanged
ユーザーが入力している間にユーザー入力の特定のものをチェックできるテキストボックスを使用しています。
では、エントリ ID が既に存在するかどうかを確認するにはどうすればよいですか? if
これを行うには、ステートメントに何を含める必要がありますか?
TextChanged
また、イベント ハンドラーを使用してそれを確認する方法はありますか? TextChanged
イベントで接続を開いたり閉じたりすると、ユーザーが入力するたびに接続が開いたり閉じたりすることがわかっているので、それについてはわかりません。しかし、どうすればこれを回避でき、リアルタイムでこれを行うことができますか? おそらく、ユーザーが入力をやめてから、1、2 秒かけてエントリ ID を確認したときでしょうか?
これは私のエントリ削除ウィンドウのコードです:
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);
}
}
}
}
}