Click here to Skip to main content
15,893,486 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello guys. I am learning C# and I have been unable to get the delete function to work in my code. What could I be doing wrong?

What I have tried:

C#
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 Point_of_sale
{
    public partial class manageUsers : Form
    {
        public manageUsers()
        {
            InitializeComponent();
        }
        SqlConnection Conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\GARNET6\Documents\inventorydb.mdf;Integrated Security=True;Connect Timeout=30");
     
        private void label1_Click(object sender, EventArgs e)
        {
            Application.Exit();

        }
        void populate()
        {
            try
            {
               Conn.Open();
                string Myquerry = "select * from UserTb1";
                SqlDataAdapter da = new SqlDataAdapter(Myquerry, Conn);
                SqlCommandBuilder builder =  new SqlCommandBuilder(da);
                var ds = new DataSet();
                da.Fill(ds);
                UsersGV.DataSource = ds.Tables[0];
                Conn.Close();
                

            }
            catch
            {

            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
           
            try
            {
                Conn.Open();
                SqlCommand cmd = new SqlCommand("insert into UserTb1 values('" + UnameTb.Text + "', '" + FnameTb.Text + "', '" + PasswordTb.Text + "', '" + PhoneTb.Text + "')", Conn);
                cmd.ExecuteNonQuery();
                MessageBox.Show("User sucessfully added");
                Conn.Close();
                populate();


            }

            catch
            {

            }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {
          
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            UnameTb.Text = UsersGV.SelectedRows[0].Cells[0].Value.ToString();
            FnameTb.Text = UsersGV.SelectedRows[0].Cells[1].Value.ToString();
            PasswordTb.Text = UsersGV.SelectedRows[0].Cells[2].Value.ToString();
            PhoneTb.Text = UsersGV.SelectedRows[0].Cells[3].Value.ToString();


        }

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

        private void ManageUsers_Load(object sender, EventArgs e)
        {
            populate();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (PhoneTb.Text == "")
            {
                MessageBox.Show("Proceed to delete?");

            }
            else
            {
                Conn.Open();
                string myquery = "delete from UserTb1 where Upassword '"+PhoneTb.Text+"'";
                SqlCommand cmd = new SqlCommand(myquery, Conn);
                cmd.ExecuteNonQuery();
                MessageBox.Show("User successfully deleted");
                Conn.Close();
                populate();
            }
        }


    }
}
Posted
Updated 13-Jan-22 8:07am
v2
Comments
CHill60 13-Jan-22 4:50am    
First you need to tell us what is actually happening. Do you get an error message?
Next you need to use parameterised queries - your code is vulnerable to SQL Injection attack because of this line
string myquery = "delete from UserTb1 where Upassword '"+PhoneTb.Text+"'";
bravian 13-Jan-22 4:57am    
hi. I get a System.NotImplementedException error
CHill60 13-Jan-22 5:26am    
On which line??
bravian 13-Jan-22 5:33am    
this line in the manageUser.Design.cs file

this.UsersGV.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);
CHill60 13-Jan-22 9:27am    
That line isn't in the code you shared. So this is nothing to do with your delete function in button3_Click!

You need to change this line
string myquery = "delete from UserTb1 where Upassword '"+PhoneTb.Text+"'";

To
string myquery = "delete from UserTb1 where UName = '"+UnameTb.Text + "'";


Your Query is vulnerable to SQL Injection Attack, please see OWASP Top Ten vulnerabilities for a detailed overview of security vulnerabilities.

You also need to know that we have assumed that UName is the User Name column in your UserTB1 table. If this name is incorrect please change UName to the Field name that corresponds to the User Name field.
 
Share this answer
 
Comments
bravian 14-Jan-22 4:31am    
After i changed the code i got this error
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')'
You've already gotten the solution, so I will just add that I encourage you to use Visual Studio's Data Designer to create your queries. The basic insert, update, and delete queries are automatically (and correctly) created for you. You then use a dataset as your in-memory database, table adapters to load the dataset from the database, and binding sources to connect your forms to your database (via the dataset).

Microsoft's ADO is a little like "The toe bone's connected to the foot bone, The foot bone's connected to the ankle bone, The ankle bone's connected to the leg bone," but it works really well once you get the hang of it.

As for the injection attacks, here's what they mean. If instead of their name, someone typed into the text box "; DROP TABLE Users;" that would delete your Users table (assuming you had such a table). Using table adapters will get around this, but you're just learning, so I wouldn't worry about it too much right now. Just keep it in mind.
 
Share this answer
 

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