Share via

Using Sql Command in C# Visual Studio

WerVardyGestern 1 Reputation point
2022-02-06T19:31:33.957+00:00

Why does the SQL Command not Delete the Data from the Database, in the properties i have already set the sql command text on the Delete Comand. Is the sql Command used rightly?

public Form1()
{
InitializeComponent();
sqlConnection1.Open();
}

    private void recreateXML_Click(object sender, EventArgs e)
    {

        dataSet11.Clear();
        sqlDataAdapter1.Update(dataSet11);

        String filePath = "";
        openFileDialog1.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            filePath = openFileDialog1.FileName;

            dataSet11.ReadXml(filePath);
            sqlCommand1.ExecuteNonQuery();
            sqlDataAdapter1.Update(dataSet11);
        }
    }

    private void updateButton_Click(object sender, EventArgs e)
    {
        sqlDataAdapter1.Update(dataSet11);
    }

    private void deleteButton_Click(object sender, EventArgs e)
    {
        foreach(DataGridViewRow row in dataGridView1.SelectedRows)
        {
            dataGridView1.Rows.Remove(row);
        }
        sqlDataAdapter1.Update(dataSet11);
    }
}

}

Developer technologies | .NET | .NET Machine Learning
Developer technologies | .NET | .NET Machine Learning

.NET: Microsoft Technologies based on the .NET software framework. Machine learning: A type of artificial intelligence focused on enabling computers to use observed data to evolve new behaviors that have not been explicitly programmed.

SQL Server | Other
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


2 answers

Sort by: Most helpful
  1. Sam of Simple Samples 5,586 Reputation points
    2022-02-07T00:35:51.227+00:00

    You are deleting the records in the DataGridView but not the DataSet bound to it. It has been a very long time since I have used a SqlDataAdapter but you need to use the command in the SqlDataAdapter.DeleteCommand Property.

    0 comments No comments

  2. Ken Tucker 5,866 Reputation points
    2022-02-06T20:05:05.793+00:00

    I do not see in your code where you define the update and delete commands for the sql data adapter

    You can use the SQLCommandBuilder class to create the update and delete commands. Of course you could also do it yourself

    https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommandbuilder?view=dotnet-plat-ext-6.0

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.