查询数据库中记录时,首先创建SqlConnection对象连接数据库,然后定义查询字符串,最后对GridView控件进行数据绑定。
示例:
查询数据库中记录
下面通过一个示例介绍在ASP.NET 2.0应用程序中如何查询数据库中记录。新建一个网站,默认主页为Default.aspx,在Default.aspx页面上分别添加一个TextBox控件、一个Button控件和一个GridView控件,并把Button控件的Text属性值设为“查询”。
该页在实现时,首先编写一个GridView控件数据绑定方法bind(该方法请参见5.3.2中bind方法),并在Page_Load事件中调用该方法显示数据库中记录,具体代码如下。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.bind();
}
}
然后在【查询】按钮Click事件下编写实现数据库查询操作的代码,具体代码如下。
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
string str = "select * from Region where RegionID='" + TextBox1.Text.Trim() + "'";
sqlconn = new SqlConnection(sqlstr);
sqlconn.Open();
SqlCommand sqlcom = new SqlCommand(str,sqlconn);
int result = Convert.ToInt32(sqlcom.ExecuteScalar());
if (result > 0)
{
SqlDataAdapter myda = new SqlDataAdapter(str, sqlconn);
DataSet myds = new DataSet();
myda.Fill(myds);
GridView1.DataSource = myds;
GridView1.DataBind();
sqlconn.Close();
}
else
Response.Write("");
}
else
this.bind();
}
执行程序,示例运行结果如图1所示。
图1查询数据库中记录
程序完整代码如下:
★★★★★Default.aspx.cs代码文件★★★★★
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string sqlstr = "Data Source=(local);Database=Northwind;Uid=sa;Pwd=";
SqlConnection sqlconn;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.bind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
string str = "select * from Region where RegionID='" + TextBox1.Text.Trim() + "'";
sqlconn = new SqlConnection(sqlstr);
sqlconn.Open();
SqlCommand sqlcom = new SqlCommand(str,sqlconn);
int result = Convert.ToInt32(sqlcom.ExecuteScalar());
if (result > 0)
{
SqlDataAdapter myda = new SqlDataAdapter(str, sqlconn);
DataSet myds = new DataSet();
myda.Fill(myds);
GridView1.DataSource = myds;
GridView1.DataBind();
sqlconn.Close();
}
else
Response.Write("");
}
else
this.bind();
}
public void bind()
{
string str = "select * from Region";
sqlconn = new SqlConnection(sqlstr);
sqlconn.Open();
SqlDataAdapter myda = new SqlDataAdapter(str, sqlconn);
DataSet myds = new DataSet();
myda.Fill(myds);
GridView1.DataSource = myds;
GridView1.DataBind();
sqlconn.Close();
}
}