在gridview

时间:2016-08-08 02:16:01

标签: c# asp.net gridview

我需要在gridview中放置错误消息我该怎么做

 public class EmployeeMetadata
    {
      [Required]
      [StringLength(20,ErrorMessage="First Name must be less than 20 characters.")]
      public string FirstName { get; set; }

      [Required]
      [StringLength(20, ErrorMessage = "Last Name must be less than 20 characters.")]
      public string LastName { get; set; }

      [Required]
      [StringLength(10, ErrorMessage = "Country must be less than 10 characters.")]
      public string Country { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

如果你需要填充GridView,那么你需要摆脱字符串连接并开始以OOP方式思考。

GridView可以使用任何实现IEnumerable的构造填充,因此您可以这样做:

VB:

Dim ListOfErrors as New List(Of MyError)

C#:

List<MyError> ListOfErrors = new List<MyError>();

其中MyError(最低限度)定义为:

VB:

Class MyError
    Public Property RowNumber as Int32 = 0
    Public Property Error as String = String.Empty
End Class

C#:

class MyError
{
    public int RowNumber { get; set; }
    public String Error { get; set; }
}

然后,当您发现错误时,而不是构建连接字符串,而是填充List:

VB:

Dim AnError as New MyError
AnError.RowNumber = i
AnError.Error = "Some error"

ListOfErrors.Add( AnError )

C#:

MyError AnError = new MyError();
AnError.RowNumber = i;
AnError.Error = "Some error";

ListOfErrors.Add( AnError );

当你找到错误时,将列表绑定到GridView

VB:

// this will autogenerate columns for all public properties in MyError
Gridview1.AutoGenerateColumns = True

// attach List
Gridview1.DataSource = ListOfErrors

// Bind
Gridview1.DataBind()

C#:

Gridview1.AutoGenerateColumns = true;
Gridview1.DataSource = ListOfErrors;
Gridview1.DataBind();