如何从SQL检索数据并将其显示到Aspx Web窗体
本文关键字:显示 Aspx 窗体 Web SQL 检索 数据 | 更新日期: 2023-09-27 18:27:38
我是.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" />
如何从数据库中检索数据并将内容显示在上面的文本框中。我使用多行,因为数据不止一个。
看看这个msdn教程:使用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();
}