在视图中显示数据库数据

时间:2019-03-16 06:53:35

标签: asp.net sql-server

我需要从数据库中获取数据并显示在aspx页面中。

下面是我的代码,但是不起作用。他们怎么了?我试图解决这个问题,将互联网上的所有内容都引用了。我熟悉PHP,但不熟悉ASP.net。因此,由于我是新手,因此很难找出正确的解决方案。

Mydefault.aspx

<%@ Page Language="C#" AutoEventWireup="true" Debug="true" CodeFile="Mydefault.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body bgcolor="#ccccff">
    <form id="form1" runat="server">
    <h4 style="color: #800080"> Test Page</h4>
     <div>
        <table class="style1">
            <tr>
                <td class="style3" style="color: #800000; font-size: large;">
                Search</td>
                <td class="style2">
                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                 </td>
                <td>
                    <asp:Button ID="Button1" runat="server" Text="Go" onclick="Button1_Click" />
                </td>
            </tr>

        </table>
        <p> 
            <asp:Label ID="Label1" runat="server" Text="Label" ForeColor="Maroon"></asp:Label>
        </p>
    </div>
    <div>
     <asp:GridView ID="GridView1" runat="server"  BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" 
        CellPadding="3" CellSpacing="2" Height="90px" Width="260px">
        <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
        <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
        <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> 
      </asp:GridView>
    </div>
    </form>
</body>
</html>

Mydefault.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    public SqlConnection con;
    public string constr;

    public void connection()
    { 
        constr = ConfigurationManager.ConnectionStrings["locations"].ToString();
        con = new SqlConnection(constr);

        con.Open();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Visible = false;
    }

    private void rep_bind()
    {
        connection();

        string query = "select * from locations where Name like'" + TextBox1.Text + "%'";

        SqlDataAdapter da = new SqlDataAdapter(query, con);
        DataSet ds = new DataSet();
        da.Fill(ds);

        GridView1.DataSource = ds;
        GridView1.DataBind();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        connection();
        string query = "select Name  from locations where Name like'" + TextBox1.Text + "%'";
        SqlCommand com = new SqlCommand(query, con);

        SqlDataReader dr;
        dr = com.ExecuteReader();

        if (dr.HasRows)
        {
            dr.Read();

            rep_bind();
            GridView1.Visible = true;

            TextBox1.Text = "";
            Label1.Text = "";
        }
        else
        {
            GridView1.Visible = false;        
            Label1.Visible = true;
            Label1.Text = "The search Term " + TextBox1.Text + " &nbsp;Is Not Available in the Records"; ;
        }
    }
}

Web.config

<?xml version="1.0"?>
<configuration>
    <system.web>
         <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <connectionStrings>
        <add name="locations" 
             connectionString="server=localhost;database=mylocations;uid=myuser;password=Mypass;" 
             providerName="System.Data.SqlClient" />
    </connectionStrings>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

1 个答案:

答案 0 :(得分:0)

您执行两次相同的查询(rep_bind和button_click),并且永远不会关闭与数据库的连接。这将创建许多通往错误条件的路径。例如,当连接正忙于为DataReader提供服务时,您不能将其用于其他任务。我敢打赌,这就是您的程序出现第一个错误的地方。
您打开连接的时间不应超过获取数据所需的时间。

当然,正如注释中已经提到的那样,您应该使用参数查询数据库,并且永远不要将用户输入连接到sql命令。

首先要更改的是 connection 方法

public SqlConnection connection()
{ 
    string constr = ConfigurationManager.ConnectionStrings["locations"].ToString();
    SqlConnection con = new SqlConnection(constr);
    con.Open();
    return con;
}

现在,我们从此方法返回连接。为什么?因为我们可以在 using 语句中使用返回的对象,该语句将为我们的代码提供每次使用时关闭连接所需的功能。另外,我们不需要两个全局变量。
rep_bind 方法中,我们可以编写

private bool rep_bind()
{
    using(SqlConnection con = connection())
    {
        string query = "select * from locations where Name like @name";
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        da.SelectCommand.Parameters.Add("@name", SqlDbType.NVarChar).Value =  TextBox1.Text + "%";
        DataSet ds = new DataSet();
        da.Fill(ds);
        bool hasRows = ds.Tables[0].Rows.Count > 0;
        GridView1.DataSource = ds;
        GridView1.DataBind();
        return hasRows;
   }
}

现在在using块的末尾,连接将被关闭并销毁,并且一个变量告诉我们是否有行返回到调用代码。
button_click 事件处理程序会精心安排所有后端和UI界面

protected void Button1_Click(object sender, EventArgs e)
{
    if(rep_bind())
    {
        GridView1.Visible = true;
        TextBox1.Text = "";
        Label1.Text = "";
    }
    else
    {
        GridView1.Visible = false;        
        Label1.Visible = true;
        Label1.Text = "The search Term " + TextBox1.Text + " &nbsp;Is Not Available in the Records"; ;
    }
}