0

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

4 回答 4

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;
                    }
                }
            }
        }

希望这会有所帮助

于 2013-11-14T04:59:15.097 回答
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;
           }
    } 
于 2013-11-13T13:18:07.923 回答
0

请尝试以下代码:

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

谢谢

于 2013-11-13T13:09:39.010 回答
0

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

或者,如果您在 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 = "";
    }
}
于 2013-11-13T15:14:37.740 回答