我有一個dgv控件﹐它的數据源是一個BindingSource控件(bsPartList)﹐當我刪除最后一行時﹐會拋出异常(如下圖)﹐我跟蹤刪除代碼﹐發現最后一行刪除完成后﹐其dgv.Rows.Count的值為1,而bsPartList.Count的值為0.(但是當表中有多行記錄時﹐刪除完成后﹐這兩個值是一樣的)﹐為會么為這樣子﹖
具体刪除代碼如下﹒
private void tsbDelete_Click(object sender, EventArgs e)
{
if (dgvPartList.Rows.Count == 0)
{
MessageBox.Show("沒有可刪除的記錄!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
dgvPartList.Rows[bsPartList.Position].Selected = true;
string strPartID = dgvPartList.CurrentRow.Cells["colPartID"].Value.ToString().Trim();
if (MessageBox.Show("您确定要刪除物料編號為\" " + strPartID + " \"的記錄嗎﹖", "詢問", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes)
{
SqlCommand cmd = new SqlCommand("Part_Delete", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@partID", SqlDbType.NVarChar, 18);
cmd.Parameters["@partID"].Value = strPartID;
cmd.Parameters.Add("@errorMsg", SqlDbType.NVarChar, 200);
cmd.Parameters["@errorMsg"].Direction = ParameterDirection.Output;
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
try
{
bsPartList.EndEdit();
cmd.ExecuteNonQuery();
bsPartList.RemoveCurrent();
bsPartList.EndEdit();
}
catch
{
string strMsg = cmd.Parameters["@errorMsg"].Value.ToString();
MessageBox.Show(strMsg, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
}
}