September 17, 2016

Insert checked rows records of datagridview into database

 dataGridView1.AllowUserToAddRows = false;
            dataGridView1.Columns.Clear();
            DataGridViewCheckBoxColumn col1 = new DataGridViewCheckBoxColumn();
            col1.Name = "chkcol";
            col1.HeaderText = "SELECT";
          
            dataGridView1.Columns.Add(col1);
            setReload();
            dataGridView1.Columns[1].HeaderText = "ATTEMPT NO";
            dataGridView1.Columns[2].HeaderText = "CAMERA 1";
            dataGridView1.Columns[3].HeaderText = "CAMERA 2";
            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
            }


 private void btnAdd_Click(object sender, EventArgs e)
        {
            int i = 0;
            List ChkedRow = new List();
            for (i = 0; i <= dataGridView1.RowCount - 1; i++)
            {
                if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
                {
                    ChkedRow.Add(i);
                }
            }
            if (ChkedRow.Count == 0)
            {
                MessageBox.Show("Plase select the attempt numbers.");
                return;
            }
            for (i = 0; i <= dataGridView1.RowCount - 1; i++)
            {
                if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
                {
                    ChkedRow.Add(i);
                }
            }

            string str;
            foreach (int j in ChkedRow)
            {
                str = @"update Tbl_Camera_configuration set camera_1 = '" + dataGridView1.Rows[j].Cells["Camera_1"].Value + "', Camera_2 = '" + dataGridView1.Rows[j].Cells["Camera_2"].Value + "' where Attempt_No = '" + dataGridView1.Rows[j].Cells["Attempt_No"].Value + "'";
                try
                {
                    using (SqlConnection con = new SqlConnection(constring))
                    {
                        using (SqlCommand cmd = new SqlCommand(str, con))
                        {
                            con.Open();
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            MessageBox.Show("Records updated sucessfully");
        }

No comments:

Post a Comment