使用for循环传递DATAROW中的值

时间:2015-01-08 09:31:02

标签: c# winforms datatable

我已为UserLogin定义了一种方法。在这里,我将值传递给DATAROW。 这是代码:

public class ApplicationUser
    {        
        public int Id { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string UserRole { get; set; }            
        public DateTime DateOfRegister { get; set; }

        public bool UserLogin(string Username, string Password)
        {            
            string strQuery = string.Format("select Username, Password from ApplicationUser where Username = '{0}' and Password = '{0}'", Username, Password);            
            DataTable dt = helper.ExecuteDataSet(strQuery).Tables[0];
            if (dt.Rows.Count > 0)
            {
                DataRow ro = dt.Rows[0];
                this.Id = ro.Field<int>("Id");
                this.Username = ro.Field<string>("Username");
                this.Password = ro.Field<string>("Password");                   
                this.UserRole = ro.Field<string>("UserRole");
                return true;
            }
            else
                return false;

        }
    }

如何使用 FOR循环进行以下操作,是否可以?

DataRow ro = dt.Rows[0];    
    this.Id = ro.Field<int>("Id");
    this.Username = ro.Field<string>("Username");
    this.Password = ro.Field<string>("Password");       
    this.UserRole = ro.Field<string>("UserRole");

1 个答案:

答案 0 :(得分:0)

您需要在一个实体

下声明以下代码
   public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string UserRole { get; set; }            
    public DateTime DateOfRegister { get; set; }

然后在您的班级制作列表或实体集合中,并添加到该列表或集合中以获取可用行。

List<Entity> lstEntity = new List<Entity>();
if (dt.Rows.Count > 0)
            {
            foreach( Datarow r in dt.Rows){ 
                Entity e= new Entity();   
                e.Id = r.Field<int>("Id");
                e.Username = r.Field<string>("Username");
                e.Password = r.Field<string>("Password");                   
                e.UserRole = r.Field<string>("UserRole");
                lstEntity.Add(e);
               }
                return true;
            }