我想使用删除按钮从datagridview中删除所选行,但是我选择的行将不会被删除,第一行 数据网格被删除。谢谢您的指教
这些是按钮代码:
private void button1_Click(object sender, EventArgs e)
{
if (dgcontact.CurrentRow != null)
{
if (MessageBox.Show("...", "...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int personID = Convert.ToInt32(dgcontact.CurrentRow.Cells[0].Value.ToString());
repository.delete(personID);
}
}
}
这是一种删除方法:
public bool delete(int personID)
{
string connectionstring = "data source=.;initial catalog=person;integrated security=true";
string query = "delete from tperson where personID=@personID";
SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@personID", personID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
return true;
}
答案 0 :(得分:0)
不要使用CurrentRow,只需遍历SelectedCells
using System.Linq;
if (MessageBox.Show("...", "...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int selectedPersonId = dgcontact.SelectedCells.Cast<DataGridViewCell>()
.Where(cell => cell.OwningColumn.Index.Equals(1))
.Select(cell => Convert.ToInt32(cell.Value)).First();
repository.delete(selectedPersonId);
}