怎样从数据库中动态读取数据?比如一个人的个人信息想从数据库中读取写到form窗体中,要怎么实现?

解决方案 »

  1.   

    不知道你想怎么个动态法?
    根据个人信息设置查询调件,在数据库中查询到后,赋给窗体中的变量,显示出来,就行了。
    要用到SQL语言。
      

  2.   

       // 数据库连接字符串
       string connString = "Data Source=.;Initial Catalog=Sql;User ID=sa;Pwd=123";
      // 创建 Connection 对象
      SqlConnection connection = new SqlConnection(connString);
       // 打开数据库连接
        connection.Open();
        string sqlString = "select * from Student";
        SqlCommand comm = new SqlCommand(sqlString,connection);
        SqlDataReader dr = comm.ExecuteReader();
        if (dr.Read())
        {
            string ID = dr.GetString(dr.GetOrdinal("stuId"));
            string Name = dr.GetString(dr.GetOrdinal("stuName"));
            
                  
         }
    我想知道,要怎么把结果显示在窗体中呢?              
      

  3.   

    晕倒label1.Text = Name;
    ...
      

  4.   

    你先去了解 ADO.Net
    就知道什么是动态了
      

  5.   

    可是数据库中有一些数据,都要这么写吗?labeln.text?能不能用个for循环写呢?还是我的for循环的思路就不对?
      

  6.   

    要看你具体的问题。如果开成label动态数组,语法上来说就可以用for循环。
    不过我觉得你好像没有考虑到重点,难点应该在数据库方面,窗体显示是基本的,也很简单啊。
      

  7.   

    那可以通过控件名字查出控件的引用。比如:Label label = (Label)this.Controls.Find("label" + i, false)[0];
    label.Text = dr.GetString(i);
      

  8.   

    Form中放个DataGridView,
    根据ID从表里查询就可以了。
      

  9.   

    9楼,麻烦你,能不能有些代码示例呢?我是真的不懂那个要怎么做目前是考虑到要用DataGridView了,就是不知道怎么操作
      

  10.   

    设计
    假设有一张数据表student,根据表的字段编写Student类public class Student
    {
       public Student(){}
       public Student(string name,int age,string hobby)
      {
             this.Name = name;
             this.Age = age;
             this.Hobby = hobby;
      }
       public int ID{get;set;}
       public string Name{get;set;}
       public int Age{get;set;}
       public string Hobby{get;set;}
    }
    编写数据访问层类,根据ID查询student信息public List<Student> GetStudentByID(int id)
    {
        List<Student> list = new List<Student>();
        
        using(SqlConnection connection = new SqlConnection("数据库连接字符串"))
       {
            string sql = string.Format("select * from student where ID = @ID");
            
            using(SqlCommand objCommand = new SqlCommand(sql,connection))
           {
                 connection.Open();
                 
                 using(SqlDataReader objReader = objCommand.ExecuteReader())
                {
                    if(objReader.HasRows)
                   {
                      if(objReader.Read())
                      {
                         Student student = new Student(objReader["Name"].ToString(),Convert.ToInt32(objReader["Age"]),objReader["Hobby"].ToString());                     list.Add(student);
                      }
                   }
                }
           }
       }    return list;
    }
    创建窗体,拖放一个DataGridView,设置三列,分别存储姓名,年龄,爱好,并且设置其DatapropertyName属性与表中字段一致。然后将数据访问层的返回的List集合赋值与DataGridViewthis.DataGridView1.DataSource = 数据层返回来的List集合;