我製作了以下WinForm,其中用戶提供書籍詳細信息並創建書籍記錄。這本書記錄被添加到具有CheckBox DataGridView的自動選擇:一個被取消選中的行總是被插入到數據庫以及來自dataGridView的選定行
現在,當我取消了一些書,然後單擊「插入數據庫」按鈕,插入所選圖書數據庫中,取消選擇的書籍之一總是與選定的書籍一起插入到數據庫中。這可能是任何一本被取消選擇的書。
喜歡這裏我取消了一些書:
現在,當我點擊「插入到數據庫」按鈕,未被選中的圖書將會從DataGridView被刪除,選擇一個將b插入到數據庫:
立即插入到數據庫中的書籍是所選擇的書籍「123」,「345,」 678' 890與一個未選擇的書沿‘’。像這樣,一本未被選中的書會隨着所選書籍一起被插入到數據庫中。
我所編寫的代碼是:
public partial class CreateBookRecord : Form
{
DataTable addedBooks;
DataColumn bookId, bookName, author, noOfCopies, noOfCopiesAvailable;
DataGridViewCheckBoxColumn check;
public CreateBookRecord()
{
InitializeComponent();
}
private void CreateBookRecord_Load(object sender, EventArgs e)
{
check = new DataGridViewCheckBoxColumn(); //Create a checkbox column for DataGridView
addedBooks = new DataTable();
bookId = new DataColumn("Book ID", typeof(string));
bookName = new DataColumn("Book Name", typeof(string));
author = new DataColumn("Author", typeof(string));
noOfCopies = new DataColumn("No of Copies", typeof(int));
noOfCopiesAvailable = new DataColumn("No of Copies Available", typeof(int));
addedBooks.Columns.AddRange(new DataColumn[] { bookId, bookName, author, noOfCopies,noOfCopiesAvailable });
dataGridViewAddedBooks.Columns.Add(check); //To make first column as checkBox column
dataGridViewAddedBooks.DataSource = addedBooks;
dataGridViewAddedBooks.Columns["No of Copies Available"].Width = 0;
}
private void buttonCreateBook_Click(object sender, EventArgs e)
{
try
{
addedBooks.Rows.Add(textBoxID.Text, textBoxBookName.Text, textBoxAuthorName.Text,Convert.ToInt32(textBoxNoOfCopies.Text),Convert.ToInt32(textBoxNoOfCopies.Text));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridViewAddedBooks_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridViewCheckBoxCell checkcell = (DataGridViewCheckBoxCell)dataGridViewAddedBooks.Rows[e.RowIndex].Cells[0];
checkcell.Value = true;
}
private void buttonInsertBooks_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridViewAddedBooks.Rows)
{
DataGridViewCheckBoxCell checkcell = (DataGridViewCheckBoxCell)row.Cells[0];
if (checkcell.Value == check.FalseValue)
{
dataGridViewAddedBooks.Rows.Remove(row);
}
}
SqlBulkCopy copy = new SqlBulkCopy(connection);
copy.DestinationTableName = "Book";
try
{
connection.Open();
copy.WriteToServer(addedBooks);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
}
}
,我會很感激,如果有人可以幫助我解決這個問題。
謝謝!