public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlConnection con = new SqlConnection("connstr"); private void button1_Click(object sender, EventArgs e) { int index = dataGridView1.SelectedRows[0].Index; if (dataGridView1.SelectedRows.Count > 0) { using (SqlCommand cmd = con.CreateCommand()) { int id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value); cmd.CommandText = "Delete from [Student] where id='" + id + "'"; con.Open(); cmd.ExecuteNonQuery(); con.Close(); for (int i = index + 1; i < dataGridView1.Rows.Count; i++) { UpdateId(i); } DisplayData(); dataGridView1.Refresh(); //commentbox.Text = "削除しました "; //commentbox.BackColor = Color.Yellow; } } else { //commentbox.Text = "削除する生を選択してください "; //commentbox.BackColor = Color.Yellow; } } private void UpdateId(int id) { con.Open(); string str = string.Format("Update Student set id={0} where id={1} ", id - 1, id); SqlCommand cmd = new SqlCommand(); cmd.CommandText = str; cmd.Connection = con; cmd.ExecuteNonQuery(); con.Close(); } //display private void DisplayData() { con.Open(); DataTable dt = new DataTable(); SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM [Student] ", con); adp.Fill(dt); dataGridView1.DataSource = dt; con.Close(); } private void Form1_Load(object sender, EventArgs e) { DisplayData(); } }