1. 程式人生 > >Gridview控制元件使用詳解

Gridview控制元件使用詳解

//一載入就填充Gridview控制元件
    public void Bin()
    {
        string strsql = "select id,title,context,datet From db_guanggao";
        com = new SqlCommand(strsql, con);
        com.CommandType = CommandType.Text;
        da = new SqlDataAdapter();
        da.SelectCommand = com;
        ds = new DataSet();
        try
        {
            da.Fill(ds, "table");
            GridView1.DataSource = ds;
            GridView1.AllowPaging = true;//啟動分頁
            GridView1.DataBind();
            string info = "頁次:<font color=red>";
            info += (this.GridView1.PageIndex + 1) + "</font>/" + this.GridView1.PageCount + "頁";
            this.Label1.Text = info;//當前頁/總頁如:1/5的形式顯示
            //記算dataset的初始值
            //計算資料集的下標,資料集的下標也是從0開始的,PageIndex * 2是每頁顯示2條資料,PageIndex下標也是從0開始的
            int yeshu = this.GridView1.PageIndex * 2;//2是每頁要顯示的數量是可以隨便改的
            //記算最後一個值
            int jie = 0;
            if ((ds.Tables[0].Rows.Count - yeshu) > 2)
            {
                jie = yeshu + 2;
            }
            else
            {
                jie = ds.Tables[0].Rows.Count;//讀出資料的總行數
            }
            for (int wu = yeshu; wu < jie; wu++)
            {
                int i = 0;
                if (wu >= 2)
                {
                    int tempNew = wu % 2;
                    i = tempNew;
                }
                else
                {
                    i = wu;
                }
            }
            this.DropDownList1.Items.Clear();
            for (int j = 0; j < this.GridView1.PageCount; j++)
            {
                this.DropDownList1.Items.Add(Convert.ToString(j + 1));
            }
        }
        catch (SqlException ex)
        {
            myLabel.Text = "資料庫出錯了";
        }
        finally
        {
            ds.Clone();
            com.Clone();
            con.Close();
        }
//下面是把GvridView控制元件的分頁事件,刪除事件已經更新事件

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.GridView1.PageIndex = e.NewPageIndex;
        this.Bin();
    }

    protected void Button1_Click(object sender, EventArgs e)//跳到某一頁的button事件
    {
        if (DropDownList1.Items.Count != 0)
        {
            string class1 = this.DropDownList1.SelectedValue.ToString();
            GridView1.PageIndex = Convert.ToInt32(class1)-1;
            this.Bin();
        }
    }
//刪除事件
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string del = "delete from db_fclass where classname='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
        com = new SqlCommand(del,con);
        try
        {
            con.Open();
            if (com.ExecuteNonQuery() > 0)
            {
                myLabel.Text = "刪除成功!";
                Bin();
            }
            else
            {
                myLabel.Text = "刪除失敗!";
            }
        }
        catch (SqlException ex)
        {
            myLabel.Text = "資料庫失敗!" + ex.Message;
        }
        finally
        {
            com.Clone();
            con.Close();
        }
    }
//更新事件
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string up_str = Convert.ToString(GridView1.DataKeys[e.RowIndex].Value.ToString().Trim());
        string classm = Convert.ToString(GridView1.Rows[e.RowIndex].Cells[0].Text.ToString().Trim());
        if (up_str.Equals(classm))
        {
            myLabel.Text = "沒有更改名字";
        }else{
            string up_class = "update db_fclass set classname='"
                              + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0])).Text.ToString().Trim() + "' where classname='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
            com = new SqlCommand(up_class, con);
            try
            {
                con.Open();
                if (com.ExecuteNonQuery() > 0)
                {
                    GridView1.EditIndex = -1;
                    myLabel.Text = "更新成功!";
                    Bin();
                }
                else
                {
                    myLabel.Text = "更新失敗!";
                }
            }
            catch (SqlException ex)
            {
                myLabel.Text = "資料庫錯誤" + ex.Message;
            }
            finally
            {
                com.Clone();
                con.Close();
            }
        }
    }
//和更新事件一起用的事件,這是必須的
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        this.Bin();
    }
//和更新事件一起用的事件,這是必須的
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        this.Bin();
    }
    }
