private void button1_Click(object sender, EventArgs e) //add data to listBox
{
if (String.IsNullOrWhiteSpace(textBox1.Text) || String.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("Proszę uzupełnić wszystkie pola, aby wprowadzić dane", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
listBox1.Items.Add(textBox4.Text + " " + textBox1.Text + " " + textBox2.Text);
listBox1.DisplayMember = textBox4.Text;
}
private void button2_Click(object sender, EventArgs e) //delete data from listbox
{
if(listBox1.SelectedIndex == -1)
{
MessageBox.Show("Proszę zaznaczyć pozycję by usunąć", "Błąd!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
listBox1.Items.Remove(listBox1.SelectedItem);
}
private void button3_Click(object sender, EventArgs e) //save to XML button
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "Tabela";
dt.Columns.Add("Name");
dt.Columns.Add("Surname");
dt.Columns.Add("PESEL");
dt.Columns.Add("Room");
ds.Tables.Add(dt);
foreach (string item in listBox1.Items)
{
DataRow dr = ds.Tables["Tabela"].NewRow();
dr["Name"] = textBox1.Text;
dr["Surname"] = textBox2.Text;
dr["PESEL"] = textBox3.Text;
dr["Room"] = textBox4.Text;
ds.Tables["Tabela"].Rows.Add(dr);
}
ds.WriteXml("D:\\data.xml");
}
private void button4_Click(object sender, EventArgs e) //read from XML button
{
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
foreach (DataRow item in ds.Tables["Tabela"].Rows)
{
listBox1.Items.Add(string.Format("{0} {1} {2}", item["Room"], item["Name"], item["Surname"]));
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml("D:\\data.xml");
foreach (DataRow item in ds.Tables["Tabela"].Rows)
{
textBox1.Text = item["Name"].ToString();
textBox2.Text = item["Surname"].ToString();
textBox3.Text = item["PESEL"].ToString();
textBox4.Text = item["Room"].ToString();
}
}
保存和讀取XML文件時出現問題。當我將從textBoxes添加一些數據到列表框時,只保存了我添加的最後一個索引,但是多次。Visual C#程序只保存最後一個索引到XML文件
例子:
<Tabela>
<Name>John</Name>
<Surname>Johnson</Surname>
<PESEL>123465789</PESEL>
<Room>21</Room>
</Tabela>
<Tabela>
<Name>John</Name>
<Surname>Johnson</Surname>
<PESEL>123465789</PESEL>
<Room>21</Room>
</Tabela>
<Tabela>
<Name>John</Name>
<Surname>Johnson</Surname>
<PESEL>123465789</PESEL>
<Room>21</Room>
</Tabela>
;當我從XML加載數據列表框工作正常,但是當我在文本框中選擇一個指數從這份名單僅出現最後一個索引,而不是我點擊了。