我想将数据库中的数据显示到网格视图控件中

时间:2015-03-29 04:22:58

标签: c# asp.net gridview ado.net

我想将存储在数据库表中的数据检索到gridview控件中,我的ado代码是

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

我的网络表单源是我想在文本框中输入名称并检索数据并将其显示到网格视图控件中,请回答我:

我的网络表单来源是:

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

        &nbsp; &nbsp; 


            <asp:TextBox ID="Textbox_retrieveclientbyname_second" runat="server" placeholder=" Second Name" CssClass="textboxstyle" required="required"></asp:TextBox>

         &nbsp; &nbsp; 

    <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 个答案:

答案 0 :(得分:0)

  

使用DataAdapter填充DataTable并绑定GridView   那DataTable

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

    }