问题
i want to retrieve the data stored in the table of the database into gridview control and my ado code is
public void retrieve_client()
{
SqlConnection con = new SqlConnection(DBconnection.connectstr);
con.Open();
SqlCommand com = new SqlCommand("retrieve_client", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@name", SqlDbType.VarChar).Value = this.name;
SqlDataReader r = com.ExecuteReader();
if(r.HasRows)
{
if(r.Read())
{
this.name = r[0].ToString();
this.address = r[1].ToString();
this.phone = r[1].ToString();
}
}
r.Close();
con.Close();
}
and my web form source is i want to enter the name in text box and retrieve the data and displaying them into grid view control please answer me:
my web form source is:
<table>
<tr>
<td>
<label class="labelclient">Name</label>
</td>
<td class="clientpadding">
<asp:TextBox ID="Textbox_retrieveclientbyname_first" runat="server" placeholder=" First Name" cssclass="textboxstyle" required="required"></asp:TextBox>
<asp:TextBox ID="Textbox_retrieveclientbyname_second" runat="server" placeholder=" Second Name" CssClass="textboxstyle" required="required"></asp:TextBox>
<asp:TextBox ID="Textbox_retrieveclientbyname_third" runat="server" placeholder=" Third Name" CssClass="textboxstyle" required="required"></asp:TextBox>
</td>
</tr>
</table>
<br />
<br />
<table>
<tr>
<td class="buttontd">
<asp:Button ID="btn_find_clientbyname" runat="server" Text="Find" CssClass="addclientbutton" OnClick="btn_find_clientbyname_Click"/>
</td>
<td>
<asp:Label ID="lbl_ermsg" runat="server" ></asp:Label>
</td>
</tr>
</table>
<div>
<asp:GridView ID="GridView_clientbyname" runat="server" >
<HeaderStyle CssClass="gridheader"/>
<RowStyle CssClass="gridrow" />
<AlternatingRowStyle cssclass="gridaltrow" />
</asp:GridView>
</div>
`
回答1:
Use
DataAdapterto FillDataTableAnd bind theGridViewWith ThatDataTable
public void retrieve_client()
{
SqlConnection con = new SqlConnection(DBconnection.connectstr);
con.Open();
SqlCommand com = new SqlCommand("retrieve_client", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@name", SqlDbType.VarChar).Value = this.name;
SqlDataAdapter da = New SqlDataAdapter(com);
DataTable dt=New DatTable();
da.Fill(dt);
con.Close();
GridView_clientbyname.DataSource=dt;
GridView_clientbyname.DataBind();
}
来源:https://stackoverflow.com/questions/29325577/i-want-to-display-data-that-is-in-database-into-grid-view-control