我目前正在使用 Visual C# 和 ASP.NET 框架,并且我正在尝试通过 DataTable
填充 GridView。正在从 Active Directory 获取信息。
我的 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>
我尝试填充 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();
目前当我运行它时,它会抛出一个
Object reference not set to an instance of an object error
在这一行:
dr["Phone"] = DE.Properties["telephoneNumber"].Value.ToString();
非常感谢任何帮助!
最佳答案
在您的场景中,您可以避免使用旧技术的DataTable 和DataSet。这些天来,我们尽量不使用它们,除非我们别无选择。
对于 NullReferenceException,您要确保 DE.Properties["mail"]
在获取其 Value 之前不为 null
。
例如,
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();
关于c# - 如何在 Visual C# 中从 Active Directory 填充 gridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38336241/