加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

C#使用list<T>来作为datagridview 的数据源进行数据的显示

(2012-04-14 14:32:47)
标签:

学习总结

it

分类: C#

 public partial class Form2 : Form
    {
        private SqlConnection con = null;
        private SqlCommand cmd = null;
        private SqlDataReader dr = null;
        private List<UserInfo> listUser = null;
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            using (con = new SqlConnection("Data Source=.;DataBase=TEST;Uid=sa;Pwd=123456;"))
            {
                using (cmd = new SqlCommand())
                {
                    cmd.CommandText = "select * from dbo.UserInfo_tb";
                    cmd.Connection = con;
                    try
                    {
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }
                        listUser = new List<UserInfo>();
                        dr = cmd.ExecuteReader();
                        while (dr.Read())
                        {
                            UserInfo user = new UserInfo { UserID = dr.GetString(0), UserName = dr.GetString(1), Eamil = dr.GetString(2), Telephone = dr.GetString(3) };
                            listUser.Add(user);
                        }
                        dataGridView1.DataSource = listUser;
                    }
                    catch (DataException ex)
                    {
                        MessageBox.Show(ex.Message, "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        if (con.State == ConnectionState.Open)
                        {
                            con.Close();
                        }
                    }
                }
            }
        }
    }
    public class UserInfo
    {
        public string UserID { get; set; }
        public string UserName { get; set; }
        public string Eamil { get; set; }
        public string Telephone { get; set; }
    }

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有