簡體   English   中英

甚至找不到在行數據綁定網格視圖上添加的復選框控件

[英]cannot find checkbox control added on rowdatabound grid view even

我已添加控制權

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chk = new CheckBox();
        chk.EnableViewState = true;
        chk.Enabled = true;
        chk.ID = "chkb";


        DataRowView dr = (DataRowView)e.Row.DataItem;
        chk.Checked = (dr[0].ToString() == "true");


        e.Row.Cells[1].Controls.Add(chk);
        e.Row.TableSection = TableRowSection.TableBody;
    }

並試圖找到

     if (GridView2.Rows.Count>0)
    {
        foreach (GridViewRow row in GridView2.Rows)
        {
            CheckBox cb =(CheckBox) GridView2.Rows[2].Cells[1].FindControl("chkb");
            if (cb != null && cb.Checked)
            {
                Response.Write("yest");
            }

        }
    }

但是我找不到它...實際上我的問題是我需要創建一個動態列表..為此,我正在使用gridview

您需要在每個回發中創建動態控件,因為它已在當前生命周期的結尾處處理。 但是,當您對GridView進行數據綁定時,只會觸發RowDataBound通常僅if(!IsPostBack) (頁面首次加載)時執行此操作。

您應該在RowCreated創建動態控件,而不是在每次回發時都調用它。 由於RowCreated首先觸發RowCreatedRowCreated可以根據需要在RowDataBound這些控件進行數據綁定。

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chk = new CheckBox();
        chk.EnableViewState = true;
        chk.Enabled = true;
        chk.ID = "chkb";
        e.Row.Cells[1].Controls.Add(chk);
    }
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var chk = (CheckBox)e.Row.FindControl("chkb");
        // databind it here according to the DataSource in e.Row.DataItem
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM