I am really stuck and non of the books or tread here are user-friendly enough to explain how to delete data from data grid object using C#
from varies of books and fourm threads I have managed to get this coded but it fails to executes the sql command , I have One table call 'SpellingList' and two columns one is ID and the other is Words, all I want to do is delete a row from the datagrid.
Can someone point me to the correct direction , once I solved this , I shall upload some basic easy to follow tutorial so the rest of the newbie can follow this example.
I have used this thread How to delete a selected DataGridViewRow and update a connected database table?
and MCSD Certificaiton Toolkit Exam 70-483 book Page 392 , all attempts have failed.
there is a catch 22 here if I comment out if(dataGridView1.SelectedRows.Count > 0) line , I get the index out of range error .
private void btnDelete_Click(object sender, EventArgs e)
{
// My SQL connectionString
SqlConnection myConnection = new SqlConnection("Data Source=Epic-LaptopWR;Initial Catalog=words;Integrated Security=True");
myConnection.Open();
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if(dataGridView1.SelectedRows.Count > 0)
{
int selectedIndex = dataGridView1.SelectedRows[0].Index;
// gets the RowID from the first column in the grid
int rowID = int.Parse(dataGridView1[0, selectedIndex].Value.ToString());
// your code for deleting it from the database
string sql = "DELETE FROM SpellingList WHERE Words =" + selectedIndex;
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = myConnection;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "@Words";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
deleteRecord.Connection.Close();
wordsDataSet.GetChanges();
// booksDataset1.GetChanges();
spellingListTableAdapter.Fill(wordsDataSet.SpellingList);
}// end of if
// then your code for refreshing the DataGridView
}// end of for each statement
myConnection.Close();
}// end of delete Button