【问题标题】:Showing data in text boxes before deleting it from access databse [closed]在从访问数据库中删除数据之前在文本框中显示数据[关闭]
【发布时间】:2017-05-25 19:59:04
【问题描述】:

我有一个项目(C# 应用程序),其中包括使用 access 数据库。我想要做的是在删除之前在文本框和组合框(按 id)中显示数据,但它总是显示错误的数据而不是我正在寻找的数据(id 比我正在寻找的高四个 - 如果我想要 4,它会显示 8 等的数据。)

这是我的代码:

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();
        }
    }

【问题讨论】:

  • 你似乎在混合索引和 BookID
  • @WayneG.Dunn 该表有 5 列。

标签: c# sql database ms-access textbox


【解决方案1】:

您传递的是图书的 ID,而不是数据表中的索引(行号)。

您可以使用 DataTable 的 Select 方法搜索其 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();

    }
}

【讨论】:

猜你喜欢
  • 2013-03-23
  • 1970-01-01
  • 2019-09-16
  • 2017-07-21
  • 2023-03-04
  • 2013-05-27
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
相关资源
最近更新 更多