動態增加 GridView 資料欄 ASP.Net C #
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- public partial class dhilip : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- //實作 datatable
- DataTable dt = new DataTable();
- //實作 datarow
- DataRow drow;
- //建遒 datacolums Column1 and Column2
- DataColumn dcol1 = new DataColumn("Column1", typeof(string));
- DataColumn dcol2 = new DataColumn("Column2", typeof(string));
- //adding datacolumn to datatable
- dt.Columns.Add(dcol1);
- dt.Columns.Add(dcol2);
- //loop for 10 rows
- for (int i = 0; i < 10; i++)
- {
- //實作 datarow
- drow = dt.NewRow();
- //增加資料列到 datatable
- dt.Rows.Add(drow);
- //增加值
- dt.Rows[i][dcol1] = i.ToString();
- dt.Rows[i][dcol2] = i.ToString();
- }
- //set gridView Datasource as dataTable dt.
- GridView1.DataSource = dt;
- //Bind Datasource to gridview
- GridView1.DataBind();
- }
- protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
- {
- //實作 table cell
- // this table cell is going to add gridview as new column
- TableCell tc = new TableCell();
- //first cell must be -1 ie the header of gridview. if it header
- if (e.Row.RowIndex == -1)
- {
- //add header column name. you can add more styles in this section
- tc.Text = "Multiple";
- //add style for header column
- tc.Style.Add(HtmlTextWriterStyle.FontWeight, "bold");
- }
- //cell add to gridview row
- e.Row.Cells.Add(tc);
- }
- protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- //if header column we dont need multiplication
- if (e.Row.RowIndex != -1)
- {
- //taking values from first cell. my first cell contain value, you can change
- string id = e.Row.Cells[0].Text;
- //taking values from second cell. my second cell contain value, you can change
- string id2 = e.Row.Cells[1].Text;
- //multiplication
- double mult = int.Parse(id) * int.Parse(id2);
- //adding result to last column. coz we add new column in last.
- e.Row.Cells[e.Row.Cells.Count - 1].Text = mult.ToString();
- }
- }
- }
沒有留言:
張貼留言