ASP.NET資料繫結之GridView控制項_實用技巧

來源:互聯網
上載者:User

GridView 是 DataGrid的後繼控制項,在.net framework 2 中,雖然還存在DataGrid,但是GridView已經走上了曆史的前台,取代DataGrid的趨勢已是勢不擋。
 作用:其功能是在web頁面中顯示資料來源中的資料。GridView和DataGrid功能相似,都是在web頁面中顯示資料來源中的資料,將資料來源中的一行資料,也就是一條記錄,顯示為在web頁面上輸出表格中的一行。
    在此GirdView的詳細屬性和事件我不再闡述。下面我只是簡單介紹一下GirdView如何顯示從後台資料庫搜尋出來的資料,也就是GirdView怎樣綁定並顯示資料來源。
一、前台介面如下

二、後台編寫:用VS建立ASP.NET表單應用程式。在此,我只編寫查詢功能,後台代碼如下
1、建立資料庫連接

public static SqlConnection createConnection()  {    SqlConnection con = new SqlConnection("server=.;database=dropDownTest;uid=sa;pwd=123456");    con.Open();    return con;  } 

2、編寫操作類、其中有普通查詢方法、按條件查詢方法、添加方法(略)

public static DataTable SelectAll() {   SqlConnection con = createConnection();   DataTable dt = new DataTable();   SqlCommand cmd = new SqlCommand("select * from person", con);   SqlDataReader sdr = cmd.ExecuteReader();   dt.Load(sdr);   return dt; } 

3、編寫查詢按鈕單擊事件

protected void Button4_Click(object sender, EventArgs e) {   string c = "";  //定義Null 字元串,用來條件查詢       //設定複選框1的查詢條件   if (this.CheckBox1.Checked)   {     c = "pID=" + this.txtID.Text;  //精確匹配查詢條件   }   else   {     c = "pID like'%' ";    //模糊比對查詢條件   }   if (this.CheckBox2.Checked)   {     c += " and personName like '%" + this.txtName.Text + "%'";   }   if (this.CheckBox3.Checked)   {     if (RadioButton1.Checked)     {       c += "and personSex='男'";     }      else     {       c += "and personSex='女'";     }   }    DataView dv = new DataView(PerosonOperate.SelectAll()); //調用查詢方法   dv.RowFilter = c;                    //設定過濾器(按條件尋找)   dv.Sort = "pID Desc";                  //使結果按照pID欄位降序排列   GridView1.DataSource = dv;               //設定資料來源   GridView1.DataBind();                  //綁定資料來源   //設定列名,如果不設定,將會以資料庫中對應的欄位名稱代替   GridView1.HeaderRow.Cells[0].Text = "編號";   GridView1.HeaderRow.Cells[1].Text = "姓名";   GridView1.HeaderRow.Cells[2].Text = "性別";  

     三張查詢效果圖如下所示,分別為直接點擊查詢、按照性別查詢、按照編號和姓名和性別一塊查詢。

    上面編寫的後台代碼只是在功能可以實現的基礎上編寫的,裡面未免有一些Bug,希望大家自己改造。
    從後台綁定資料的篩選再到前台的呈現,用GridView將資料在瀏覽器上顯示出來的大致流程就是這樣,這裡面唯一有點彆扭的是按條件查詢中,字串的拼字不好弄,這樣做無非是使用GirdView的過濾效果,也就是這段代碼dv.RowFilter = c;希望大家在代碼編寫上細心點。

以上就是通過執行個體為大家介紹ASP.NET資料繫結中的GridView控制項的使用方法,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.