こんにちは、2D 配列を使用して動的に作成されたボタンのこの 4x4 グリッドの色の状態を xml ドキュメントに保存しようとしています。
ただし、保存を押すと、次のメッセージが表示され続けます。
ボタンに1次元配列を使用すると、これを機能させることができますが、必要なグリッドが得られませんが、ボタンに2D配列を使用すると機能しません。
これを機能させるために何を変更できますか?どんな提案でも大歓迎です:
これは私が持っている私のコードです:
FormState
クラス:
public class FormState
{
public string ButtonBackColor { get; set; }
}
フォームコード:
public partial class Form1 : Form
{
int col = 4;
int row = 4;
Button[,] buttons;
FormState[,] states;
public Form1()
{
InitializeComponent();
buttons = new Button[col, row];
states = new FormState[col, row];
}
public void placeRows()
{
for (int r = 0; r < row; r++)
{
createColumns(r);
}
}
public void createColumns(int r)
{
int s = r * 25; //gap
for (int c = 0; c < col; c++)
{
buttons[r, c] = new Button();
buttons[r, c].SetBounds(75 * c, s, 75, 25);
buttons[r, c].Text = Convert.ToString(c);
buttons[r, c].Click += new EventHandler(grid_Click);
panel1.Controls.Add(buttons[r, c]);
}
}
int count = 0;
//backcolor change
void grid_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (count == 0)
{
button.BackColor = Color.Red;
count++;
}
else if (count == 1)
{
button.BackColor = Color.Blue;
count--;
}
}
private void Form1_Load(object sender, EventArgs e)
{
placeRows();
if (File.Exists("config.xml"))
{
loadConfig();
}
for (int i = 0; i < col; ++i)
{
for (int j = 0; j < row; ++j)
{
if (states[i,j] != null)
{
buttons[i,j].BackColor = ColorTranslator.FromHtml(states[i,j].ButtonBackColor);
}
}
}
}
//method to load file
private void loadConfig()
{
XmlSerializer ser = new XmlSerializer(typeof(FormState[]));
using (FileStream fs = File.OpenRead("config.xml"))
{
states = (FormState[,])ser.Deserialize(fs);
}
}
private void writeConfig()
{
for (int i = 0; i < col; i++)
{
for (int j = 0; j < row; j++)
{
if (states[i,j] == null)
{
states[i,j] = new FormState();
}
states[i,j].ButtonBackColor = ColorTranslator.ToHtml(buttons[i,j].BackColor);
}
using (StreamWriter sw = new StreamWriter("config.xml"))
{
XmlSerializer ser = new XmlSerializer(typeof(FormState[]));
ser.Serialize(sw, states);
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
writeConfig();
}
}