我们可以定义一个类,为类加上特性、通过特性与数据库中的表、字段相关联,来获取数据库中的数据。而我们在加特性类时需要为它的字段设置个开关和主键来方便我们来写sql语句时所需要的条件。由于不同的操作所需要的字段不一样所以我们要根据业务建立多个user类,这要考虑类是否要继承user类。下面是一段代码:
user类:
 [TableAttr(TableName = "users")]
    class User
    {
        int id;
        [FieldAttr(FieldName = "id", IsPrimaryKey = true)]
        public int ID
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        string name;
        [FieldAttr(FieldName = "username", OnOff = true)]
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                if (Encoding.Default.GetByteCount(value) > 20)
                {
                    throw new Exception("用户名称过长,请保持在20个字符以内");
                }
                else
                {
                    name = value;
                }

            }
        }

        string password;
        [FieldAttr(FieldName = "userpw", OnOff = true)]
        public string Password
        {
            get
            {
                return password;
            }
            set
            {
                if (Encoding.Default.GetByteCount(value) > 20)
                {
                    throw new Exception("密码过长,请保持在20个字符以内");
                }
                else
                {
                    password = value;
                }

            }
        }
    }
    [TableAttr(TableName = "users")]
    class NewUser : User
    {
        string password;
        [FieldAttr(FieldName = "userpw", OnOff = false)]
        public string Password
        {
            get
            {
                return password;
            }
            set
            {
                if (Encoding.Default.GetByteCount(value) > 20)
                {
                    throw new Exception("密码过长,请保持在20个字符以内");
                }
                else
                {
                    password = value;
                }

            }
        }
    }
    [TableAttr(TableName = "users")]
    class New1User
    {
        int id;
        [FieldAttr(FieldName = "id")]
        public int ID
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        string name;
        [FieldAttr(FieldName = "username")]
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                if (Encoding.Default.GetByteCount(value) > 20)
                {
                    throw new Exception("用户名称过长,请保持在20个字符以内");
                }
                else
                {
                    name = value;
                }

            }
        }

        string password;
        [FieldAttr(FieldName = "userpw")]
        public string Password
        {
            get
            {
                return password;
            }
            set
            {
                if (Encoding.Default.GetByteCount(value) > 20)
                {
                    throw new Exception("密码过长,请保持在20个字符以内");
                }
                else
                {
                    password = value;
                }

            }
        }
    }
特性类:
 [AttributeUsage(AttributeTargets.Class,Inherited=true)]
    class TableAttr : Attribute
    {
        public string TableName
        {
            get;
            set;
        }
    }
    [AttributeUsage(AttributeTargets.Property)]
    class FieldAttr : Attribute
    {
        public string FieldName
        {
            get;
            set;
        }
        public bool OnOff
        {
            get;
            set;
        }
        public bool IsPrimaryKey
        {
            get;
            set;
        }
    }
建立了类之后我们就需要对它进行操作,所以我们建立useropt类,由于所有的类都可能是使用增删改查的功能,所以我们建立了opt类。
useropt类:
 class UserOpt
    {   
        public int Select(User user)
        {
            return opt.Select(user);
        }
        OPT opt = new OPT();
        public DataTable SelectAll()
        {
            return new OPT().SelectAll("users");
        }
        public int Insert(User user)
        {
            return opt.Insert(user);
        }
        public int Delete(User user)
        {
            return opt.Delete(user);
        }
        public int Update(User user)
        {
            return opt.Update(user);
        }
    }
