0

別のフォームのボタンを押して、あるフォームの datagridview からレコードを削除したい。しかし、私はnullreferenceexception was unhandledエラーが発生しています。私はc#が初めてなので、誰かが私に正しいコードを書いてくれたら本当に感謝しています.

これが私がこれまでに得たものです。

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@" Data Source=HOME-D2CADC8D4F\SQL;Initial Catalog=motociclete;Integrated Security=True");

    SqlCommand cmd = new SqlCommand();
    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        DataGridViewRow dr = dataGridView1.Rows[i];
        if (dr.Selected == true)
        {
            dataGridView1.Rows.RemoveAt(i);
            try
            {
                con.Open();
                cmd.CommandText = "Delete from motociclete where codm=" + i + "";
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
    this.Close();
}
4

5 に答える 5

0

すべての行をループするのはなぜですか。dataGridView1.SelectedRows を使用します。

for (int i = dataGridView1.SelectedRows.Count - 1; i >= 0; i--)
    dataGridView1.Rows.Remove(dataGridView1.SelectedRows[i]);

また、DataTable と BindingSource を使用してデータをバインドします。

于 2013-05-18T20:46:41.590 に答える
0
private void button1_Click(object sender, EventArgs e)
{  int row =-1;   

      SqlConnection con = new SqlConnection(@" Data Source=HOME-D2CADC8D4F\SQL;Initial Catalog=motociclete;Integrated Security=True");

    SqlCommand cmd = new SqlCommand();
    row = new_tab_Object.CurrentCell.RowIndex;

            if (row!= (-1))
            {

                new_tab_Object.Rows.RemoveAt(row);                
                row = -1;
            try
            {
                con.Open();
                cmd.CommandText = "Delete from motociclete where codm=" + row + "";
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

    this.Close();
  }

あなたのこれ...

于 2013-05-18T20:16:03.023 に答える
0

行を繰り返し処理しながら行をNullPointerException削除しています。これは、行を削除するとカウントが変化しますが、最初のカウントまでループが続くためです。

それを行う1つの方法は、行の一時的なリストを作成し、後でそれらを削除することです:

List<DataGridViewRow> rowstodelete = new List<DataGridViewRow>();

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    DataGridViewRow dr = dataGridView1.Rows[i];
    if (dr.Selected)
    {
        rowstodelete.Add(dr);
        try
        {
              con.Open();
              cmd.CommandText = "Delete from motociclete where codm=" + i + "";
              cmd.ExecuteNonQuery();
              con.Close();
         }
         catch (Exception ex)
         {
               MessageBox.Show(ex.ToString());
         }
    }
}

foreach (DataGridViewRow row in rowstodelete)
{
    dataGridView1.Rows.Remove(row);
}
于 2013-05-18T19:38:25.293 に答える