0

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

我正在使用 .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);
}

}

从这里开始,所有复选框都显示为未选中...

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

4

1 回答 1

-1

这样做。检查 rowDatabound 事件中的列在哪里是真假,并且仅在此处添加控件。

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);
    }
}
于 2013-09-21T06:00:22.903 回答