asp.net webforms

时间:2016-04-23 21:51:13

标签: c# php sql asp.net webforms

您好我正在尝试从数据库中读取数据然后将其放入表中。表中的行是根据数据库中的行数自动创建的。我使用mysql_fetch_array在php中完成了这个,但似乎无法在asp.net webforms中执行此操作。我的想法是使用此查询获取信息并存储在服务器页面中的标签中,并使用标签填充coloumns数据创建一个表。这是我在&page;页面中的代码'谢谢你:

<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 = new SqlCommand(&#34;选择手术,PatientID,详细位置&#34;,conn);                 SqlDataAdapter sda = new SqlDataAdapter(cmd);                 DataTable dt = new DataTable();                 sda.Fill(DT);                 GridView1.DataSource = dt;                 GridView1.DataBind();                 conn.Close();

1 个答案:

答案 0 :(得分:1)

GridView代码中添加aspx

<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();