あなたの質問を明確にしてみましょう:
それぞれがテキスト ファイル内の 1 行を表す多数のテキスト ボックスがあります。ユーザーがテキストボックスの横にあるボタンをクリックするたびに、対応する行を置き換えます。
テキスト ファイルの 1 行を置き換えるのは非常に簡単です。すべての行を配列に読み込み、行を置き換えて、すべてをファイルに書き戻します。
private static void ReplaceLineInFile(string path, int lineNumber, string newLine)
{
if (File.Exists(path))
{
string[] lines = File.ReadAllLines(path);
lines[lineNumber] = newLine;
File.WriteAllLines(path, lines);
}
}
残っている唯一のことは、どの行を置き換える必要があるかを知ることです。ボタンごとにハンドラーを追加できます (行番号が 0 から始まることに注意してください)。
private void button1_Click(object sender, EventArgs e)
{
ReplaceLineInFile(fileName, 0, textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
ReplaceLineInFile(fileName, 1, textBox2.Text);
}
etc.
これは同じコードを複製するため、あまりエレガントではありません。すべてのボタンに対して 1 つのイベント ハンドラーを使用し、それがどのテキスト ボックスに対応し、どの行を置き換える必要があるかを判断することをお勧めします。テキストボックスとボタンの配列を用意し、コンストラクターで構築することをお勧めします。
private TextBox[] textBoxes;
private Button[] buttons;
public managementsystem()
{
InitializeComponent();
textBoxes = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5 };
buttons = new Button[] { button1, button2, button3, button4, button5 };
}
単一のイベント ハンドラーは次のようになります。
private void button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
int lineNumber = Array.IndexOf(buttons, button);
if (lineNumber >= 0)
{
ReplaceLineInFile(fileName, lineNumber, textBoxes[lineNumber].Text);
}
}
}
ある時点で、すべての値を保存したり、ファイルを作成したりすることが必要になる場合があります。また、フォームがロードされたときに、既存の値をテキスト ボックスにロードすることもできます。
private void Form1_Load(object sender, EventArgs e)
{
LoadFile();
}
private void LoadFile()
{
if (!File.Exists(fileName))
{
WriteAllLines();
return;
}
string[] lines = File.ReadAllLines(fileName);
if (lines.Length != textBoxes.Length)
{
// the number of lines in the file doesn't fit so create a new file
WriteAllLines();
return;
}
for (int i = 0; i < lines.Length; i++)
{
textBoxes[i].Text = lines[i];
}
}
private void WriteAllLines()
{
// this will create the file or overwrite an existing one
File.WriteAllLines(fileName, textBoxes.Select(tb => tb.Text));
}
新しいテキストボックスを追加しても、これは引き続き機能することに注意してください。変更する必要があるのは、コンストラクターでの配列の作成だけです。ただし、テキストボックスの数を変更すると、既存のファイルが削除されます。これを回避するには、新しい行を手動で追加または削除します。