Markup:
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2" runat="server">
</head>
<body>
<form id="form1" runat="server">
<asp:GridView runat="server" ID="grvItems" />
<asp:Panel runat="server" ID="pnlAddCar">
Modal: <asp:TextBox runat="server" ID="txtModal" />
Color: <asp:TextBox runat="server" ID="txtColor" />
<asp:Button runat="server" ID="btnSave" Text="Save Car" OnClick="SaveCar" />
</asp:Panel>
</form>
</body>
</html>
Code:
public partial class Test : Page
{
private string fileName;
public List<Car> Cars
{
get { return ViewState["Items"] as List<Car>; }
set { ViewState["Items"] = value; }
}
public Test()
{
fileName = Server.MapPath("~/Data.bin");
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!this.IsPostBack)
this.LoadCars();
}
protected void SaveCar(object sender, EventArgs e)
{
if (this.Cars == null) this.Cars = new List<Car>();
Car car = new Car() { Color = this.txtColor.Text, Modal = this.txtModal.Text };
this.Cars.Add(car);
Stream stream = File.Open(fileName, FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, this.Cars);
stream.Close();
this.grvItems.DataSource = this.Cars;
this.grvItems.DataBind();
}
protected void LoadCars()
{
List<Car> cars;
if (File.Exists(this.fileName))
{
Stream stream = File.Open(fileName, FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
cars = (List<Car>)binaryFormatter.Deserialize(stream);
stream.Close();
this.Cars = cars;
}
if (this.Cars != null)
{
this.grvItems.DataSource = this.Cars;
this.grvItems.DataBind();
}
}
}
[Serializable]
public class Car
{
#region Properties
public string Modal { get; set; }
public string Color { get; set; }
#endregion
#region Methods
#endregion
}
No comments:
Post a Comment