【问题标题】:How to retrieve and display data from SQL to Aspx webform如何从 SQL 检索和显示数据到 Aspx webform
【发布时间】:2012-03-14 05:23:14
【问题描述】:

我是 in.net 的新手,我尝试创建一个简单的网站。

我有这个文本框是多行的并且有固定的宽度和高度。

<asp:TextBox ID="TextBox1" runat="server" Height="168px" TextMode="MultiLine" 
                            Width="303px"></asp:TextBox>

我还创建了一个 web.config 来连接我的 sql 数据库:

<connectionStrings>
<add name="TDBSConnectionString" connectionString="Data Source=local;Initial Catalog=IBSI;Persist Security Info=True;User ID=sa;Password=1"
  providerName="System.Data.SqlClient" />

如何从我的数据库中检索数据并将内容显示到上面的文本框中。 我使用多行,因为数据不止一个。

【问题讨论】:

标签: c# asp.net sql


【解决方案1】:

看看这个 msdn 教程:Retrieving Data Using the DataReader

示例:

        SqlDataReader rdr = null;
        SqlConnection con = null;
        SqlCommand cmd = null;

        try
        {
            // Open connection to the database
            string ConnectionString = "server=xeon;uid=sa;"+
                "pwd=manager; database=northwind";
            con = new SqlConnection(ConnectionString);
            con.Open();

            // Set up a command with the given query and associate
            // this with the current connection.
            string CommandText = "SELECT FirstName, LastName" +
                                 "  FROM Employees" +
                                 " WHERE (LastName LIKE @Find)";
            cmd = new SqlCommand(CommandText);
            cmd.Connection = con;

            // Add LastName to the above defined paramter @Find
            cmd.Parameters.Add(
                new SqlParameter(
                "@Find", // The name of the parameter to map
                System.Data.SqlDbType.NVarChar, // SqlDbType values
                20, // The width of the parameter
                "LastName"));  // The name of the source column

            // Fill the parameter with the value retrieved
            // from the text field
            cmd.Parameters["@Find"].Value = txtFind.Text;

            // Execute the query
            rdr = cmd.ExecuteReader();

            // Fill the list box with the values retrieved
            lbFound.Items.Clear();
            while(rdr.Read())
            {
                lbFound.Items.Add(rdr["FirstName"].ToString() +
                " " + rdr["LastName"].ToString());
            }
        }
        catch(Exception ex)
        {
            // Print error message
            MessageBox.Show(ex.Message);
        }
        finally
        {
            // Close data reader object and database connection
            if (rdr != null)
                rdr.Close();

            if (con.State == ConnectionState.Open)
                con.Close();
        }

【讨论】:

  • 我要为这个创建另一个.aspx 或.cs 文件吗?还是在同一个文件上?我的 home.aspx 只有 html 代码。
  • @Bert - 您可以编写内联代码或使用代码隐藏文件,即 home.aspx.cs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
相关资源
最近更新 更多