這篇帶給大家DataGrid以及DataTable的應用方式,從DataTable欄位&資料建置到DataGrid利用DataBind將畫面展示,click按鈕時再新增一筆資料上去。
當我還是初學者時,上網找尋一些元件使用範例,要不是常常建置不成功,不然就是跑不起來,當時也不清楚哪裡缺少了什麼東西,因此又要在找下一篇範例試試看,不知道是網路上的都東缺西少還是自己能力不夠,所以希望JC ASP.NET學習筆記能帶給大家比較完整的範例(至少能run起來)。
開發工具 : Visual Studio 2017 Web Form
DataGrid.aspx
<form id="form1" runat="server"> <div> <asp:DataGrid id="ThisDataGrid" runat="server" CellPadding="4" CellSpacing="0" BorderStyle="Solid" BorderWidth="1" > <Columns> <asp:BoundColumn HeaderText="品項" DataField="ID" /> <asp:BoundColumn HeaderText="價格" DataField="Price"/> </Columns> </asp:DataGrid> </div> <div> <asp:Button ID="Button1" runat="server" Text="Click Me" OnClick="Button1_Click" /> </div> </form>
DataGrid.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
var DT = new DataTable("AppleStore");
DataColumn DC = DT.Columns.Add("ID", typeof(string));
DC.AllowDBNull = false;
DC.Unique = true;
DT.Columns.Add("Price", typeof(string));
DataRow dr = DT.NewRow();
dr["ID"] = "iPhone";
dr["Price"] = 55000;
DT.Rows.Add(dr);
ThisDataGrid.DataSource = DT;
ThisDataGrid.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable DT = (DataTable)ThisDataGrid.DataSource;
DataRow dr = DT.NewRow();
dr["ID"] = "iPhone XS";
dr["Price"] = 57000;
DT.Rows.Add(dr);
ThisDataGrid.DataSource = DT;
ThisDataGrid.DataBind();
}
DataGrid簡單的教學就到這裡,如有問題下面可以留言讓我知道。