ASP.NET 2.0 中動態添加 GridView 模板列 以及取值的例子

來源:互聯網
上載者:User

<%...@ Page Language="C#" %>
<%...@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">...
  ICollection CreateDataSource()
  ...{
    DataTable dt = new DataTable();
    DataRow dr;
    dt.Columns.Add(new DataColumn("id", typeof(Int32)));
    dt.Columns.Add(new DataColumn("text", typeof(string)));
    for (int i = 0; i < 6; i++)
    ...{
      dr = dt.NewRow();
      dr[0] = i;
      dr[1] = "清單項目 " + i.ToString();
      dt.Rows.Add(dr);
    }
    DataView dv = new DataView(dt);
    return dv;
  }

   public class GridViewTemplate : ITemplate
    {
        private DataControlRowType templateType;
        private string columnName;

        public GridViewTemplate(DataControlRowType type, string colname)
        {
            templateType = type;
            columnName = colname;
        }

        public void InstantiateIn(System.Web.UI.Control container)
        {
            switch (templateType)
            {
                case DataControlRowType.Header:
                    Literal lc = new Literal();
                    lc.Text = columnName;
                    container.Controls.Add(lc);
                    break;
                case DataControlRowType.DataRow:
                    TextBox tb = new TextBox();
                    tb.ID = "ItemNum";
                    tb.Width = 50;
                    tb.DataBinding += new   EventHandler(this.OnDataBinding);     
                    container.Controls.Add(tb);
                    break;
                default:
                    break;
            }
        }
        public void OnDataBinding(object sender, EventArgs e)
        {
            TextBox l = (TextBox)sender;//TextBox發送綁定請求     
            GridViewRow container = (GridViewRow)l.NamingContainer;
            l.Text = ((DataRowView)container.DataItem)["ItemNum"].ToString();//綁定ItemNum欄位     
        }    
    }
  
  protected void Page_Load(object sender, EventArgs e)
  ...{
    if (!IsPostBack)
    ...{
      TemplateField customField = new TemplateField();
      customField.ShowHeader = true;
      customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "動態添加列");
      customField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "");
      GridView1.Columns.Add(customField);
      GridView1.DataSource = CreateDataSource();
      GridView1.DataBind();
    }
  }

  protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e )
  ...{
    if (e.Row.RowType == DataControlRowType.DataRow)
    ...{
      //可以在這裡訪問資料庫的其它欄位的值,可以設定預設選擇項,具體應用,看自己的發揮了。
      //下面只是例子,舉一反三,不再費話了
      DataRowView gv = (DataRowView)e.Row.DataItem;
      int itemSeleted = Int32.Parse(gv.Row["id"].ToString()) > 3 ? 0 : Int32.Parse(gv.Row["id"].ToString());
      DropDownList dr = (DropDownList)e.Row.FindControl("dropdown");
      dr.SelectedIndex = itemSeleted;
    }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>GridView動態添加模板列的例子</title>
</head>
<body>
<form id="form1" runat="server">
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
     OnRowDataBound="GridView1_RowDataBound">
    <Columns>
      <asp:BoundField HeaderText="標題"  DataField="text"/>
    </Columns>
  </asp:GridView> 
</form>
</body>
</html>

 

動態添加的TextBox,PostBack之後就沒有了,要取得使用者在裡面輸入的值,要用Request.Form[###]

其中的###需要填入的是控制項在用戶端的name屬性

幸好,雖然嵌套在模版列裡的TextBox的name是自動產生的,但終歸有規律可循:

假設GridView控制項的ID是GridView1,動態添加的TextBox控制項的ID是MyText,那麼:
protected void Button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        string txtName = "GridView1$ctl"+(i+2).ToString().PadLeft(2,'0')+"$MyText";
        if(Request.Form[txtName]!=null)
         {
             Response.Write(Request.Form[txtName] + "<br/>");
         }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.