private void myDataGridView_CellContentClick(object sender,
DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (e.RowIndex >= 0)
{
string celval = senderGrid.Rows[e.RowIndex].Cells[0].Value.ToString();
}
}
private void delete_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Do You Want delete selected Row?",
"Important",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
connetionString = @"Data Source=DESKTOP-1SAGJQ9\SQLEXPRESS;Initial Catalog=StudentEnroll;User
ID=sa;Password=sa";
connection = new SqlConnection(connetionString);
string query1 = "delete StudentDetails where id='" + celval + "'";
connection.Open();
command = new SqlCommand(query1, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show(" Student Details Deleted Succesfuly !!");
DisplayData();
}
else
{
MessageBox.Show("Please select a row");
}
}
Asked
Active
Viewed 36 times
-5

halfer
- 19,824
- 17
- 99
- 186
-
1This code has far more serious problems than the attempt to read a cell value in the wrong place, in the wrong way. It leaks connections and is wide open to SQL injection. Just imagine what would happen if that cell contained `'; DELETE TABLE Student;--'`. Using the `sa` login means nothing would stop a malicious user from doing any damage they want – Panagiotis Kanavos Aug 09 '22 at 11:07
-
You can [get the selected cell or rows using the correct properties](https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/selected-cells-rows-and-columns-datagridview?view=netframeworkdesktop-4.8). A DataGridView isn't a data *container* though, only a UI element. Its data should be supplied by *binding* to a DataTable or list of items. Instead of trying to read values from the grid, you can [read them from the selected data item](https://stackoverflow.com/questions/2084976/datagridview-get-current-selected-object) – Panagiotis Kanavos Aug 09 '22 at 11:09
1 Answers
0
You dont need to declare the global variable celval , you can directly get it in delete button
for that you need to set your DataGridView as MultiSelect = false; and SelectionMode = FullRowSelect;
private void delete_Click(object sender, EventArgs e)
{
if (senderGrid.SelectedRows.Count > 0)
{
string celval = senderGrid.SelectedRows[0].Cells["yourColumnName"].Value.ToString();
if (celval!="")
{
// do your delete
}
}
}

Sund'er
- 666
- 1
- 4
- 11