[英]Dynamic CheckBoxes in GridView Rows are not showing properly in ASP.NET
我有一个gridview,其中我在gridview行中显示要检查或未选中的值。现在,我想在gridview行中动态显示这些值,但不会发生..所有这些复选框都将被选中,而结果应该是不同..
这是我的硬编码代码条件,以显示结果很好...
string[] rolesarr = Roles.GetAllRoles();
DataTable dTable = new DataTable();
dTable.Columns.Add("Select", typeof(bool));
dTable.Columns.Add("Username", typeof(string));
Array.ForEach(rolesarr, r => dTable.Columns.Add(r, typeof(bool)));
foreach (MembershipUser u in Membership.GetAllUsers())
{
DataRow dRow = dTable.NewRow();
dRow[0] = false;
dRow[1] = u.UserName;
string[] roles = Roles.GetRolesForUser(u.UserName);
dRow[2] = roles.Contains("Admin") ? true : false;
dRow[3] = roles.Contains("DPAO User") ? true : false;
dRow[4] = roles.Contains("GeneralUser") ? true : false;
dTable.Rows.Add(dRow);
}
GridView1.DataSource = dTable;
GridView1.DataBind();
现在,我想让我编写代码的条件动态化。
string[] rolesarr = Roles.GetAllRoles();
DataTable dTable = new DataTable();
dTable.Columns.Add("Select", typeof(bool));
dTable.Columns.Add("Username", typeof(string));
Array.ForEach(rolesarr, r => dTable.Columns.Add(r, typeof(bool)));
foreach (MembershipUser u in Membership.GetAllUsers())
{
DataRow dRow = dTable.NewRow();
dRow[0] = false;
dRow[1] = u.UserName;
string[] roles = Roles.GetRolesForUser(u.UserName);
for (int i = 0; i < roles.Length; i++)
{
string rol = roles[i];
for (int j = 2; j < dTable.Columns.Count; j++)
{
dRow[j] = roles.Contains(rol) ? true : false;
}
}
dTable.Rows.Add(dRow);
}
GridView1.DataSource = dTable;
GridView1.DataBind();
这是我的复选框的RowDatabound事件。
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox c0 = (CheckBox)e.Row.Cells[0].Controls[0];
CheckBox c2 = (CheckBox)e.Row.Cells[2].Controls[0];
CheckBox c3 = (CheckBox)e.Row.Cells[3].Controls[0];
CheckBox c4 = (CheckBox)e.Row.Cells[4].Controls[0];
c0.Enabled = c2.Enabled = c3.Enabled = c4.Enabled = true;
}
}
请大家帮我..提前谢谢...
问题应该是您提供的双循环。
根据您的硬编码代码,您想要在数组roles
rolesarr
和用户roles
之间映射,以显示为每个用户检查了哪些角色。
要在索引2到4处设置数据行的值,您将有两个循环,第一个循环重复rolesarr
数组,第二个循环重复roles
数组并在第二个循环中进行比较
这是我的意思是代码:
string[] rolesarr = Roles.GetAllRoles();
DataTable dTable = new DataTable();
dTable.Columns.Add("Select", typeof(bool));
dTable.Columns.Add("Username", typeof(string));
Array.ForEach(rolesarr, r => dTable.Columns.Add(r, typeof(bool)));
foreach (MembershipUser u in Membership.GetAllUsers())
{
DataRow dRow = dTable.NewRow();
dRow[0] = false;
dRow[1] = u.UserName;
string[] roles = Roles.GetRolesForUser(u.UserName);
for (int i = 0; i < rolesarr.Length; i++)
{
for (int j = 0; j < roles.Length; j++)
{
if (rolesarr[i] == roles[j])
{
dRow[i + 2] = true;
break;
}
}
}
dTable.Rows.Add(dRow);
}
GridView1.DataSource = dTable;
GridView1.DataBind();
请注意,在第二个循环中,我将数据行索引用作i + 2
(dRow [i + 2]) ,因为您的角色列始于index = 2,而不是0,并且长度必须等于rolesarr.Length
作为角色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.