我制作了以下 WinForm,用户在其中提供书籍详细信息并创建书籍记录。这本书记录被添加到 dataGridView 并自动选中复选框:
现在,当我取消选择一些书籍并单击“插入到数据库”按钮以将选定的书籍插入数据库时,其中一本被取消选择的书籍总是与选定的书籍一起插入到数据库中。那可能是任何一本被取消选择的书。
像这里我取消选择一些书:
现在,当我单击“插入到数据库”按钮时,未选择的书籍将从 dataGridView 中删除,选定的书籍将插入数据库:
现在插入数据库的书籍是选定的书籍“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();
}
}
如果有人能帮助我解决这个问题,我将不胜感激。
谢谢!