2016-04-23 35 views
2

嗨我想从数据库中读取数据,然后把它放到一个表中。根据数据库中有多少行自动创建表中的行。我在php中使用mysql_fetch_array完成了这项工作,但似乎无法在asp.net webforms中完成。我的想法是使用此查询来获取信息并存储在服务器页面的标签中,并使用标签填充颜色数据创建一个表格。这里是我的代码在 'Page_Load中' 谢谢你,在asp.net中的mysql_fetch_array webforms

<table> 
     <tr> 
      <th>Surgery</th> 
      <th>PatientID</th> 
      <th>Location</th> 
     </tr> 
     <tr> 
      <td> 

     <asp:Label ID="Label1" runat="server"></asp:Label> 
     </td> 
     <td> 
     <asp:Label ID="Label2" runat="server"></asp:Label> 
     </td> 
     <td> 

     <asp:Label ID="Label3" runat="server"></asp:Label> 
     </td> 
     </tr> 
     </table> 



      string query= "select surgery,patientID, location from details"; 
      SqlCommand result= new SqlCommand(query, conn); 
      result.ExecuteNonQuery(); 
      using (SqlDataReader getInfo= result.ExecuteReader()) 


       while (getInfo.Read()) 
       { 
        Label1.Text = getInfo["surgery"].ToString(); 
        Label2.Text = getInfo["patientID"].ToString(); 
        Label3.Text = getInfo["location"].ToString(); 


       } 

的SqlCommand CMD =新的SqlCommand( “选择手术,PatientID,从细节位置”,conn);在 SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); conn.Close();

+0

使用'GridView'。可能的重复[ASP.NET本地SQL Server数据库C#gridview数据绑定Visual Studio 2013](http://stackoverflow.com/questions/26817272/asp-net-local-sql-server-database-c-sharp-gridview- data-binding-visual-studio-20) – Shaharyar

+0

已经尝试过,似乎没有工作? –

+0

这些要求可以通过GridView轻松实现,您是否尝试过?如果是,请分享该代码。 – Shaharyar

回答

1

aspx代码添加GridView

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"> 
    <Columns> 
     <asp:BoundField HeaderText="Surgery" DataField="surgery" /> 
     <asp:BoundField HeaderText="PatientID" DataField="patientID" /> 
     <asp:BoundField HeaderText="Location" DataField="location" /> 
    </Columns> 
</asp:GridView> 

你的C#代码是好的,只是关闭绑定到GridView控件之前的连接:

SqlCommand cmd = new SqlCommand("select surgery, PatientID, location from details", conn); 
SqlDataAdapter sda = new SqlDataAdapter(cmd); 
DataTable dt = new DataTable(); 
sda.Fill(dt); 

conn.Close(); 

GridView1.DataSource = dt; 
GridView1.DataBind(); 
+0

谢谢:)感谢帮助。风格它将与普通表相同?我对么? –

+0

是啊,只需写一个CSS类并设置其属性'cssClass =“youCSSclass”' – Shaharyar

+0

谢谢。最后一个问题说,我想在每一行旁边添加一个删除按钮。我将如何通过服务器传递'id'?我已经在php中完成了这个工作,并且会使用相同的方法。添加额外的colunm并将aspx中的DataField更改为'button_click',并将代码放入C#中的函数中?如果我想在aspx页面中使用该变量,是否使用%button_click%?谢谢 –