如何在 Visual C# 中从 Active Directory 填充网格视图
本文关键字:Directory 填充 网格 视图 Active 中从 Visual | 更新日期: 2023-09-27 17:56:42
我目前正在使用带有 ASP.NET 框架的Visual C#,并且我正在尝试通过DataTable
填充GridView。信息是从活动目录获取的。
我的网格视图是这样声明的:
<asp:GridView ID="grdvList" runat="server" AutoGenerateColumns="False" Width="567px">
<Columns>
<asp:BoundField HeaderText="Name" ReadOnly="True" />
<asp:BoundField HeaderText="Phone" ReadOnly="True" />
<asp:BoundField HeaderText="Email" ReadOnly="True" />
</Columns>
</asp:GridView>
我尝试填充网格视图的代码如下:
DirectoryEntry entry = new DirectoryEntry(ConfigurationManager.AppSettings["LDAP"]);
DirectorySearcher search = new DirectorySearcher(entry)
{
SearchScope = SearchScope.Subtree,
Filter = "(&(objectClass=user)(physicalDeliveryOfficeName=Dartmouth))"
};
search.PropertiesToLoad.Add("sAMAccountName");
SearchResultCollection result = search.FindAll();
DataTable table = new DataTable();
DataRow dr = null;
//Add columns to DataTable
table.Columns.Add("Name", System.Type.GetType("System.String"));
table.Columns.Add("Phone", System.Type.GetType("System.String"));
table.Columns.Add("Email", System.Type.GetType("System.String"));
foreach (SearchResult sr in uList)
{
dr = table.NewRow();
DirectoryEntry DE = sr.GetDirectoryEntry();
dr["Name"] = DE.Properties["givenName"].Value.ToString();
dr["Phone"] = DE.Properties["telephoneNumber"].Value.ToString();
dr["Email"] = DE.Properties["mail"].Value.ToString();
table.Rows.Add(dr);
}
table.AcceptChanges();
grdvList.DataSource = table;
grdvList.DataBind();
目前,当我运行它时,它会抛出一个
对象引用未设置为对象错误的实例
在这一行:
dr["Phone"] = DE.Properties["telephoneNumber"].Value.ToString();
任何帮助绝对不胜感激!
在您的方案中,您可以避免使用旧技术的 DataTable 和 DataSet。如今,除非我们别无选择,否则我们尽量不使用它们。
对于 NullReferenceException,您希望在获取其Value
之前确保DE.Properties["mail"]
不为空。
例如
DirectoryEntry entry = new DirectoryEntry(ConfigurationManager.AppSettings["LDAP"]);
DirectorySearcher search = new DirectorySearcher(entry)
{
SearchScope = SearchScope.Subtree,
Filter = "(&(objectClass=user)(physicalDeliveryOfficeName=Dartmouth))"
};
search.PropertiesToLoad.Add("sAMAccountName");
SearchResultCollection result = search.FindAll();
var users = result.Cast<SearchResult>().Select(sr => sr.GetDirectoryEntry())
.Select(de => new
{
Name = de.Properties["Name"] != null ? de.Properties["Name"].Value.ToString() : "",
Phone = de.Properties["Phone"] != null ? de.Properties["Phone"].Value.ToString() : "",
Email = de.Properties["Email"] != null ? de.Properties["Email"].Value.ToString() : "",
}).ToList();
grdvList.DataSource = users;
grdvList.DataBind();