如何从asp.net&中的数据库中检索表数据的所有值以字符串/标签显示

时间:2014-01-03 05:46:25

标签: c# asp.net

con.Open();
string query = "select Calf_ID,Plant,date1,Event from Holiday_Master ";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();

while (dr.Read())
{
    Label1.Text = dr["Calf_ID"].ToString();
    Label2.Text = dr["Plant"].ToString();
    Label3.Text = dr["date1"].ToString();
    Label4.Text = dr["Event"].ToString();
}

con.Close();

我正在使用此代码,但它只从表中检索一行我想要表中的所有数据。

4 个答案:

答案 0 :(得分:5)

您可以尝试网格视图

con.Open();
string query = "select Calf_ID,Plant,date1,Event from Holiday_Master ";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;

using (SqlDataReader dr = cmd.ExecuteReader())
{
   GridView1.DataSource = dr;
   GridView1.DataBind();
}

con.Close();

答案 1 :(得分:1)

con.Open();
string query = "select Calf_ID,Plant,date1,Event from Holiday_Master ";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();

while (dr.Read())
{

    Label1.Text += dr["Calf_ID"].ToString();
    Label2.Text += dr["Plant"].ToString();
    Label3.Text += dr["date1"].ToString();
    Label4.Text += dr["Event"].ToString();
}

con.Close();

答案 2 :(得分:0)

Public class Employee
{
    public int EmployeeId{get;set;}
    public string Name{get;set;}
} 


//ADO.NET CODES

    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;


    string cs = ConfigurationManager.ConnectionString["DBCS"].ConnectionStrings;
    using(SqlConnection con = ne SqlConnection(cs))
    {
       List<Employee> employee = new List<Employee>();
       SqlCommand cmd = new SqlCommand("select * from Employee",con);
       cmd.commandType = CommandType.Text;
       con.Open();
       SqlReader rdr = cmd.ExecuteReader();
       while(rdr.Read())
       {
          Employee emp = new Employee();
          emp.EmployeeId = Convert.ToInt32(rdr["EmployeeId"]);
          emp.Name = rdr["Name"].ToString();

          employee.Add(emp);
       }
    }

答案 3 :(得分:0)

在MVC5上,您可以使用:

List<EntityName> varName = db.EntityName.ToList(); //This selects all rows from the table

然后您可以迭代列表以显示信息字符串/标签