用list来读出数据库的内容

来源:互联网 发布:java开发的发展方向 编辑:程序博客网 时间:2024/04/29 06:50

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        string constr = ConfigurationManager.ConnectionStrings["TblStudentconStr"].ConnectionString;
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            List<ClassModel> list = new List<ClassModel>();
            using (SqlConnection con = new SqlConnection(constr))
            {
                con.Open();
                string sp_name = "usp_T_TbClass_selectAll2";
                using (SqlCommand cmd = new SqlCommand(sp_name, con))
                 {
                    cmd.CommandType = CommandType.StoredProcedure;
                    using (SqlDataReader reader = cmd.ExecuteReader())
                      {
                          if (reader.HasRows)
                          {
                              while (reader.Read())
                              {
                                 ClassModel model = new ClassModel();
                                 model.clsName = reader.IsDBNull(reader.GetOrdinal("tClassName")) ? string.Empty : reader.GetString(reader.GetOrdinal("tClassName"));
                                 model.clsDesc = reader.IsDBNull(reader.GetOrdinal("tClassDesc")) ? string.Empty : reader.GetString(reader.GetOrdinal("tClassDesc"));
                                 list.Add(model);
                              }
                          }
                       }
                    }
                }
            dataGridView1.DataSource = list;//为其进行赋值
            }
        }
    }

 

原创粉丝点击