Check the stored data and right-click to delete data in c# DataGridView (sample code)

Time:2021-10-21

DataGridView event cellcontentclick

Trigger the CellContentClick event of dataGridView and invoke the Edit method in the event.
If the conditions are not met after adding a checkbox in the DataGridView, remove the check box
It also implements the action of saving the bound data into the table after checking

在这里插入图片描述

Click OK to remove the check

在这里插入图片描述

Main.cs

private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.tabControl1.SelectedIndex)
            {
                //case 0:
                //// display data
                //    ShowVlues();
                //    break;

                case 1:
                   
                    TableDefine.Initial_TableE();
                    for (int i = 0; i <= TableDefine.tGridField.Length - 1; i++)
                    {
                        cboSearch.Items.Add(TableDefine.tGridField[i].sCaption);
                        cboSearchList.Items.Add(TableDefine.tGridField[i].sFieldName);
                    }
                    if (cboSearch.Items.Count > 0)
                    {
                        cboSearch.SelectedIndex = 0;
                    }
                    //Take model
                    DataTable ModelDT = fslConn.GetAllModel();
                    if (ModelDT.Rows.Count > 0)
                    {
                        foreach (DataRow item in ModelDT.Rows)
                        {
                            cboModel.Items.Add(item[0]);
                        }
                    }

                    //Fetch process
                    DataTable RouteDT = fslConn.GetAllRoute();
                    if (RouteDT.Rows.Count > 0)
                    {
                        foreach (DataRow item in RouteDT.Rows)
                        {
                            cboRoute.Items.Add(item[0]);
                        }
                    }

                    //Display data
                    ShowEVlues();
                    break; 
            }
        }

        //Fetch data display
        void ShowEVlues()
        {
            string sFieldName = string.Empty;
            string sFieldText = string.Empty;
            if (cboSearch.SelectedIndex > -1 && txtSearch.Text.Trim() != "")
            {
                sFieldName = cboSearchList.Items[cboSearch.SelectedIndex].ToString();
                sFieldText = txtSearch.Text.Trim();
            }
            if (string.IsNullOrWhiteSpace(sFieldText))
                gvDataE.DataSource = fslConn.GetAllFslEName();
            else
                gvDataE.DataSource = fslConn.GetAllFslEName(sFieldName, sFieldText);
            //Field title
            for (int i = 0; i <= gvDataE.Columns.Count - 1; i++)
            {
                gvDataE.Columns[i].Visible = false;
            }
            for (int i = 0; i < TableDefine.tGridField.Length; i++)
            {
                string sGridField = TableDefine.tGridField[i].sFieldName;

                if (gvDataE.Columns.Contains(sGridField))
                {
                    gvDataE.Columns[sGridField].HeaderText = TableDefine.tGridField[i].sCaption;
                    gvDataE.Columns[sGridField].DisplayIndex = i; // Field display order 
                    gvDataE.Columns[sGridField].Visible = true;
                }
            }
            gvDataE.Focus();
            //Add check box column for DGV
            DataGridViewCheckBoxColumn checkbox = new DataGridViewCheckBoxColumn();
            //Column display name
            Checkbox.headertext = "select";
            checkbox.Name = "IsChecked";
            checkbox.TrueValue = true;
            checkbox.FalseValue = false;
            checkbox.DataPropertyName = "IsChecked";
            //Column width
            checkbox.Width = 50;
            //The column size does not change
            checkbox.Resizable = DataGridViewTriState.False;
            //The added checkbox is in the DGV first column
            this.gvDataE.Columns.Insert(0, checkbox);   
        }
        
  //Implement search
        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)Keys.Return)
                return;
            ShowEVlues();
            editFilter.Focus();
        }
   //Get the site through the process
        private void cboRoute_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboRoute.Text != "")
            {
                //Take site
                DataTable StationTypeDT = fslConn.GetAllStationType(cboRoute.Text);
                if (StationTypeDT.Rows.Count > 0)
                {
                    for (int i = 0; i < StationTypeDT.Rows.Count; i++)
                    {
                        //cboStationType.Items.Add(item[0]);
                        cboStationType.Items.Add(new Metadata(StationTypeDT.Rows[i][2].ToString(), StationTypeDT.Rows[i][0].ToString(), StationTypeDT.Rows[i][1].ToString()));
                    }
                }
            }
        }
        //Click to check the event for data binding
        private void gvDataE_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string Model = cboModel.Text;
            string Route = cboRoute.Text;
            if (Model == "" || Route == ""|| cboStationType.Text == "")
            {
                MessageBox. Show ("model, process and site cannot be empty, please check!");
                //DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)this.gvDataE.Rows[e.RowIndex].Cells["IsChecked"];
                // this.gvDataE.Rows[e.RowIndex].Cells["IsChecked"].Value = false;
                //Remove the check
                this.gvDataE.RefreshEdit();
                return;
            }

            //Site code
            string StationType = ((Metadata)cboStationType.SelectedItem).ID;
            //Site description
            string StationTypeDesc = ((Metadata)cboStationType.SelectedItem).NAMEDESC;

         
            if (e.ColumnIndex == 0 && e.RowIndex != -1)
            {
                //Gets the value of the control
                DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)this.gvDataE.Rows[e.RowIndex].Cells["IsChecked"];
                Boolean flag = Convert.ToBoolean(checkCell.Value);
                //KP product name
                string gvFunName = gvDataE.Rows[e.RowIndex].Cells["MAT_TYPE_CODE"].Value.ToString();
                //KP product name描述
                string gvFunNameDesc = gvDataE.Rows[e.RowIndex].Cells["MAT_TYPE_DESC"].Value.ToString();

        
                if  (flag == false)
                {
                    checkCell.Value = true;
                    //Add permissions
                    fslConn.SaveFslPower(gvFunName, gvFunNameDesc, Model,StationType, StationTypeDesc);
                }
            }
        }

