C# 简单问题 我零基础刚接触C# 求各位高手解答
亮工巧匠 2013-07-14 03:11:34 如果我在我程序里想实现,按一个按钮将我程序里边的Checklistbox中的选项(每个选项都是一个Car类,里边有数据的)都保存到本地文件中。
然后,每次打开这个程序的时候,先从本地文件中读取每个Car类实例的信息,上来就显示在我的Checklistbox中。
我编写的代码如下:
namespace ZAICUN
{
partial class Form1 : Form
{
public Car car1;
public Form2 fm2;
public Form1()
{
InitializeComponent();
fm2 = new Form2(this);
fm2.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
fm2.Visible = true;
}
private void button3_Click(object sender, EventArgs e)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.CheckedItems.Contains(checkedListBox1.Items[i]))
{
Car carx = (Car)Cangku.al_Car[i];
MessageBox.Show(carx.name.type + carx.brand.type + carx.size.type);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.CheckedItems.Contains(checkedListBox1.Items[i]))
{
Cangku.al_Car.RemoveAt(i);
}
}
showCar();
}
public void showCar()
{
this.checkedListBox1.Items.Clear();
for (int i = 0; i < Cangku.al_Car.Count; i++)
{
Car mycar = (Car)Cangku.al_Car[i];
this.checkedListBox1.Items.Add(mycar.name.type+ "的车");
}
}
private void button4_Click(object sender, EventArgs e)
{
}
}
}
namespace ZAICUN
{
partial class Form2 : Form
{
public Form1 fm1;
public Form2(Form1 fm1)
{
this.fm1 = fm1;
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0 || textBox3.Text.Length == 0)
return;
Name n1 = new Name(this.textBox1.Text);
Brand b1 = new Brand(this.textBox2.Text);
Size s1 = new Size(this.textBox3.Text);
Car car1 = new Car(n1, b1, s1);
Cangku.al_Car.Add(car1);
fm1.showCar();
this.textBox1.Clear();
this.textBox2.Clear();
this.textBox3.Clear();
this.Visible = false;
}
}
}
namespace ZAICUN
{
class Cangku
{
public static ArrayList al_Car = new ArrayList();
}
class Car
{
public Name name;
public Brand brand;
public Size size;
public Car(Name n1,Brand b1,Size s1)
{
name = n1;
brand = b1;
size = s1;
}
}
class Name
{
public string type;
public Name(string myname)
{
type = myname;
}
}
class Brand
{
public string type;
public Brand(string mybrand)
{
type = mybrand;
}
}
class Size
{
public string type { get; set; }
public Size(string mysize)
{
type = mysize;
}
}
}
我想在botton4里 添加代码 点击能将Checklistbox的里边的Car类的实例存入本地文件
等打开这个程序的时候 自动读取文件中的Car实例, 还是可以读取这些实例里的信息
新手,知道问题 很幼稚。 谢谢各位大神了 谢谢大家了!