C# datagridview 删除行(转 学会、放弃博客)

原文引入:http://zhangyanyansy.blog.163.com/blog/static/13530509720106171252978/

 

datagridview 删除行  

2010-07-17 13:25:29|  分类: C#|字号 订阅

 
 

 private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            #region Shift多行删除
            if (this.dgvAdmin.SelectedRows.Count > 0)
            {
                if (MessageBox.Show("确定要该管理员的信息吗?", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Del();
                }                
            }
            else
            {
                MessageBox.Show("请选择要删除的信息!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            #endregion
        }

 

public bool DelUser(int adminId)
        {
            bool result = false;
            try
            {
                string sql = "delete from Admin where AdminId=" + adminId;
                SqlCommand command = new SqlCommand(sql, DBHelper.connection);
                DBHelper.connection.Open();
                command.ExecuteNonQuery();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                Console.Write(ex.Message);                
            }
            finally
            {
                DBHelper.connection.Close();
            }
            return result;           
        }


        /// <summary>
        /// 删除的方法
        /// </summary>
        public void Del()
        {
            int count = this.dgvAdmin.SelectedRows.Count;
            if (dgvAdmin.Rows.Count > 0)
            {
                for (int i = count; i >= 1; i--)
                {
                    int adminId = Convert.ToInt32(dgvAdmin.SelectedRows[i - 1].Cells["AdminId"].Value.ToString());
                    if (DelUser(adminId))
                    {
                        this.dgvAdmin.Rows.RemoveAt(dgvAdmin.SelectedRows[i - 1].Index);
                    }
                    else
                    {
                        MessageBox.Show("删除失败!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    
                }
                MessageBox.Show("删除成功!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);  
            }
            else
            {
                dgvAdmin.Rows.Clear();
            }

        }

posted @ 2013-09-23 08:40  meimao5211  阅读(718)  评论(0编辑  收藏  举报