在Gridview单元格中清除文本框

时间:2013-11-13 13:01:50

标签: c# gridview

gridview有多个行和列,每个单元格都有一个文本框,验证器控件,就像在Excel中一样。列是动态生成的,我想清除所有文本框。

这不起作用。我哪里错了

protected void btnClear_Click(object sender, EventArgs e)
{
 if(gvMain.Rows.Count > 0)
  {
    foreach(GridViewRow gvr in gvMain.Rows)
     {
       foreach(TableCell tc in gvr.Cells)
        {
           if(tc.HasControls())
            {
              for(int i=0;i<tc.Controls.Count;i++)
               {
                 if(tc.Controls[i] is TextBox)
                   {
                     TextBox tb = (TextBox)tc.Controls[i];
                      tb.Text= "";
                   }
               }
            }
        }
     }
  }
}

4 个答案:

答案 0 :(得分:2)

这是解决方案。我已经尝试过了,它运行良好。

     foreach (GridViewRow row in GridView1.Rows)
        {
            foreach (TableCell cell in row.Cells)
            {
                foreach (var control in cell.Controls)
                {
                    var box = control as TextBox;
                    if (box != null )
                    {
                        box.Text = string.Empty;
                    }
                }
            }
        }

希望这会有所帮助

答案 1 :(得分:0)

Plz尝试以下代码:

foreach(GridViewRow r in GridView.Rows)
{
   TextBox txtbox = (TextBox)r.FindControl("Id of TextBox");
   txtbox.Text = "";
} 

由于

答案 2 :(得分:0)

使用以下代码:

 foreach(GridViewRow gr in GridView.Rows)
    {
       // find your all textbox
       TextBox txtA= (TextBox)gr.FindControl("txtA");
       TextBox txtB= (TextBox)gr.FindControl("txtB");
       //Check they are not null
       if(txtA!=null){
       //Assign empty string
           txtA.Text = string.empty;
           }
       if(txtB!=null){
       //Assign empty string
           txtB.Text = string.empty;
           }
    } 

答案 3 :(得分:0)

基本上问题是在回发时必须重新创建动态控件。只要在回发期间将PageInInit中的动态控件重新添加到每一行,ViewState就应该注意填充控件属性(Text,Visible等)。

或者,如果您在RowCreated中创建控件,然后在RowDataBound中指定默认值,它还将保持动态控件。这是一个简化版本:

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        gvTest.DataSource = new int[] { 1, 2, 3 };
        gvTest.DataBind();
    }
}

protected void gvTest_RowCreated(object sender, GridViewRowEventArgs e)
{
    //note: e.Row.DataItem will be null during postback
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[0].Controls.Add(new TextBox());
    }
}

protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        var txtBox = (TextBox)e.Row.Cells[0].Controls[0];
        txtBox.Text = e.Row.DataItemIndex.ToString();
    }
}

protected void Clear_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvTest.Rows)
    {
        var txtBox = (TextBox)row.Cells[0].Controls[0];
        //txtBox.Text will have whatever value the user gave it client side
        txtBox.Text = "";
    }
}