opt类:
 class OPT
    {
        SqlConnection con = null;
        public OPT()
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString);

        }
        public DataTable SelectAll(string tablename)
        {
            string SQL = "select * from " + tablename;
            SqlDataAdapter DA = new SqlDataAdapter(SQL, con);
            DataTable DT = new DataTable();
            DA.Fill(DT);
            return DT;
        }

        public void GetTableMessage(Object Entity, out string tablename, out Dictionary<string, string> Dic)
        {
            //得到实体类的对应表名
            object[] AttrS = Entity.GetType().GetCustomAttributes(false);
            TableAttr TA = (TableAttr)AttrS[0];
            tablename = TA.TableName;
            //得到字段列表和其对应的值
            PropertyInfo[] PIArr = Entity.GetType().GetProperties();
            Dictionary<string, string> FieldDic = new Dictionary<string, string>();
            foreach (PropertyInfo pi in PIArr)
            {
                FieldAttr fa = (FieldAttr)pi.GetCustomAttributes(false)[0];
                if (fa.OnOff)
                {
                    FieldDic.Add(fa.FieldName, pi.GetValue(Entity, null).ToString());
                }
            }
            Dic = FieldDic;
        }
        public void GetTableMessage(Object Entity, out string tablename, out Dictionary<string, string> Dic, out Dictionary<string, string> PrimaryField)
        {
            Dic = new Dictionary<string, string>();
            PrimaryField = new Dictionary<string, string>();
            //得到实体类的对应表名
            object[] AttrS = Entity.GetType().GetCustomAttributes(false);
            TableAttr TA = (TableAttr)AttrS[0];
            tablename = TA.TableName;
            //得到字段列表和其对应的值
            PropertyInfo[] PIArr = Entity.GetType().GetProperties();
            Dictionary<string, string> FieldDic = new Dictionary<string, string>();
            foreach (PropertyInfo pi in PIArr)
            {
                FieldAttr fa = (FieldAttr)pi.GetCustomAttributes(false)[0];
                if (!fa.IsPrimaryKey)
                {
                    FieldDic.Add(fa.FieldName, pi.GetValue(Entity, null).ToString());
                }
                else
                {
                    PrimaryField.Add(fa.FieldName, pi.GetValue(Entity, null).ToString());
                }
            }
            Dic = FieldDic;

        }

        public int Select(Object tableentity)
        {

            string tablename;
            Dictionary<string, string> FieldDic = new Dictionary<string, string>();
            GetTableMessage(tableentity, out tablename, out FieldDic);
            //组装SQL语句
            string SQL = "select count(*) from " + tablename;
            int countindex = 0;
            foreach (string key in FieldDic.Keys)
            {

                if (countindex == 0)
                {
                    SQL += string.Format(" where {0}='{1}'", key, FieldDic[key]);
                }
                else
                {
                    SQL += string.Format(" and {0}='{1}'", key, FieldDic[key]);
                }

                countindex++;
            }

            SqlCommand cmd = new SqlCommand(SQL, con);
            int result = 0;
            try
            {
                con.Open();
                result = Convert.ToInt32(cmd.ExecuteScalar());
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                con.Close();
            }
            return result;
        }

        public int OptTable(string SQL)
        {
            SqlCommand cmd = new SqlCommand(SQL, con);
            int result = 0;
            try
            {
                con.Open();
                result = cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                con.Close();
            }
            return result;
        }

        public int Insert(Object tableentity)
        {
            string tablename;
            Dictionary<string, string> FieldDic = new Dictionary<string, string>();
            GetTableMessage(tableentity, out tablename, out FieldDic);
            //组装SQL语句
            string SQL = "insert into " + tablename + "(";
            foreach (string key in FieldDic.Keys)
            {
                SQL += key + ",";
            }
            SQL = SQL.TrimEnd(',') + ") values('";
            foreach (string key in FieldDic.Keys)
            {
                SQL += FieldDic[key] + "','";
            }
            SQL = SQL.TrimEnd('\'');
            SQL = SQL.TrimEnd(',') + ")";
            return OptTable(SQL);
        }
        public int Delete(Object tableentity)
        {
            string tablename;
            Dictionary<string, string> FieldDic = new Dictionary<string, string>();
            Dictionary<string, string> PrimaryDic = new Dictionary<string, string>();
            GetTableMessage(tableentity, out tablename, out FieldDic, out PrimaryDic);
            //组装SQL语句
            string SQL = "delete " + tablename;
            int countindex = 0;
            foreach (string key in PrimaryDic.Keys)
            {
                if (countindex == 0)
                {
                    SQL += string.Format(" where {0}='{1}'", key, PrimaryDic[key]);
                }
                else
                {
                    SQL += string.Format(" and {0}='{1}'", key, PrimaryDic[key]);

                }
                countindex++;
            }

            return OptTable(SQL);
        }

        public int Update(Object tableentity)
        {
            string tablename;
            Dictionary<string, string> FieldDic = new Dictionary<string, string>();
            Dictionary<string, string> PrimaryDic = new Dictionary<string, string>();
            GetTableMessage(tableentity, out tablename, out FieldDic, out PrimaryDic);
            //组装SQL语句
            string SQL = "update " + tablename + " set ";

            int countindex = 0;
            foreach (string key in FieldDic.Keys)
            {
                if (countindex != FieldDic.Count - 1)
                {
                    SQL += string.Format("{0}='{1}', ", key, FieldDic[key]);
                }
                else
                {
                    SQL += string.Format("{0}='{1}'", key, FieldDic[key]);
                }
                countindex++;
            }

            countindex = 0;
            foreach (string key in PrimaryDic.Keys)
            {
                if (countindex == 0)
                {
                    SQL += string.Format(" where {0}='{1}'", key, PrimaryDic[key]);
                }
                else
                {
                    SQL += string.Format(" and {0}='{1}'", key, PrimaryDic[key]);
                }
                countindex++;
            }
            return OptTable(SQL);
        }
}
然后我们在相应的界面层做相对应的操作就行了,下面主要谈谈怎样使用datagridwview控件:在我们需要显示数据库中的字段名时可以使用编辑列,人后添加一列。把DataProperName改成对应的数据库字段,把Headtext改成你需要显示的字段名。datagridwview出去空表行的属性为:AllowUserToAddRows设置为true;
可以通过dataGridView的cellclick事件去单击一行中的某个字段时去触发相应的操作。要注意cellcontentclick事件与cellclick的区别。
 User indexuser = new User();

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                indexuser.ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
                indexuser.Name = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
                Username_TB.Text = indexuser.Name;
                indexuser.Password = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
                Pssword_TB.Text = indexuser.Password;
            }
        }