What is causing a system beep?
-
15-06-2021 - |
Domanda
This is what I'm using to allow the enter button to start the search. It works but causes a system beep. I have no idea why.
private void searchbox_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
searchbutton.PerformClick();
}
else
{
//Run.
}
}
It happens as soon as I press enter and not some other line in the code. Thoughts on what I'm missing?
Here is searchbutton_Click:
private void searchbutton_Click(object sender, EventArgs e)
{
var searchvar = searchbox.Text;
SqlParameter var1 = new SqlParameter(@"var1", SqlDbType.Text);
var1.Value = "%" + searchvar + "%";
var conn = new SqlConnection("Data Source=TX-MANAGER;Initial Catalog=Contacts;Integrated Security=True");
var comm = new SqlCommand(@"SELECT [Name ID], First, Last, Address, City, State, ZIP FROM contacts WHERE (First LIKE @var1) OR (Last LIKE @var1)", conn);
if (checkBox1.Checked == true)
{
comm.CommandText += "ORDER BY ZIP";
}
else
{
//Run.
}
try
{
comm.Parameters.Add(var1);
conn.Open();
comm.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}
catch (Exception e1)
{
display_box.Text = e1.ToString();
tabControl1.Focus();
}
finally
{
int rowcount = dataGridView1.RowCount - 1;
count.Text = rowcount.ToString();
tabControl1.SelectedTab = tabPage2;
}
}
Soluzione
You could try adding e.Handled = true;
to the KeyPressed
event for your TextBox
.
Normally, if your Form
doesn't have its AcceptButton
property set, a system beep is played when hitting Enter inside a TextBox
. The beep indicates that there's no default button defined for your Form
.
Altri suggerimenti
Add the following event handler (in addition to KeyUp
):
private void searchbox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
e.Handled = true;
}
That is, subscribe to the KeyPress
event and when Enter
is pressed, set e.Handled
to true
. I just tested this on my machine and it worked; it removed the beep.