GridView At CodeBehind 透過程式碼產生GridView
GridView GridView1 = new GridView(); SqlDataSource sqldsBankuai = new SqlDataSource();
protected void Page_Load(object sender, EventArgs e) { GridView1.ID = "GridView1"; sqldsBankuai.ConnectionString = "server=.;database=db;trusted_connection=true"; sqldsBankuai.SelectCommand = "select * from Table"; sqldsBankuai.ID = "SqlDataSource1"; sqldsBankuai.DataSourceMode = SqlDataSourceMode.DataSet; this.form1.Controls.Add(sqldsBankuai); GridView1.ID = "GridView1"; GridView1.AutoGenerateColumns = false; GridView1.DataSourceID = sqldsBankuai.ID; GridView1.AllowPaging = true; GridView1.PageSize = 3; form1.Controls.Add(GridView1); if (!IsPostBack) { BoundField bfield1 = new BoundField(); bfield1.HeaderText = "名稱"; bfield1.DataField = "Subject"; GridView1.Columns.Add(bfield1); } TemplateField textF = new TemplateField(); textF.ItemTemplate = new GridViewTextTemplate(DataControlRowType.DataRow, "Subject", "Subject"); GridView1.Columns.Add(textF); GridView1.PageIndexChanging += new GridViewPageEventHandler(GridView1_PageIndexChanging); }
void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { //throw new NotImplementedException(); GridView1.PageIndex = e.NewPageIndex; GridView1.DataSourceID = sqldsBankuai.ID; GridView1.DataBind(); }
//Text Box public class GridViewTextTemplate : ITemplate { private DataControlRowType templateType; private string columnName; private string cId; public GridViewTextTemplate(DataControlRowType type, string colname, string controlId) { templateType = type; columnName = colname; cId = controlId; } public void InstantiateIn(System.Web.UI.Control container) { // Create the content for the different row types. switch (templateType) { case DataControlRowType.Header: // Create the controls and set id properties to put in the header Label label1 = new Label(); label1.ID = cId; label1.Text = "<B>" + columnName + "</B>"; container.Controls.Add(label1); break; case DataControlRowType.DataRow: // Create the controls and set id properties to put in a data row TextBox myTextBox = new TextBox(); myTextBox.ID = cId; myTextBox.DataBinding += new EventHandler(this.TextBoxDataBinding); container.Controls.Add(myTextBox); break; default: // Insert code to handle unexpected values. break; } } private void TextBoxDataBinding(Object sender, EventArgs e) { TextBox myTextBox = (TextBox)sender; GridViewRow row = (GridViewRow)myTextBox.NamingContainer; myTextBox.Text = System.Web.UI.DataBinder.Eval(row.DataItem, columnName).ToString(); } }