C# 在从access数据库中删除数据之前在文本框中显示数据
我有一个项目(C#应用程序),包括使用access数据库。我想做的是在删除之前在文本框和组合框中显示数据(按id),但它总是显示错误的数据(id比我要查找的数据高4个-如果我要4个,它会显示8个等的数据) 这是我的代码:C# 在从access数据库中删除数据之前在文本框中显示数据,c#,sql,database,ms-access,textbox,C#,Sql,Database,Ms Access,Textbox,我有一个项目(C#应用程序),包括使用access数据库。我想做的是在删除之前在文本框和组合框中显示数据(按id),但它总是显示错误的数据(id比我要查找的数据高4个-如果我要4个,它会显示8个等的数据) 这是我的代码: public partial class Form2 : Form { OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C
public partial class Form2 : Form
{
OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Computer\Desktop\BookCollection.accdb");
DataTable books = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter();
OleDbCommand command;
public Form2()
{
InitializeComponent();
}
public void ShowData(int index)
{
tbID.Text = books.Rows[index][0].ToString();
comboBoxTitle.Text = books.Rows[index][1].ToString();
tbPageNumber.Text = books.Rows[index][2].ToString();
comboBoxBookType.Text = books.Rows[index][3].ToString();
tbComment.Text = books.Rows[index][4].ToString();
}
private void btnDelete_Click(object sender, EventArgs e)
{
string sComDelete = "DELETE FROM BOOKS WHERE BookID = @BookID";
OleDbCommand comDelete = new OleDbCommand(sComDelete, connection);
comDelete.Parameters.AddWithValue("@BookID", tbID.Text);
try
{
connection.Open();
ShowData(Convert.ToInt32(tbID.Text));
comDelete.ExecuteNonQuery();
MessageBox.Show("Record is deleted.");
tbID.Text = tbBrStrana.Text = tbKom.Text = comboBoxTitle.Text = comboBoxBookType.Text = "";
}
catch (Exception ex1)
{
MessageBox.Show("Error! " + ex1.Message.ToString());
}
finally
{
connection.Close();
}
}
您传递的是书籍的ID,而不是数据表中的索引(行号) 您可以使用DataTable的Select方法搜索ID为输入中传递的ID的行,然后使用该行填充文本框
public void ShowData(int bookId)
{
// Select returns an array of DataRows that match the condition
// in your case probably you have zero or one row returned
DataRow[] rows = books.Select("BookID = " + bookID);
if(rows.Length > 0)
{
tbID.Text = rows[0][0].ToString();
comboBoxTitle.Text = rows[0][1].ToString();
tbPageNumber.Text = rows[0][2].ToString();
comboBoxBookType.Text = rows[0][3].ToString();
tbComment.Text = rows[0][4].ToString();
// Consider also that if you delete the found row
// probably you want to keep in synch the in memory datatable
rows[0].Delete();
books.AcceptChanges();
}
}
你似乎把索引和BookID@WayneG.Dunn该表中有5列。谢谢,正在运行。很高兴能提供帮助。看看你的个人资料,我建议你读一读