执行结果:
C# ->新建空网站->添加新项WEB窗体
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
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.bind();
}
}
public SqlConnection GetConnection()
{
string Str = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection Conn = new SqlConnection(Str);
return Conn;
}
protected void bind()
{
SqlConnection myConn = GetConnection();
myConn.Open();
string sqlStr = "select * from t001";
SqlDataAdapter myDa = new SqlDataAdapter(sqlStr, myConn);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
GridView1.DataSource = myDs;
GridView1.DataBind();
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}
protected void btnSelect_Click(object sender, EventArgs e)
{
if (this.txtName.Text != "")
{
SqlConnection myConn = GetConnection();
myConn.Open();
string sqlStr = "select * from t001 where bukrs=@Name";
SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
myCmd.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = this.txtName.Text.Trim();
SqlDataAdapter myDa = new SqlDataAdapter(myCmd);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
if (myDs.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = myDs;
GridView1.DataBind();
}
else
{
Response.Write("<script>alert('没有相关记录')</script>");
}
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}
else
this.bind();
}
}
配置文件代码:
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\DataBase\sap.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"/>
</appSettings>
<connectionStrings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
</configuration>