日期:2014-05-18  浏览次数:20389 次

gridview动态生成模版列后,实现编辑更新的问题
我需要实现的结果是
根据设置,运行时在gridview中生成不同的模版列,绑定数据并在gridview中实现编辑删除。

在网上找了一些资料后。实现了部分效果
1、根据设置生成模版列并绑定数据实现了
  方法:动态生成TemplateField并插入到gridview。代码如下:
  (当处理GridView1_RowEditing的时候发现,如果我在load时加上了if (!IsPostBack)则点编辑后会在gridview增加
与现有列数目相同的空列,去掉if (!IsPostBack)后发现还是增加,于是加上GridView1.Columns.Clear();后暂时可以实现
点击编辑后显示textbox并绑定数据了。与此同时遇到另一个问题,修改数据后,点更新的时候,无法查询到修改后的数据。
还有一个问题:为什么我在load的时候Label l = (Label)GridView1.Rows[3].FindControl("label计算机");就能找到值而在GridView1_RowEditing如果加上if (!IsPostBack)则label l的值就时null呢?)
2、如何实现编辑更新?是不是我的方法错了?各位大大给点建议。谢谢

  我问的有不清楚的地方请各位大大提出来呀。谢谢各位啦
C# code
 
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (!IsPostBack)
        //{
            GridView1.Columns.Clear();
            tf4 = new TemplateField();
            tf4.ItemTemplate = new GridViewTemplate("Label", "计算机");
            tf4.EditItemTemplate = new GridViewTemplate("TextBox", "计算机");
            tf4.HeaderText = "计算机";
            GridView1.Columns.Add(tf4);
            tf4 = new TemplateField();
            tf4.ItemTemplate = new GridViewTemplate("Label", "数学");
            tf4.EditItemTemplate = new GridViewTemplate("TextBox", "数学");
            tf4.HeaderText = "数学";
            GridView1.Columns.Add(tf4);

            cf = new CommandField();
            cf.ShowDeleteButton = false;
            cf.ShowCancelButton = false;
            cf.ShowEditButton = true;
            GridView1.Columns.Add(cf);
            databind();
            Label l = (Label)GridView1.Rows[3].FindControl("label计算机");
            if (l != null) TextBox1.Text = "GridView1.Rows[3] label.text = " + l.Text;
            Label l2 = (Label)GridView1.Rows[3].FindControl("labeltext");
            if (l2 != null) TextBox2.Text = "GridView1.Rows[3] l2.text" + l2.Text;
        //}
    }


C# code

public class GridViewTemplate : ITemplate
{
    private string temptype;
    private string columnName;
    public GridViewTemplate(string type, string colname)
    {
        temptype = type;
        columnName = colname;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (temptype.ToLower())
        {
            case "textbox":
                TextBox textbox = new TextBox();
                textbox.ID = "textbox" +columnName;
                textbox.Text = "test";
                //container.Controls.Add(textbox);
                textbox.DataBinding += new EventHandler(this.OnDataBinding);
                textbox.TextChanged += new EventHandler(this.OnTextChanged);
                container.Controls.Add(textbox);
                break;
            case "labe