Asp.net Gridview Rowdata即将空置且未经检查

时间:2013-09-21 04:58:10

标签: c# asp.net gridview custom-controls

我有一个要求,我需要动态添加列名和rowdatabound值。我已设法动态获取列名。根据我的需要,我希望值以网格行中的复选框的形式显示以检查的形式或未经检查的条件,但在这里,每件事都是以未经检查的形式出现..

我正在使用.net成员资格角色表...

这是我的gridview动态列分配代码..

protected void BindGridviewData()
{

    var role = from MembershipUser u in Membership.GetAllUsers()
               select new
               {
                   User = u.UserName,
                   Role = string.Join(",", Roles.GetRolesForUser(u.UserName))
               };


    DataTable dTable = new DataTable();
    string[] rolesarr = Roles.GetAllRoles();
    // add column for user name 
    dTable.Columns.Add("Username", typeof(string));
    // then add all the roles as columns 
    Array.ForEach(rolesarr, r => dTable.Columns.Add(r));

    List<string> tempfield = new List<string>();

    foreach (DataColumn column in dTable.Columns)
    {
       string ColName = column.ColumnName;
       tempfield.Add(ColName);
    }

    for (int i = 0; i < tempfield.Count; i++)
    {

    string tempfieldname = tempfield[i];
    TemplateField temp = new TemplateField();
    if (i == 0)
    {
        temp.HeaderText = tempfieldname;

        tempfieldname = string.Empty;
    }
    else {

        temp.ItemTemplate = new MyTemplate();
        temp.HeaderText = tempfieldname;
        tempfieldname = string.Empty;
    }
    GridView1.Columns.Add(temp);
    }

现在我在这里检查要检查或未检查的值..

foreach (MembershipUser u in Membership.GetAllUsers())
    {
        DataRow dRow = dTable.NewRow();
        dRow[0] = u.UserName;

        string[] roles = Roles.GetRolesForUser(u.UserName);

        dRow[1] = roles.Contains("Admin") ? true : false;
        dRow[2] = roles.Contains("DPAO User") ? true : false;
        dRow[3] = roles.Contains("GeneralUser") ? true : false;
        dTable.Rows.Add(dRow);
    }
    GridView1.DataSource = dTable;
    GridView1.DataBind();
}

此处的值在 dTable 中正常,但一旦流程进入rowdatabound事件

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

}

在rowdatabound上,事件流自动移动到自定义控件类,这是......

public class MyTemplate : ITemplate
  {
public void InstantiateIn(Control container)
{
    CheckBox chk = new CheckBox();
    chk.ID = "chk";
    container.Controls.Add(chk);
}

}

从此处所有复选框都显示为未选中...

请大家帮帮我.. 提前谢谢......

1 个答案:

答案 0 :(得分:-1)

以这种方式做到这一点。在rowDatabound事件中检查列的位置为f​​alse,仅在此处添加控件。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox cb = new CheckBox();
        if(e.Row.Cells["Column Name"].toString == true ){
             cb.Checked = true; 
        }else{
             cb.Checked = false;   
        }
        e.Row.Cells["Column Name"].Controls.Add(cb);
    }
}