//用選擇按鈕激發事件做更新資料
 protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        con.Open();
        SqlTransaction stran = con.BeginTransaction();//用到事物
        string up_str = "update db_Theme set CurrenShow=0";
        com = new SqlCommand(up_str, con,stran);
        try
        {
            if (com.ExecuteNonQuery() > 0)
            {
                com.CommandText = "update db_Theme set CurrenShow=1 where id="
                      + GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
                if (com.ExecuteNonQuery() > 0)
                {
                    Page.RegisterStartupScript("key", "<script>alert('指定成功!');</script>");
                }
                else
                {
                    Page.RegisterStartupScript("key", "<script>alert('指定失敗!');</script>");
                }
            }
            stran.Commit();//提交事務
        }
        catch (SqlException ex)
        {
            stran.Rollback();//回滾事務
            Response.Write("資料庫錯誤!" + ex.Message);
        }
        finally
        {
            com.Clone();
            con.Close();
        }
    }
 /// <summary>
    /// 用GRIDVIEW中的選擇按鈕進行參看使用者上傳的檔案然後更新
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        string f_name=GridView1.Rows[e.NewSelectedIndex].Cells[2].Text.ToString();//得到要檢視的檔名
        Response.Redirect("../second/file_sc/"+f_name,false);//跳轉檢視此檔案
        //GridView1.DataKeys[e.NewSelectedIndex].Value.ToString()是得到ID值進行更新
        //檢視後更新
        string up_sql = "update ja_file_sc set f_zt=1 where id="+GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
        if (objsql.RunSql(up_sql))
        {
            sel_c();//更新後重新整理GRIDVIEW
        }
    }
//CheckBox多選框在Gridview中的使用,這裡是被選中的刪除
protected void LinkButton1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            //下面是用FindControl("CheckBox1");得到制定控制元件的ID值,
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
            if (cbox.Checked == true)
            {
        string id=GridView1.DataKeys[i].Value.ToString();
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["dns"].ConnectionString);
        string delete_str = "delete grbg_dzyj_postmail from where

[email protected]";
        com = new SqlCommand(delete_str, con);
        com.Parameters.Add("@id", SqlDbType.Int);
        com.Parameters["@id"].Value = id;
         con.open();
          com.com.ExecuteNonQuery();
         con.clone();
            }
        }
        Bin();//重新繫結Grideview保持資料更新
    }
//在grideview頭模板中新增一個CheckBox當選中的時候下面表中的CheckBox全選
 protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {

        CheckBox cbox_1 = (CheckBox)GridView1.HeaderRow.FindControl("CheckBox1");//("CheckBox1");//得到grideview頭中的CheckBox控制元件
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox3");
            if (cbox_1.Checked == true)
            {
                cbox.Checked = true;
            }
            else
            {
                cbox.Checked = false;
            }
        }
    }
 

相關推薦

Android入門——基本控制元件

Android應用開發的一項重要內容就是介面開發。對於使用者來說,不管APP包含的邏輯多麼複雜,功能多麼強大,如果沒有提供友好的圖形互動介面,將很難吸引終端使用者。作為一個程式設計師如何才能開發出友好的圖形介面呢。實際上Android提供了非常豐富UI(User Interface)控制元

《Android群英傳》學習筆記之Android控制元件架構與自定義控制元件

一、Android控制元件架構: 控制元件大致分為兩類:ViewGroup控制元件與View控制元件。View是繪製在螢幕上的使用者能與之互動的一個物件。而ViewGroup則是一個用於存放其他Vi

Android SeekBar控制元件

SeekBar控制元件詳解 使用 SeekBar 實現圖片的虛幻 註解:圖片虛幻度最大值為255,為實體最小值為0,虛幻值越小,圖片越虛幻。 使用 SeekBar 實現圖

IOS-TextField控制元件

//初始化textfield並設定位置及大小   UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, 30)]; //設定邊框樣式,只有設定了才會顯示邊框樣式     text.borderSty

ASP.Net MVC中使用Chart 控制元件

在 .NET 3.5 的時候,微軟就提供了一個 Chart 控制元件,網路上有大量的關於在 VS2008 中使用這個控制元件的文章,在 VS2010 中,這個控制元件已經被整合到 ASP.NET 4.0 中,可以從工具箱中直接使用了。 這個控制元件在 ASP.NET 經典的頁面中很容易使用,但是在

PyQt5基本控制元件之QPixmap(十九)

