Reputation: 7
I have the following code, but I can't seem to manipulate it to work the way I want. I would like to have the command search the data base for the first entry in the database that matches textbox2.text
and delete the row.
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DillPickle\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From ACCNT where ACCNTNUM=" + textBox2.Text , con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
ACCNT."txtbox2.text".Rows[0].Delete();
}
else
{
MessageBox.Show("The account does not exist in the record!");
}
}
Upvotes: 0
Views: 139
Reputation: 3777
There's many ways to accomplish what you are trying to do; here's one way:
private readonly string SqlConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DillPickle\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30";
private readonly string SqlDeleteQuery = "DELETE FROM ACCNT WHERE ACCNTNUM=@accountNumber";
private void button4_Click(object sender, EventArgs e)
{
try
{
using (var sqlConnection = new SqlConnection(SqlConnectionString))
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlConnection.Open();
sqlCommand.CommandText = SqlDeleteQuery;
sqlCommand.Parameters.AddWithValue("@accountNumber", textBox2.Text);
sqlCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// Do something with the exception, like log it...
}
}
Upvotes: 1