C# 透過類別寫連線方法

摘要:C# 透過類別寫連線方法

參考了http://jheng1212.pixnet.net/blog/post/22777501

的方法去做不過,由於小弟還不是對C#很熟

還是有小地方用不出來

最後自己用自己的方式改出來 與大家分享一下

首先在App_Code裡加入一個類別稱是callclassconn

 檔案名稱也是用callclassconn .cs

 

 

01 using System;
02 using System.Data;
03 using System.Data.SqlClient;
04 using System.Configuration;
05 using System.Web;
06 using System.Web.Security;
07 using System.Web.UI;
08 using System.Web.UI.WebControls;
09 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;

11
12 ///// <summary>
13 ///// Class1 的摘要描述
14 ///// </summary>
15
16 public class callclassconn  
17 {
18
19
20     const string constring = "server=127.0.0.1; database=Scan; uid=sa; pwd=123456; Initial Catalog=Scan"; //註1
21     public static SqlConnection conn;     //Connection物件
22     public static SqlCommand cmd;        //Command物件
23     public static SqlDataAdapter myadpt;  //DataAdapter物件
24     public static DataSet ds;                 //DataSet物件
25     public static DataView dv;              //DataView物件
26
27     public string select(string text, string table_name)
28
29       {
30         
31         conn = new SqlConnection(constring);  //註1
32         conn.Open();
33
34         cmd = new SqlCommand(text, conn);
35
36         myadpt = new SqlDataAdapter(cmd);
37
38         ds = new DataSet();
39
40         myadpt.Fill(ds, table_name);
41
42         dv = new DataView(ds.Tables[0]);
43         return text;
44         }

45
46 }

 

 

 

 

在前台部份

只要拉一個girdview 和一個按鈕

之後 Button1_Click內編輯

即可完成

 


01 using System;
02 using System.Data;
03 using System.Configuration;
04 using System.Collections;
05 using System.Web;
06 using System.Web.Security;
07 using System.Web.UI;
08 using System.Web.UI.WebControls;
09 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;

11
12 public partial class call_class : System.Web.UI.Page
13 {
14     protected void Page_Load(object sender, EventArgs e)
15     {
16
17     }

18     protected void Button1_Click(object sender, EventArgs e)
19     {
20
21        callclassconn myCSharpObject = new callclassconn();     //建立新物件
22        myCSharpObject.select("select * from news", "talename");   //呼叫物件
23        GridView1.DataSource = callclassconn.ds;                    //設定資料來源
24        GridView1.DataBind();                                                 //將資料繫結進去
25
26     }

27 }

 

 

 

 

 

 

 

大家一起加入blogads 賺零用錢!!