2012-03-14 68 views
2

我是一个新手在.net和即时尝试创建一个简单的网站。如何检索和显示数据从SQL到Aspx webform

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

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

我怎样才能从我的数据库中检索数据并显示上述内容到文本框中。 我使用多行,因为数据不止一个。

+5

你尝试过什么...... HTTP://mattgemmell.com/2008/12/08/what-有你试过/ – 2012-03-14 05:26:25

回答

3

必须看看这个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(); 
     } 
+0

我是否为这个创建another.aspx或.cs文件?或在同一个文件?我的home.aspx只有html代码。 – Bert 2012-03-14 05:30:54

+0

@Bert - 你可以编写codeinline或者使用代码隐藏文件,它是home.aspx.cs – 2012-03-14 05:32:28

+0

oh thx ill试试 – Bert 2012-03-14 05:33:21

相关问题