ComboBox value

main.cs
 //Take model
                    DataTable ModelDT = fslConn.GetAllModel();
                    if (ModelDT.Rows.Count > 0)
                    {
                        foreach (DataRow item in ModelDT.Rows)
                        {
                            cboModel.Items.Add(item[0]);
                        }
                    }
 fslConn.cs                   
 //Take model
        public DataTable GetAllModel()
        {
            return fslDAL.GetAllModel();
        }
fslDAL.cs
 //Take model
        public DataTable GetAllModel()
        {
            string sql = "SELECT MODEL FROM IMES.M_MODEL";
            return utility.Query(sql);
        }

Store data

fslConn.cs  
    public long SaveFslPower(string gvFunName, string gvFunNameDesc, string Model, string StationType, string StationTypeDesc )
        {    
            return fslDAL.SaveFslPower(gvFunName, gvFunNameDesc, Model, StationType, StationTypeDesc);
        }
fslDAL.cs
     //Save permission
        public long SaveFslPower(string gvFunName, string gvFunNameDesc, string Model, string StationType, string StationTypeDesc)
        {
            string id = GetMaxId();
            string sql = @"INSERT INTO IMES.M_STATIONTYPE_PARTSPEC  (ID,MODEL,STATION_TYPE,STATION_DESC,KP_SPEC,KP_SPEC_DESC,QTY,ENABLED,CREATE_EMPNO,CREATE_TIME,UPDATE_EMPNO)
                        VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11)";
            object[] para = new object[] { id, Model, StationType , StationTypeDesc,gvFunName, gvFunNameDesc, "1", "Y", utility.GlobalUserNo,DateTime.Now, utility.GlobalUserNo };
            return utility.ExecuteSql(sql, para);
        }

Right click to delete data

Realization effect

在这里插入图片描述

Main.cs
   //Right click the DataGridView field to delete data
        Private void delete toolstripmenuitem_ Click(object sender, EventArgs e)
        {
            if (gvData.Rows.Count == 0 || gvData.CurrentRow == null)
            {
                return;
            }
            string ID = gvData.CurrentRow.Cells["ID"].Value.ToString();
            If (MessageBox. Show ("ID:" + ID + "are you sure to delete?", "prompt", messageboxbuttons. Yesno, messageboxicon. Question) = = DialogResult. Yes)
            {
                //M_ STATIONTYPE_ PARTSPEC_ HT write history library
                fslConn.SaveFslHistoryData(ID);
                Remove permissions
                fslConn.DeleteFslByIDAndFunc(ID);

                //Display data
                ShowVlues();
            }              
        }
fslConn.cs 
    //Delete permissions
        public long DeleteFslByIDAndFunc(string id)
        {
            return fslDAL.DeleteFslByIDAndFunc( id);
        }   
fslDAL.cs
     //Delete permissions
        public long DeleteFslByIDAndFunc(string id)
        {
            string sql = @"Delete from  IMES.M_STATIONTYPE_PARTSPEC WHERE ID =:1";
            object[] para = new object[] { id };
            return utility.ExecuteSql(sql, para);
        }

This is the end of the article on checking the storage of data and right clicking to delete data in c# DataGridView. For more information about right clicking to delete data in c# DataGridView, please search for previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer more in the future!