解决ASP.Net之外的争论

时间:2017-01-28 05:21:18

标签: c# asp.net

以下是我获取异常的代码。

protected void AddButton_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        int empId = Id++;
        Employees employees = new Employees();
        employees.AddEmployee(new Employee(empId, txtName.Text,              txtEmail.Text, txtMobile.Text, txtLandline.Text, txtWebsite.Text, txtAddress.Text));
        foreach (Employee employee in employees.GetList())
        {
            if (employee.Name.Equals(txtName.Text))
            {
                Repeater1.DataSource = employee;
                Repeater1.DataBind();
            }
        }
    }
    else
    {
        contactsForm.Style.Add("display", "block");
    }

这是例外 **类型' System.ArgumentException'的例外情况发生在System.Web.dll中但未在用户代码中处理

附加信息:Repeater1使用了无效的数据源。有效的数据源必须实现IListSource或IEnumerable。**

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string MobileNumber { get; set; }
    public string LandLineNumber { get; set; }
    public string Website { get; set; }
    public string Address { get; set; }

    public Employee(int id, string name, string email, string mobilenumber, string landlinenumber, string website, string address)
    {
        Id = id;
        Name = name;
        Email = email;
        MobileNumber = "+91 " + mobilenumber;
        LandLineNumber = landlinenumber;
        Website = website;
        Address = address;
    }
}
public class Employees
{
    List<Employee> ListOfEmployee = new List<Employee>();
    public void AddEmployee(Employee employee)
    {
        ListOfEmployee.Add(employee);
    }
    public List<Employee> GetList()
    {
        return ListOfEmployee;
    }
}

这是员工类。

我如何解决该异常。

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>'></asp:Label>
        <asp:Label ID="Label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Email") %>'></asp:Label>
        <asp:Label ID="Label3" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "MobileNumber") %>'></asp:Label>
    </ItemTemplate>
</asp:Repeater>

这是.aspx代码

2 个答案:

答案 0 :(得分:0)

转发器期待一个集合,但是你只传递一个对象。试一试。

if (employee.Name.Equals(txtName.Text))
{
      Repeater1.DataSource = new List<Employee>(){ employee }.AsEnumerable();
      Repeater1.DataBind();
}

答案 1 :(得分:0)

试一试

var filteredEmployees = employees.GetList().Where(p=> p.Name.Equals(txtName.Text)).ToList();
Repeater1.DataSource = filteredEmployees;
Repeater1.DataBind();