在ASP中为DataGrid添加角色列.NET Web表单



我有Web表单在ASP。. NET中,我想在我的应用程序中显示与所有用户的表。应该有用户名,用户电子邮件,最后活动日期和用户角色。

目前我有这个:

<asp:DataGrid id="UserGrid" runat="server"
            CellPadding="2" CellSpacing="1"
            Gridlines="Both" AutoGenerateColumns="false">
  <Columns>
    <asp:BoundColumn DataField="UserName" ReadOnly="False" HeaderText="Name" />
    <asp:BoundColumn DataField="Email" ReadOnly="True" HeaderText="Email" />
    <asp:BoundColumn DataField="LastActivityDate" ReadOnly="True" HeaderText="Last activity"/>
</Columns>
<HeaderStyle BackColor="darkblue" ForeColor="white" />
</asp:DataGrid>

_

UserGrid.DataSource = Membership.GetAllUsers();
UserGrid.DataBind();

我想向这个DataGrid添加列角色。我该怎么做呢?

在下一步中,我想添加带有按钮的列来编辑用户信息,管理他的角色等

按如下所示为GridView添加列

 <asp:GridView id="UserGrid" runat="server"
                CellPadding="2" CellSpacing="1"
                Gridlines="Both" AutoGenerateColumns="false">
      <Columns>
        <asp:BoundColumn DataField="UserName" ReadOnly="False" HeaderText="Name" />
        <asp:BoundColumn DataField="Email" ReadOnly="True" HeaderText="Email" />
        <asp:BoundColumn DataField="LastActivityDate" ReadOnly="True" HeaderText="Last activity"/>
        <asp:TemplateField HeaderText="User Roles" ItemStyle-Width="30%">
                                                            <ItemTemplate>
                                                                <asp:Label ID="lblrole" runat="server" %>'></asp:Label>
                                                            </ItemTemplate>
                                                        </asp:TemplateField>
    </Columns>
    <HeaderStyle BackColor="darkblue" ForeColor="white" />
    </asp:GridView>

声明一个全局变量来保存用户角色。

string[] roles;

在页面加载得到你的数据

protected void page_load(object sender,EventArgs e)
{
if(!IsPostBack)
{
string[] roles=GetUserRoles();
}
}

在RowDataBound事件中添加数据到gridview

    protected void UserGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       if(e.Row.RowType= DataControlRowType.DataRow)
      {
        e.Row.FindControl("lblrole").Text=roles[e.Row.RowIndex];
       }
    }

如果数据顺序不匹配,则对两个集合进行排序。这里DataField是您的数据库列名或您在查询中使用的别名

最新更新