SqlMembershipProvider.FindUsersByName(String, Int32, Int32, Int32) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Obtém uma coleção de utilizadores de membros onde o nome de utilizador contém o nome de utilizador especificado para corresponder.
public:
override System::Web::Security::MembershipUserCollection ^ FindUsersByName(System::String ^ usernameToMatch, int pageIndex, int pageSize, [Runtime::InteropServices::Out] int % totalRecords);
public override System.Web.Security.MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords);
override this.FindUsersByName : string * int * int * int -> System.Web.Security.MembershipUserCollection
Public Overrides Function FindUsersByName (usernameToMatch As String, pageIndex As Integer, pageSize As Integer, ByRef totalRecords As Integer) As MembershipUserCollection
Parâmetros
- usernameToMatch
- String
O nome de utilizador a procurar.
- pageIndex
- Int32
O índice da página de resultados para devolver.
pageIndex é baseado em zero.
- pageSize
- Int32
O tamanho da página de resultados para devolver.
- totalRecords
- Int32
Quando este método regressa, contém o número total de utilizadores emparelhados.
Devoluções
A MembershipUserCollection que contém uma página de pageSizeMembershipUser objetos começando na página especificada por pageIndex.
Exceções
usernameToMatch é uma cadeia vazia ("") ou tem mais de 256 caracteres.
-ou-
pageIndex é inferior a zero.
-ou-
pageSize é inferior a 1.
-ou-
pageIndex multiplicado por pageSize mais pageSize menos um excede Int32.MaxValue.
usernameToMatch é null.
Exemplos
O seguinte exemplo de código utiliza o FindUsersByName método para recuperar informações de utilizador de membros e apresenta os resultados em páginas de dados.
Note
Este exemplo utiliza System.Web.Security.SqlMembershipProvider para chamar o SqlMembershipProvider especificado como defaultProvider o no ficheiro Web.config. Se precisares de aceder ao fornecedor padrão como tipo SqlMembershipProvider, podes castar a Provider propriedade da Membership classe. Para aceder a outros fornecedores configurados como um tipo específico de fornecedor, pode aceder a eles pelo nome configurado com a Providers propriedade da Membership classe e atribuí-los ao tipo específico de fornecedor.
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
int pageSize = 5;
int totalUsers;
int totalPages;
int currentPage = 1;
private void GetUsers()
{
UserGrid.DataSource = Membership.FindUsersByName(UsernameTextBox.Text,
currentPage - 1, pageSize, out totalUsers);
totalPages = ((totalUsers - 1) / pageSize) + 1;
// Ensure that we do not navigate past the last page of users.
if (currentPage > totalPages)
{
currentPage = totalPages;
GetUsers();
return;
}
UserGrid.DataBind();
CurrentPageLabel.Text = currentPage.ToString();
TotalPagesLabel.Text = totalPages.ToString();
if (currentPage == totalPages)
NextButton.Visible = false;
else
NextButton.Visible = true;
if (currentPage == 1)
PreviousButton.Visible = false;
else
PreviousButton.Visible = true;
if (totalUsers <= 0)
NavigationPanel.Visible = false;
else
NavigationPanel.Visible = true;
}
public void NextButton_OnClick(object sender, EventArgs args)
{
currentPage = Convert.ToInt32(CurrentPageLabel.Text);
currentPage++;
GetUsers();
}
public void PreviousButton_OnClick(object sender, EventArgs args)
{
currentPage = Convert.ToInt32(CurrentPageLabel.Text);
currentPage--;
GetUsers();
}
public void GoButton_OnClick(object sender, EventArgs args)
{
currentPage = 1;
GetUsers();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Find Users</title>
</head>
<body>
<form id="form1" runat="server">
<h3>User List</h3>
Username to Search for:
<asp:TextBox id="UsernameTextBox" runat="server" />
<asp:Button id="GoButton" Text=" Go " OnClick="GoButton_OnClick" runat="server" /><br />
<asp:Panel id="NavigationPanel" Visible="false" runat="server">
<table border="0" cellpadding="3" cellspacing="3">
<tr>
<td style="width:100">Page <asp:Label id="CurrentPageLabel" runat="server" />
of <asp:Label id="TotalPagesLabel" runat="server" /></td>
<td style="width:60"><asp:LinkButton id="PreviousButton" Text="< Prev"
OnClick="PreviousButton_OnClick" runat="server" /></td>
<td style="width:60"><asp:LinkButton id="NextButton" Text="Next >"
OnClick="NextButton_OnClick" runat="server" /></td>
</tr>
</table>
</asp:Panel>
<asp:DataGrid id="UserGrid" runat="server"
CellPadding="2" CellSpacing="1"
Gridlines="Both">
<HeaderStyle BackColor="darkblue" ForeColor="white" />
</asp:DataGrid>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Dim pageSize As Integer = 5
Dim totalUsers As Integer
Dim totalPages As Integer
Dim currentPage As Integer = 1
Private Sub GetUsers()
UserGrid.DataSource = Membership.FindUsersByName(UsernameTextBox.Text, _
currentPage - 1, pageSize, totalUsers)
totalPages = ((totalUsers - 1) \ pageSize) + 1
' Ensure that we do not navigate past the last page of users.
If currentPage > totalPages Then
currentPage = totalPages
GetUsers()
Return
End If
UserGrid.DataBind()
CurrentPageLabel.Text = currentPage.ToString()
TotalPagesLabel.Text = totalPages.ToString()
If currentPage = totalPages Then
NextButton.Visible = False
Else
NextButton.Visible = True
End If
If currentPage = 1 Then
PreviousButton.Visible = False
Else
PreviousButton.Visible = True
End If
If totalUsers <= 0 Then
NavigationPanel.Visible = False
Else
NavigationPanel.Visible = True
End If
End Sub
Public Sub NextButton_OnClick(sender As Object, args As EventArgs)
currentPage = Convert.ToInt32(CurrentPageLabel.Text)
currentPage += 1
GetUsers()
End Sub
Public Sub PreviousButton_OnClick(sender As Object, args As EventArgs)
currentPage = Convert.ToInt32(CurrentPageLabel.Text)
currentPage -= 1
GetUsers()
End Sub
Public Sub GoButton_OnClick(sender As Object, args As EventArgs)
currentPage = 1
GetUsers()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Find Users</title>
</head>
<body>
<form id="form1" runat="server">
<h3>User List</h3>
Username to Search for:
<asp:TextBox id="UsernameTextBox" runat="server" />
<asp:Button id="GoButton" Text=" Go " OnClick="GoButton_OnClick" runat="server" /><br />
<asp:Panel id="NavigationPanel" Visible="False" runat="server">
<table border="0" cellpadding="3" cellspacing="3">
<tr>
<td style="width:100">Page <asp:Label id="CurrentPageLabel" runat="server" />
of <asp:Label id="TotalPagesLabel" runat="server" /></td>
<td style="width:60"><asp:LinkButton id="PreviousButton" Text="< Prev"
OnClick="PreviousButton_OnClick" runat="server" /></td>
<td style="width:60"><asp:LinkButton id="NextButton" Text="Next >"
OnClick="NextButton_OnClick" runat="server" /></td>
</tr>
</table>
</asp:Panel>
<asp:DataGrid id="UserGrid" runat="server"
CellPadding="2" CellSpacing="1"
Gridlines="Both">
<HeaderStyle BackColor="darkblue" ForeColor="white" />
</asp:DataGrid>
</form>
</body>
</html>
Observações
FindUsersByName devolve uma lista de utilizadores de membros para os quais o nome de utilizador contém uma correspondência com o fornecido usernameToMatch para a configuração ApplicationName.
Procura SqlMembershipProvider um nome de utilizador que corresponda ao valor do usernameToMatch parâmetro, usando a cláusula LIKE. Caracteres coringa do SQL Server podem ser incluídos com o valor do parâmetro. Por exemplo, se o usernameToMatch parâmetro estiver definido como "user1", então a informação do utilizador com o nome de utilizador "user1" é devolvida, caso exista. Se o usernameToMatch parâmetro for definido como "user%", então a informação do utilizador para utilizadores com o nome de utilizador "user1", "user2", "user_admin", entre outros, é devolvida.
Os resultados devolvidos por FindUsersByName são limitados pelos pageIndex parâmetros e.pageSize O pageSize parâmetro identifica o número máximo de MembershipUser objetos a devolver no MembershipUserCollection. O pageIndex parâmetro identifica qual página de resultados devolver, onde zero identifica a primeira página. O totalRecords parâmetro é um out parâmetro definido para o número total de utilizadores de membros para o .applicationName Por exemplo, se houver 13 utilizadores para o configurado applicationName, e o pageIndex valor for 1 com a pageSize de 5, os MembershipUserCollection retornados conterão o sexto ao décimo utilizador retornado. O totalRecords parâmetro seria definido para 13.
Os espaços à frente e à saída são cortados a partir do usernameToMatch valor do parâmetro.