簡體   English   中英

C#刪除數據庫中所有選中的復選框

[英]C# Delete all checked checkboxes in database

我在刪除數據庫中選中的復選框時遇到麻煩。 表明

字符串未被識別為有效的布爾值

在這條線上:

if (bool.Parse(item.Cells[0].Value.ToString()))

這是我檢查所有復選框的代碼

 if (checkBox2.Checked == false)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                chk.Value = chk.TrueValue;

            }
        }
        else if (checkBox2.Checked == true)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                chk.Value = 1;

                if (row.IsNewRow)
                {
                    chk.Value = 0;
                }
            }
        }

//這是我的代碼,用於將選中的復選框刪除到數據庫中。

int count = 0;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if ((Convert.ToBoolean(row.Cells[0].Value) == true))
            {
                count++;
            }
        }

        if (count == 0)
        {
            MessageBox.Show("Please select an item to delete");
        }
        else
        {

            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                if (bool.Parse(item.Cells[0].Value.ToString()))
                {

                    connection.Close();
                    connection.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = connection;

                    cmd.CommandText = "INSERT INTO tbl_Archive ([ID],[Date],[StartTime],[EndTime],[NameOfSchool],[Pax],[TourAgency],[Coordinator],[ContactNumber],[Date & Time Added]) VALUES ('"
                    + id + "','" + myDate + "','" + start + "','" + end + "','" + school + "','" + pax + "','" + touragency + "','" + coordinator + "','" + contact + "','" + dateadded + "')";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "DELETE FROM tbl_Schedule WHERE [ID] = '" + item.Cells[1].Value.ToString() + "'";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "DELETE FROM tbl_ScheduledVisitors WHERE [ID] = '" + item.Cells[1].Value.ToString() + "'";
                    cmd.ExecuteNonQuery();
                    connection.Close();

                }

            }
            MessageBox.Show("Successfully Deleted");
            refreshgrid();
            checkBox2.Checked = false;

            //}
        }

錯誤

為了診斷問題,您可以在以下兩行放置斷點:

if ((Convert.ToBoolean(row.Cells[0].Value) == true))

if (bool.Parse(item.Cells[0].Value.ToString()))

並查看item.Cells[0].Value的值是什么。

這可能不是有效的布爾字符串。

您可以替換以下內容:

if (bool.Parse(item.Cells[0].Value.ToString()))

有了這個:

if (Convert.ToBoolean(item.Cells[0].Value))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM