如何从数据库中检索记录,并使其与表单加载的索引保持一致

本文关键字:表单 加载 保持一致 索引 数据库 检索 记录 | 更新日期: 2023-09-27 18:17:19

我第一次尝试对数据库中的记录进行搜索;我有一个窗体项目,在加载事件显示从一个文本框中的访问数据库的名称。还有更多的形式比这,但出于实际目的,我有按钮上,下一个和查找。假设我在数据库中有4个名字:1-Atlas, 2-Benson, 3-Lane &4-Smith。表单加载并显示Atlas。搜索Lane, Lane就会显示在表单上。点击"下一步",显示的不是史密斯,而是本森。我知道为什么这样做:搜索将记录放在DataRow ' return '中,而所有记录都显示在表单加载和' Previous '上;"Next"来自DataRow"dRow"。如何从dRow内部的查询中检索记录?

OleDbConnection myConn = new OleDbConnection();
DataSet myDS;
int MaxRows = 0        
int inc = 0;
private void Form1_Load(object sender, EventArgs e)
    {          
        myConn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:'Temp'Testing'TestDatabase.accdb";
        myConn.Open();
        myDS = new DataSet();
        string sql = "SELECT * From Test";
        OleDbDataAdapter myDA = new OleDbDataAdapter(sql, myConn);
        myDA.Fill(myDS, "People");
        NavigateRecords();
        MaxRows = myDS.Tables["People"].Rows.Count;
        myConn.Close();
    }
private void NavigateRecords()
    {
        DataRow dRow = myDS.Tables["People"].Rows[inc];
        txtName.Text = dRow.ItemArray.GetValue(1).ToString();
        txtAddress.Text = dRow.ItemArray.GetValue(2).ToString();
        txtCity.Text = dRow.ItemArray.GetValue(3).ToString();
        txtState.Text = dRow.ItemArray.GetValue(4).ToString();
        txtZip.Text = dRow.ItemArray.GetValue(5).ToString();  
    }
private void btnNext_Click(object sender, EventArgs e)
    {
        if (inc != MaxRows - 1)
        {
            inc++;
            NavigateRecords();
        }
        else
        {
            MessageBox.Show("No more rows");
        }
    }
private void btnFind_Click(object sender, EventArgs e)
    {
        string searchFor = txtFind.Text;
        int results = 0;
        if (txtFind.Text.Trim() == "")
        {
            MessageBox.Show("Nothing to search for");
            return;
        }
        DataRow[] returnedRows;
        string expression;
        expression = "Name1='" + searchFor + "'";
        returnedRows = myDS.Tables["People"].Select(expression);
        results = returnedRows.Length;
        if (results > 0) 
        {
            DataRow dr1;
            dr1 = returnedRows[0];
            txtName.Text = dr1[1].ToString();
            txtAddress.Text = dr1[2].ToString();
            txtCity.Text = dr1[3].ToString();
            txtState.Text = dr1[4].ToString();
            txtZip.Text = dr1[5].ToString();
        }
        else
        {
            MessageBox.Show("No record found");
        }
    }

如何从数据库中检索记录,并使其与表单加载的索引保持一致

你是说这部分…

?
private void NavigateRecords()
{
    DataRow dRow = myDS.Tables["People"].Rows[inc];
    txtName.Text = dRow[1];
    txtAddress.Text = dRow[2];
    txtCity.Text = dRow[3];
    txtState.Text = dRow[4];
    txtZip.Text = dRow[5];  
 }