webservice1.asmx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
namespace test16_3
{
/// <summary>
/// WebService1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public System.Data.DataSet GetQuery()
{
string connectionString = @"Data Source=LAPTOP-AQKEN65V\SQLEXPRESS08;Initial Catalog=db_news;User ID=sa;Password=123456;";
SqlConnection myCon = new SqlConnection(connectionString);
myCon.Open();
SqlCommand myCmd = new SqlCommand("select * from tb_news", myCon);
SqlDataAdapter adapter = new SqlDataAdapter(myCmd);
System.Data.DataSet myDs = new System.Data.DataSet();
adapter.Fill(myDs);
myCon.Close();
return myDs;
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
webform1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="test16_3.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>获取数据库信息</h3>
<asp:Button ID="Button1" runat="server" Text="获取" OnClick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
webform1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace test16_3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
localhost.WebService1 service1 = new localhost.WebService1();
System.Data.DataSet ds = service1.GetQuery();
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
注意,在添加服务引用时,引用名是默认的localhost,如果你的名称不一样,请在代码中替换。