Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
I've created a code that allows the user to sign in (still work in progress) and then add patient records to a database that is displayed in a datagridview. I'm needing the delete button to delete the selected row in the datagridiew and save that to the database. Right now my code runs but it's not actucally deleting anything.

Heres my code:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Reports
{
public partial class ReportsForm : Form
{
public ReportsForm()
{
InitializeComponent();
}

private void ReportsForm_Load(object sender, EventArgs e)
{
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\RecordsDatabase.mdf;Integrated Security=True;Connect Timeout=30";

SqlConnection con = new SqlConnection(connectionString);

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Database_tbl", con);

DataSet ds = new DataSet();

da.Fill(ds, "Database_tbl");

RecordsdataGridView.DataSource = ds.Tables["Database_tbl"].DefaultView;

// TODO: This line of code loads data into the 'recordsDatabaseDataSet.Database_tbl' table. You can move, or remove it, as needed.
this.database_tblTableAdapter.Fill(this.recordsDatabaseDataSet.Database_tbl);

}

private void DisplayData()

{
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\RecordsDatabase.mdf;Integrated Security=True;Connect Timeout=30";

SqlConnection con = new SqlConnection(connectionString);

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Database_tbl", con);

DataSet ds = new DataSet();

da.Fill(ds, "Database_tbl");

RecordsdataGridView.DataSource = ds.Tables["Database_tbl"].DefaultView;
}

private void btnSubmit_Click(object sender, EventArgs e)
{
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\RecordsDatabase.mdf;Integrated Security=True;Connect Timeout=30";


SqlConnection con = new SqlConnection(connectionString);

con.Open();

SqlCommand cmd = new SqlCommand("INSERT INTO Database_tbl (EntryDate, ReportText) VALUES ('" + DateTime.Now + "','" + txtReports.Text + "')", con);


cmd.ExecuteNonQuery();

con.Close();

MessageBox.Show("Report Successfully Added");

DisplayData();

txtReports.Text = "";

}

private void RecordsdataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (RecordsdataGridView.Columns[e.ColumnIndex].Name == "Edit")
{

int rowIndex = RecordsdataGridView.CurrentCell.RowIndex;

txtReports.Text = RecordsdataGridView.Rows[rowIndex].Cells[2].Value.ToString();

lblRowID.Text = RecordsdataGridView.Rows[rowIndex].Cells[0].Value.ToString();


btnUpdate.Visible = true;

btnSubmit.Visible = false;

}

if (RecordsdataGridView.Columns[e.ColumnIndex].Name == "Cancel")

{

txtReports.Text = "";
}

else if (RecordsdataGridView.Columns[e.ColumnIndex].Name == "Delete")

{
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\RecordsDatabase.mdf;Integrated Security=True;Connect Timeout=30";


DialogResult result = MessageBox.Show("Are you sure you want to delete this patient report?", "Conformation", MessageBoxButtons.YesNo);

if (result == DialogResult.Yes)
{

SqlConnection con = new SqlConnection(connectionString);

SqlCommand cmd = new SqlCommand("DELETE FROM Database_tbl WHERE EntryID = @EntryID ", con);

con.Open();
cmd.Parameters.AddWithValue("@EntryID", lblRowID.Text);
cmd.ExecuteNonQuery();
con.Close();

DisplayData();
}

else if (result == DialogResult.No)

{
return;
}
}
}


private void btnUpdate_Click(object sender, EventArgs e)
{
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\RecordsDatabase.mdf;Integrated Security=True;Connect Timeout=30";


SqlConnection con = new SqlConnection(connectionString);

con.Open();

using (SqlCommand cmd = new SqlCommand("Update Database_tbl set ReportText = @ReportText Where EntryID = @EntryID", con))
{

cmd.Parameters.AddWithValue("@ReportText", txtReports.Text);

cmd.Parameters.AddWithValue("@EntryID", lblRowID.Text);

cmd.ExecuteNonQuery();
}

con.Close();


MessageBox.Show("Report Successfully Updated");

DisplayData();
txtReports.Text = "";
}

private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}

What I have tried:

I have tried this which it does work and while the applicatin is running it will delete the selected row. However, it doesn't save it to the database so when the application is ran again the selected row that was deleted is back.

Code:

DialogResult result = MessageBox.Show("Are you sure you want to delete this patient report?", "Conformation", MessageBoxButtons.YesNo);

if (result == DialogResult.Yes)

{
int rowIndex = RecordsdataGridView.CurrentCell.RowIndex;

RecordsdataGridView.Rows.RemoveAt(rowIndex);
else if (result == DialogResult.No)

{
return;
}
Posted
Comments
[no name] 28-Apr-20 13:42pm    
Your "grid" has no knowledge of any database. You retrieved some data and loaded a grid; the 2 are independent. Since there is some Sql "DELETE" code there, I'm assuming you copied but do not understand what you copied. Lots of duplicated code.
Member 14802172 28-Apr-20 16:16pm    
I'm not quite sure what you mean by my "grid" has no knowledge of any database. I can submit information into my code and edit it. I'm just having trouble figuring out the delete button. I created this application from the ground up. I've had to teach myself most of what you see by watching videos and reading forms. I'm still very new to this. Hence why I asked a question in the first place. If you have better knowledge of what I should be doing please explain so I can learn. It's not the nicest looking code I know that but I'm doing the best I can. Thank you.
Sinisa Hajnal 29-Apr-20 6:00am    
You shouldn't concatenate in the INSERT statement, you're using parameters in other queries.
Did you try a) set a breakpoint and see if lblID.Text contains the value b) try..catch around execute non-query to see if something breaks (you should actually have it all around the code c) what is the returning value of ExecuteNonQuery (i.e. does ID exists and it tries to delete correct record)

Finally, you should call close and dispose in finally block so you don't get memory leaks on exceptions.
Richard Deeming 29-Apr-20 9:00am    
Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

Particularly worrying given the mention of "patient records". Unless this is a toy application for a school project, be prepared to face an enormous fine for not securing your data properly!
Jassom 10-May-20 22:09pm    
Make sure that you use the right parameter of the patient ID you going to delete, is this parameter (lblRowID.Text) is the right ID for the record you going to delete.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900