【问题标题】:how to show data in labels in c#c#如何在标签中显示数据
【发布时间】:2013-12-30 10:17:43
【问题描述】:

我有两层,一个从数据库获取结果的数据层和一个在标签控件中显示数据的 UI 层 这是数据层的代码

public class Test_DAL
{
    public DataSet getEMP(string name1)
    {

        string conn = System.IO.File.ReadAllText("Connect.txt");
        //string conn="Data Source=.\\sqlexpress;Initial Catalog=pss;Integrated Security=True";
        //string conn = ConfigurationManager.ConnectionStrings["constr"].ToString();
        SqlConnection dbconn = new SqlConnection(conn);
        dbconn.Open();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = new SqlCommand("select * from pss where Emp_code='"+name1+"'", dbconn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        dbconn.Close();
        return ds;
    }

}

而且是UI层的代码

    private void btn_search_Click(object sender, EventArgs e)
    {

        string empcode=txt_empcode.Text;
        Test_DAL obj1= new Test_DAL();
        obj1.getEMP(empcode);
        //dg.DataSource = obj1.getEMP(empcode).Tables[0];


    }

我的问题是如何在标签上显示数据

提前非常感谢

【问题讨论】:

    标签: c# sql .net labels data-layer


    【解决方案1】:

    您的要求不是很明确。只是为了让您了解如何做是

    private void btn_search_Click(object sender, EventArgs e)
        {
    
            string empcode=txt_empcode.Text;
            Test_DAL obj1= new Test_DAL();
            DataSet ds = obj1.getEMP(empcode);
            //displays the data of row 1 column 1 of table 1
            yourLabel.Text  = ds.Tables[0].Rows[0][0].ToString(); 
    
    
        }
    

    注意:这既不是最好的也不是最合适的做事方式。没有任何异常处理等。

    【讨论】:

      【解决方案2】:

      我会让GetEmployee 返回一个实际的Employee 类型。

      public Employee getEMP(string name1)
      {
          // left out some of your code intentionally
          da.SelectCommand = new SqlCommand("select * from pss where Emp_code='"+name1+"'", dbconn);
          DataSet ds = new DataSet();
          da.Fill(ds);
          dbconn.Close();
          return new Employee(ds);
      }
      

      定义一个类Employee,看起来像

      public class Employee
      {
          public string Name { get; set; }
          /* Other properties ... */ 
      
          public Employee(DataSet dataset)
          {
              Name = ds.Tables[0].Rows[0][0].ToString();
              // etc
          }
      }
      

      这样,您的 UI 层可以与实际对象(实体)对话,而不必费心处理 DataSets 中的幻数,例如依赖于 UI 中的数据绑定。

      private void btn_search_Click(object sender, EventArgs e)
      {
          string empcode=txt_empcode.Text;
          Test_DAL obj1= new Test_DAL();
      
          var employee = obj1.getEMP(empcode);
      
          dg.DataSource = employee;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-07
        • 1970-01-01
        • 1970-01-01
        • 2021-08-19
        • 2021-10-12
        相关资源
        最近更新 更多