//store the selected row index.
        private int selectedRowIndex = 0;
        public Form1() {
            InitializeComponent();
        }
        //Initialize the Data.
        private void Form1_Load(object sender, EventArgs e) {
            string strConnection = @"Data Source=.\SQLExpress;Initial Catalog=DB_Person;Integrated Security=True";
            using(SqlConnection connect = new SqlConnection(strConnection)) {
                SqlCommand cmd = connect.CreateCommand();
                cmd.CommandText = "select * from [T_Employee]";
                DataSet set = new DataSet();
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(set, "T_Employee");
                dataGV.DataSource = set.Tables["T_Employee"];   //specify the DataSource.
                dataGV.ReadOnly = true; //read only not work when trying to delete or add rows.
                //can not add or delete rows.
                dataGV.AllowUserToAddRows = false;
                dataGV.AllowUserToDeleteRows = false;
            }
        }
        //Try to delete the DataGridView row.
        private void btn_DeleteRow_Click(object sender, EventArgs e) {
            dataGV.Rows.Remove(dataGV.Rows[selectedRowIndex]);
        }
        //Get the index of the selected row.
        private void dataGV_CellClick(object sender, DataGridViewCellEventArgs e) {
            selectedRowIndex = dataGV.CurrentCell.RowIndex;
        }
//我做的测试很简单.但是我不解的是,怎么还是可以删除行...

解决方案 »

  1.   

    木有人?
    我上代码只是为了方便...
    搞不懂为什么设置 DataGridView的属性 AllowUserToAddRows 和 AllowUseToDeleteRows属性设置为false后,还能删除....
      

  2.   

    你说的可以删除 是不是你点那个删除行按钮的时候 可以删除?
    AllowUseToDeleteRows属性只是在DataGridView里面执行行删除,那是它本身带有的功能,就像它的排序一样,而你通过删除按钮来删除这样肯定可以,所以说你禁止的只是DataGridView里面的删除功能
      

  3.   

    AllowUseToDeleteRows这个属性是这么用的,启用时候:在DataGridView中选中行,按Delete键可以删除选中行数据;不启用时:按Delete键无效。
    非DataGridView内操作是不控制的。
      

  4.   

    请问,添加呢?
    AllowUserToAddRows这个属性应该是对对代码约束吧?
    这个测试貌似又麻烦了一点...
      

  5.   

    原因很简单,你的方法是对的,只是你不应该在load事件来做,这是vs的一个bug,, 如果你放在shown的事件就可以,你也可直接去设计窗体属性里去设置
      

  6.   

    哦,是我看错了,datagridview本身有自动的删除行的功能,而AllowUserToDeleteRows这属性只是针对自带的删除功能,
      

  7.   

    你是想说 这个约束只是对 键盘的 delete键其作用而已吧...
      

  8.   

    AllowUserToDeleteRows对于用户体验就有效果,如果对代码是无效的!!
      

  9.   


    Add 和Delete属性都一样,对代码无效的?
    这两个都一样么?...
      

  10.   

    如果你从代码上去操作,那就是无效的!
    AllowUserToDeleteRows和AllowUserToAddRows是针对用户体验的!!