C# DataGridView 手动添加和删除行

通过查资料以及自己的不断尝试,终于成功了

目的:不对DataGridView本身操作,直接将页面上其它文本框的信息添加到DataGridView中

优点:不对DataGridView本身操作,并且去除了带*行的空白行

缺点:带*行总在DataGridView最下行

 

注:qcResultDataSet是从数据库查询出来数据集,dataGridViewQcHistory为DataGridView的别名 

      DataGridView的属性:AllowUserToAdd为true  

思路:是先填充第一行的数据,再对第一行深复制两次,一共3行数据

private void LoadDataBaseGrid() { //从数据库中得到数据集qcResultDataSet qcResultDataSet = QcDataBase.GetQcParamSets(condition); for (int i = 1; i < qcResultDataSet.Tables[1].Rows.Count; i++) { //先对第一行赋值 if (i == 1) { dataGridViewQcHistory.Rows[0].Cells[0].Value = qcResultDataSet.Tables[1].Rows[0]["QcTestDate"].ToString().Substring(0, 10); dataGridViewQcHistory.Rows[0].Cells[1].Value = qcResultDataSet.Tables[1].Rows[0]["QcResult"].ToString(); dataGridViewQcHistory.Rows[0].Cells[2].Value = qcResultDataSet.Tables[1].Rows[0]["QcOutRange"].ToString(); } //克隆第一行,再填充后面数据 DataGridViewRow dgr = dataGridViewQcHistory.Rows[i-1].Clone() as DataGridViewRow; dgr.Cells[0].Value = qcResultDataSet.Tables[1].Rows[i]["QcTestDate"].ToString().Substring(0, 10); dgr.Cells[1].Value = qcResultDataSet.Tables[1].Rows[i]["QcResult"].ToString(); dgr.Cells[2].Value = qcResultDataSet.Tables[1].Rows[i]["QcOutRange"].ToString(); dataGridViewQcHistory.Rows.Add(dgr); } } 方法二:

 

              DataGridView属性设置如下:

             AllowUserToAddRows             False

             AllowUserToDeleteRows         False

             AutoSizeColumsMode             AllCells

             AutoSizeRowsMode                AllCells 

            //不绑定DATAGRIDVIEW的情况下,添加6行数据

            string[] chemProName = new string[6];
            chemProName[0] = "A";
            chemProName[1] = "B";
            chemProName[2] = "C";
            chemProName[3] = "D";
            chemProName[4] = "E";  
            chemProName[5] = "F";

 

            for (int i = 0; i < chemProName.Length; i++)
            {
                DataGridViewRow dr = new DataGridViewRow();
                dr.CreateCells(dvgChemProInfo);
                dr.Cells[0].Value = chemProName[i];
                dr.Cells[1].Value = "234";
                //dvgChemProInfo.Rows.Insert(0, dr);
                dvgChemProInfo.Rows.Add(dr);

 

            }

 

 

你可能感兴趣的:(C#)