0

我第一次尝试对数据库中的记录进行搜索;我有一个 Windows 窗体项目,在加载事件时会在文本框中显示来自 Access 数据库的名称。除了这个之外,表单还有更多内容,但出于实际目的,我有上一个按钮、下一个按钮和一个查找按钮。假设我在数据库中有 4 个名字:1-Atlas、2-Benson、3-Lane 和 4-Smith。表单加载并显示 Atlas。搜索 Lane,然后 Lane 会显示在表单上。点击“下一步”,而不是史密斯,本森显示。我知道为什么这样做:搜索将记录放在 DataRow 'returnedRow' 中,而表单加载和“上一个”和“下一个”显示的所有记录都来自 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");
        }
    }
4

1 回答 1

0

你是说这部分……?

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];  
 }
于 2013-06-07T14:16:47.593 回答