2
votes

Hi I am trying to read data from database then put this into a table. rows in the table are created automatically depending on how many rows there are in database. I have done this in php using mysql_fetch_array but cannot seem to do it in asp.net webforms. My idea is to use this query to get the information and store in the labels in the server page and create a table there with coloumns data filled using the labels. Here is my code in the 'page_load' Thank you:

<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("select surgery, PatientID, location from details", conn); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); conn.Close();

1
Already tried that does not seem to work??Adam Patel
The requirements can be fulfilled by GridView easily, did you try that? If yes then please share that code.Shaharyar
I am missing a directive or assembly reference for 'dataset' ???Adam Patel
Add reference for System.Data in your project.Shaharyar

1 Answers

1
votes

Add GridView in your aspx code:

<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>

You C# code is fine, just close the connection before binding to 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();