QPixmap 前言 QPixmap類用於繪圖裝置的影象顯示,它可以作為一個QPainterDevice物件,也可以載入到一個控制元件中,通常是標籤或者按鈕,用於在標籤或按鈕上顯示影象

DataGrid/DataList控制元件

5、Items俗話說,最後的都是最重要的,把Items作為最後一個屬性來介紹,正式基於這樣的理由。Items是DataGridItem的集合,可以遍歷當前DataGrid中顯示資料的DataGridItem。5.1、DataGridItem每一個DataGridItem就是DataGrid中顯示的一行,其中包

html拖動控制元件

HTML5提供專門的拖拽與拖放的API,以後實現這類效果就不必亂折騰了。但是,考慮到Opera瀏覽器似乎對此不感冒,在通用性上有待商榷,所以這裡也就簡單說一說。 二、相關重點 DataTransfer 物件:退拽物件用來傳遞的媒介,使用一般為Event.dataTran

WatchOS開發教程之三: 導航方式和控制元件

導航方式 Watch App中導航樣式分為兩種:分頁樣式(Page based) 和分層樣式(Hierarchical), 這兩種樣式是互斥的,所以不能混合使用只能選擇其一。Hierarchical方式可以通過pushController或者prese

Delphi 中WebBrowser控制元件例項

uses mshtml,IdHTTP;procedure TFrmmain.Act_BeginWrite;varmyitem:Olevariant;i:integer;tmp:string;TemName:String;TemIniFile:TIniFile;beginTrymyitem := WebBrow

PyQt5基本控制元件之QDialog(十二)

QDialog 前言 為了更好的實現人機互動,比如window和linux等系統均會提供一系列的標準對話方塊來完成特定場景下的功能,比如選擇字號大小。字型顏色等,在PyQt5中定義了一系列的標準對話方塊類,讓使用者能夠方便快捷地通過各個類完成字號大

React Native之ScrollView控制元件

概述 ScrollView在Android和ios原生開發中都比較常見,是一個 滾動檢視控制元件。在RN開發中,系統也給我們提供了這麼一個控制元件。不過在RN開發中 ,使用ScrollView必須有一個確定的高度才能正常工作,因為它實際上所做的就是將一系列不確

AppWidget(桌面小控制元件

介紹 Android widget 也稱為桌面外掛,其是android系統應用開發層面的一部分,但是又有特殊用途,而且會成為整個android系統的亮點。Android中的AppWidget與google widget和中移動的widget並

android Spinner控制元件

Spinner提供了從一個數據集合中快速選擇一項值的辦法。預設情況下Spinner顯示的是當前選擇的值,點選Spinner會彈出一個包含所有可選值的dropdown選單,從該選單中可以為Spinner選擇一個新值。 上圖顯示的是Spinner常見的樣式。

IOS WebView控制元件

概述 WebView就是一個內嵌瀏覽器控制元件,在iOS中主要有兩種WebView:UIWebView和WKWebView,UIWebView是iOS2之後開始使用,WKWebView是在iOS8開始使用,WKWebView將逐步取代笨重的UIWebView。

DotNetBar第三方控制元件

為office2010、windows7、Office 2007 Ribbon 控制元件提供了Black,Silver ,Blue三種配色方案,支援Windows Vista Glass、tab groups, ribbon hyper menus, multi-level KeyTips, complete

閱讀徐宜生《Android群英傳》的筆記——第3章 Android控制元件架構與自定義控制元件(3.6-3.8)

3.6 自定義 View 在自定義 View 時,我們通常會去重寫 onDraw() 方法來繪製 View 的顯示內容。如果該 View 還需要使用 wrap_content 屬性,那麼還必須重寫 onMeasure() 方法。另外,通過自定義 attr

Objective-C 獲取控制元件

1> 通過 IBOutlet 連線來獲取控制元件 2> Tag 屬性獲取控制元件 <1> 在屬性面板中,設定元件 Tag 的值,設定唯一的Tag 值 <2>

PyQt5基本控制元件之QCheckBox(八)

QCheckBox QCheckBox類中常用方法如表 方法 描述 setChecked() 設定複選框的狀態,設定為True表示選中,False表示取消選中的複選框 setText() 設定複選框的顯示文字

PyQt5基本控制元件之QLineEdit(四)

QLineEdit QLineEdit類中常用的方法如下表 方法 描述 setAlignment() 按固定值方式對齊文字 Qt.AlignLeft:水平方向靠左對齊 Qt.AlignRight:水平方