0

アクセスデータベースからのデータを表示する単純なc#アプリケーションがあります

    private void DisplayRow(int rowIndex)
    {
        // Check that we can retrieve the given row
        if (myDataTable.Rows.Count == 0)
            return; // nothing to display
        if (rowIndex >= myDataTable.Rows.Count)
            return; // the index is out of range

        // If we get this far then we can retrieve the data
        try
        {
            DataRow row = myDataTable.Rows[rowIndex];
            SurnametextBox.Text = row["Surname"].ToString();
            FirstNametextBox.Text = row["Firstname"].ToString();
            PhonetextBox.Text = row["Phone"].ToString();
            ContactTypetextBox.Text = row["ContactType"].ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
        }

    }

データベースの最初のレコードが表示されるようになりました。これで、データをクリックするために次へボタンと戻るボタンが配置されましたが、次のレコードを表示するにはどのコードが必要ですか?

4

3 に答える 3

1

RhysW: ご指摘ありがとうございます。パターン コードの基本を示しただけです。確かに、スムーズに機能させるためにやるべきことはたくさんあります。

これは、およそ次のように行うことができます。

class Form1
{
    int counter;
    DataTable table; //class variable so we can access to the reference from all over the class

    void ButtonForth_Click()
    {
       if(counter < table.Rows.Count)
          counter++;
       YourMethod();
    }

    void ButtonBack_Click()
    {
       if(counter > 0)
          counter--;
       YourMethod();
    }

    void YourMethod()
    {
        DataRow row = table.Rows[counter];
        if(row.Count > 0 )
        {
           SurnametextBox.Text = row["Surname"].ToString();
           FirstNametextBox.Text = row["Firstname"].ToString();
           PhonetextBox.Text = row["Phone"].ToString();
           ContactTypetextBox.Text = row["ContactType"].ToString();
        }
        //no need of try, catch block, is there are all the names correct (textobxes, and columns of datatable)
    }
}
于 2012-05-08T16:47:19.830 に答える
1

クラス変数を作成して、現在どの行インデックスを持っているかを覚えておくことができます。したがって、[次へ] をクリックすると、この変数に +1 が加算され、[前へ] をクリックすると、変数から減算されます (-1)。そして、後で変数を使用します。

class Form1
{
    int counter;
    void ButtonForth_Click()
    {
       counter++;
       YourMethod();
    }

    void ButtonBack_Click()
    {
       counter--;
       YourMethod();
    }

    void YourMethod()
    {
        DataRow row = table.Rows[counter];
        // more code...
    }
}
于 2012-05-08T14:43:33.570 に答える
0

この関数が呼び出される前に、rowIndex がインクリメントされていることを確認してください。それ以外の場合、コードは見栄えがします。

于 2012-05-08T14:41:46.303 に答える