我有一个程序写入Access数据表,然后信息显示在数据网格中。当文本框中出现一个6位数字后跟"L"
时会触发此操作。
我在代码中"TextBox1.Clear();"
清除了6个数字,但不是"L"
。
这是我的代码:
private void Registration_Main(object sender, KeyPressEventArgs e)
{
SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
Object returnValue;
Object returnName;
string txtend = textBox1.Text;
if (e.KeyChar == 'L')
{
DBConnection.Open();
}
if (DBConnection.State == ConnectionState.Open)
{
if (textBox1.Text.Length != 6) return;
{
cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =@Name");
cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(@"L", "")));
cmd.CommandType = CommandType.Text;
cmd.Connection = DBConnection;
returnValue = cmd.ExecuteScalar() + "\t " + textBox1.Text.Replace(@"L", "");
returnName = cmd.ExecuteScalar();
DBConnection.Close();
AccessDB_Connection(returnName);
}
textBox1.Clear();
}
}
private void AccessDB_Connection(object returnName)
{
String varID;
Object varName;
varID = textBox1.Text.Replace(@"L", "").ToString();
varName = returnName;
OleDbConnection OLEDB_Connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Test Applications\\Tablet Registration - Access Database\\Tablet Registration - Access\\Tablet Registration - Access\\Registration.accdb");
OleDbCommand updateCmd = new OleDbCommand();
try
{
updateCmd.CommandText = "INSERT INTO TestDB ([Name], [ID]) VALUES (@NAME, @ID)";
updateCmd.Parameters.AddWithValue("@NAME", varName);
updateCmd.Parameters.AddWithValue("@ID", varID);
OLEDB_Connection.Open();
updateCmd.Connection = OLEDB_Connection;
updateCmd.ExecuteNonQuery();
this.testDBTableAdapter.Fill(this.registrationDataSet1.TestDB);
OLEDB_Connection.Close();
}
catch
{
}
}
非常感谢任何帮助!
答案 0 :(得分:2)
尝试从以下位置更新您的代码:
if (e.KeyChar == 'L')
{
DBConnection.Open();
}
到
if (e.KeyChar == 'L')
{
e.Handled = true;
DBConnection.Open();
}
这应该会阻止事件传播并填充文本框。