I went through many threads here, I also found a few threads related to what I need, but none worked. So please if anyone can check if there's any mistake in my code or tell me what exactly I should do...
Actually I am able to view the data which is present in the database in a datagrid, now what I exactly want is to delete the selected fields from datagrid as well as database, by pressing the delete button.
Here's my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Marketing_Resource
{
    public partial class frmMainForm : Form
    {
        public frmMainForm()
        {
            InitializeComponent();
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void btnAddData_Click(object sender, EventArgs e)
        {
            frmAddExcel tempfrm = new frmAddExcel();
            tempfrm.ShowDialog();
        }

        private void btnShowAllData_Click(object sender, EventArgs e)
        {
            string executableName = Application.ExecutablePath;
            FileInfo executableFileInfo = new FileInfo(executableName);
            string parentName = executableFileInfo.Directory.Parent.FullName;
            executableName = parentName;
            executableFileInfo = new FileInfo(executableName);
            parentName = executableFileInfo.Directory.Parent.FullName;
            SqlConnection DBCon = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=" + parentName + "\\Marketing Resource\\Students.mdf;Integrated Security=True;User Instance=True");
            SqlDataAdapter da;
            try
            {
                string qry = "select * from StudentDetails";
                int i = 0;
                da = new SqlDataAdapter(qry, DBCon);
                DataSet ds = new DataSet();
                da.Fill(ds, "stud");
                dataGridView1.DataSource = ds.Tables[0].DefaultView;
            }
            catch (Exception ex)
            {
                lblCheck.Text = ex.Message;
            }
            finally
            { DBCon.Close(); }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {

        }

        private void frmMainForm_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1_Object.Items.Remove(dataGridView1_Object.SelectedIndex); 
        }

       
    }
}

right click to your datagrid and select properties, click to events section and select delete event from there, it will add the delete event handler to your codebehind page, then you can implement your deletion code there. if this is not clear enough, tell me and i will provide you with some code.

Thank for your help, but am still not able to delete the records from the database, I think there's some mistake in my deletion code....

I am using this code..

private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1_Object.Items.Remove(dataGridView1_Object.SelectedIndex); 
        }

Please tell me what wrong in this code or what code should I use?

i couldnt find the server explorer in visual c# 2008 express edition, so i can not provide you with the code, but you are deleting the row from the grid not from the database. you need to raise datagrid delete event then handle that event.

I am unable to raise datagrid delete event then handle that event, I think my Deletion code is wrong.

You are deleting the information from the DataGrid, you're not even touching the database.

I suggest you make create a stored procedure and then call forth that procedure in your datagridview.

For instance, what I do is make a column with a button. So, when that button is clicked I check for the row the button is in and pass the number i to the stored procedure deletion.

I am not getting what exactly I should write, I tried a many things but none worked :(

I am not getting what exactly I should write, I tried a many things but none worked :(

if you wait at the end of today , i will be able to provide you with working sample, i need to fill 8 hours at work first ...

ok ready to show you

forms1.cs :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // i am creating a datatable for the datasource of the gridview, you wont need this portion as you retrieve the 
        // data from database
       

        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("column1");
            dt.Columns.Add("column2");
            dt.Rows.Add(new object[]{"1","2"});
            dt.Rows.Add(new object[] { "3", "4" });
            dataGridView1.DataSource = dt;
        }

        private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            // here the important part is to get the row's primary key so we can handle the deletion operation

            MessageBox.Show(((DataRowView)e.Row.DataBoundItem)["column1"].ToString());

            // here i want to cancel the deletion

            e.Cancel = true;

            // your deletion code will be implemented here 


        }
        
    }
}

form1.designer.cs :

namespace WindowsApplication6
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // dataGridView1
            // 
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dataGridView1.Location = new System.Drawing.Point(0, 0);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(606, 433);
            this.dataGridView1.TabIndex = 0;
            this.dataGridView1.UserDeletingRow += new System.Windows.Forms.DataGridViewRowCancelEventHandler(this.dataGridView1_UserDeletingRow);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(606, 433);
            this.Controls.Add(this.dataGridView1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView dataGridView1;
    }
}

Hello,

I have the same problem as sid.coco. I am using VS2005 and connected to a MySQL database using the wizzard (did not manage to connect manually, maybe some incompatibility between Vista and VS2005 or MySQL); the entries are viewed using a dataGridView.

I have no problem inserting values into my table using the following code:

DataRow myNewRow;
            myNewRow = mydatabaseDataSet.test.NewRow();
            myNewRow[0] = Convert.ToInt32(textBox1.Text);
            myNewRow[1] = textBox2.Text;
            mydatabaseDataSet.test.Rows.Add(myNewRow);
            dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1];
            testTableAdapter.Update(mydatabaseDataSet.test);

,but i can't seem to manage to delete entries from my table. They dissapear from the dataGridView but are still present in the database table. I am using the following code:

DataRow Linie;
                int index = dataGridView1.CurrentCell.RowIndex;
                Linie = mydatabaseDataSet.test.Rows[index];
                dataGridView1.Rows.RemoveAt(index);
                //Linie.Delete();

            this.mydatabaseDataSet.test.AcceptChanges();
            testTableAdapter.Update(mydatabaseDataSet.test);

I have also tried using Serkan's code, but did not understand what exactly the code is after "// your deletion code will be implemented here ".

Does anybody have any other ideas?

Thank you for your time!

Hello,

I have the same problem as sid.coco. I am using VS2005 and connected to a MySQL database using the wizzard (did not manage to connect manually, maybe some incompatibility between Vista and VS2005 or MySQL); the entries are viewed using a dataGridView.

I have no problem inserting values into my table using the following code:

DataRow myNewRow;
            myNewRow = mydatabaseDataSet.test.NewRow();
            myNewRow[0] = Convert.ToInt32(textBox1.Text);
            myNewRow[1] = textBox2.Text;
            mydatabaseDataSet.test.Rows.Add(myNewRow);
            dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1];
            testTableAdapter.Update(mydatabaseDataSet.test);

,but i can't seem to manage to delete entries from my table. They dissapear from the dataGridView but are still present in the database table. I am using the following code:

DataRow Linie;
                int index = dataGridView1.CurrentCell.RowIndex;
                Linie = mydatabaseDataSet.test.Rows[index];
                dataGridView1.Rows.RemoveAt(index);
                //Linie.Delete();

            this.mydatabaseDataSet.test.AcceptChanges();
            testTableAdapter.Update(mydatabaseDataSet.test);

I have also tried using Serkan's code, but did not understand what exactly the code is after "// your deletion code will be implemented here ".

Does anybody have any other ideas?

Thank you for your time!

the question for this thread was different, so i didnt show the deletion implementation for that solution. In your case all you need to do is to delete rows from your data element, which is your dataset, then commit the changes back to your database using update method. what you are doing in your code is you are deleting rows from the gridview which only changes GUI of the application.

Hello,

Shouldn't the following statement do an update for the database?

testTableAdapter.Update(mydatabaseDataSet.test);

If yes, then it doesn't; not even for updating a field of the table.

I have managed to create a query with the VS wizzard, but in the given situation can only delete all entries at once, and do not have the posibility to delete a selected entry.

Thank you for the quick reply.

if i were you, i would read some ADO.NET tutorials from ASP.NET website. or just search google with ADO.NET tutorial.

This article has been dead for over six months. Start a new discussion instead.