2012年4月16日 星期一

jquery ui for bootstrap 的使用

最近常常使用 Bootstrap 在做版面配置,頓時覺得 UI 美化是一件很輕鬆的事情,只是要我設計出這種羽量級且各大瀏覽器都通用的 css,那叫我去撞牆會比較快。

可是在我網頁缺少日歷的元件時,才發現他少了這麼個東西,應該是說要用甚麼卻發現沒有才知道沒有,所以我就去 google 了一下,找到一個 Bootstrap 相容的外掛,居然還是 jquery ui,那我就毫不客氣的去引用啦!

果然好用,以下就介紹使用他流程:

1.

首先先到 jquery for bootstrap 下載檔案:

2.

解壓縮出來,將必要的檔案取出來並分類建立路徑 ( 暫以解壓縮出來的檔案路徑為路徑 )

需要的檔案:
  • css/custom-theme/jquery-ui-1.8.16.custom.css
  • bootstrap/bootstrap.css
  • js/jquery-1.6.2.min.js
  • js/jquery-ui-1.8.16.custom.min.js

3.

最後我建立一個 sample 檔案,供大家隨意取用:
<html>
    <head>
        <link type="text/css" rel="stylesheet"
href="css/custom-theme/jquery-ui-1.8.16.custom.css"/>
        <link href="bootstrap/bootstrap.css" rel="stylesheet">
    </head>
    
    <body>
        <div id="datepicker"></div>
    </body>
    
    <script type="text/javascript" 
src="js/jquery-1.6.2.min.js"></script>
    <script type="text/javascript" 
src="js/jquery-ui-1.8.16.custom.min.js"></script>
    
    <script>
        $('#datepicker').datepicker();
    </script>
</html>

回html目錄
回首頁

2012年4月11日 星期三

SQL 自製類別

這個 SQL 類別為我個人設計並撰寫,可能設計的不夠完整,就請廣大的觀眾多多指教囉!

若要引用請註明來源,歡迎取用。







使用範例:
private SQL sql;

protected void Page_Load(object sender, EventArgs e)
{
    sql = new SQL("NorthwindConnectionString", 
        SQLConnectionType.SettingsName);

    Hashtable ht = new Hashtable();
    ht.Add("eID", "1");

    gv.DataSource = sql.ExecuteDataTable(
        "SELECT * FROM Employees WHERE EmployeeID=@eID ", ht);
    gv.DataBind();
    

}

類別程式碼如下:
public enum SQLConnectionType
{
    ConnectionString,
    SettingsName
};

/// <summary>
/// SQL 的摘要描述
/// </summary>
public class SQL
{
    private DataTable dt;

    private SqlConnection connection;
    private SqlCommand command;
    private SqlDataAdapter adapter;
    public SqlDataReader reader { get; set; }
    private SqlTransaction tran;
    public bool isError { get; set; }
    public string errorMessage { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public SQL()
    {

    }

    /// <summary>
    /// 初始化資料庫連線
    /// </summary>
    public SQL(string strConnection, SQLConnectionType type)
    {
        Connection(strConnection, type);
    }

    /// <summary>
    /// 資料庫連線
    /// </summary>
    /// <param name="strConnection">連接字串</param>
    /// <param name="type">資料庫連線方式</param>
    public void Connection(string strConnection, SQLConnectionType type)
    {
        connection = new SqlConnection();
        command = new SqlCommand();

        switch (type)
        {
            case SQLConnectionType.ConnectionString:
                
                connection.ConnectionString = strConnection;
                command.Connection = connection;
                
                break;

            case SQLConnectionType.SettingsName:

                connection.ConnectionString =
                    ConfigurationManager.ConnectionStrings[strConnection].
                    ConnectionString;
                command.Connection = connection;

                break;
        }
    }

    /// <summary>
    /// 執行資料庫語法
    /// </summary>
    /// <param name="query">指令</param>
    public void Execute(string query)
    {
        command.CommandText = query;
        connection.Open();

        isError = false;
        try
        {
            // 開始執行資料庫交易
            tran = connection.BeginTransaction();
            command.Transaction = tran;
            command.ExecuteNonQuery();
            tran.Commit();

        }
        catch (Exception ex)
        {
            // 失敗則 Rollback
            tran.Rollback();

            errorMessage = ex.Message;
            isError = true;
        }
        finally
        {
            connection.Close();
        }
    }

    /// <summary>
    /// 執行資料庫語法
    /// </summary>
    /// <param name="query">指令</param>
    /// <param name="ht">參數</param>
    public void Execute(string query, Hashtable ht)
    {
        SetParameters(ht);
        Execute(query);
    }

    /// <summary>
    /// 傳回結果第一行第一列之資料
    /// </summary>
    /// <param name="query">指令</param>
    /// <returns></returns>
    public object ExecuteScalar(string query)
    {
        object obj = string.Empty;

        command.CommandText = query;
        connection.Open();

        isError = false;
        try
        {
            obj = command.ExecuteScalar();
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
            isError = true;
        }
        finally
        {
            connection.Close();
        }

        return obj;
    }

    /// <summary>
    /// 傳回結果第一行第一列之資料
    /// </summary>
    /// <param name="query">指令</param>
    /// <param name="ht">參數</param>
    /// <returns></returns>
    public object ExecuteScalar(string query, Hashtable ht)
    {
        SetParameters(ht);

        return ExecuteScalar(query);
    }


    /// <summary>
    /// 傳回 DataTable
    /// </summary>
    /// <param name="query">指令</param>
    /// <returns></returns>
    public DataTable ExecuteDataTable(string query)
    {
        dt = new DataTable();
        command.CommandText = query;
        
        isError = false;
        try
        {
            adapter = new SqlDataAdapter(command);
            adapter.Fill(dt);
        }
        catch(Exception ex)
        {
            errorMessage = ex.Message;
            isError = true;
        }

        return dt;
    }

    /// <summary>
    /// 傳回 DataTable
    /// </summary>
    /// <param name="query">指令</param>
    /// <param name="ht">參數</param>
    /// <returns></returns>
    public DataTable ExecuteDataTable(string query, Hashtable ht)
    {
        SetParameters(ht);

        return ExecuteDataTable(query);
    }

    /// <summary>
    /// 傳回 SqlDataReader
    /// </summary>
    /// <param name="query">指令</param>
    public SqlDataReader ExecuteReader(string query)
    {
        command.CommandText = query;

        reader = command.ExecuteReader();

        return reader;
    }

    /// <summary>
    /// 傳回 SqlDataReader
    /// </summary>
    /// <param name="query">指令</param>
    /// <param name="ht">參數</param>
    /// <returns></returns>
    public SqlDataReader ExecuteReader(string query, Hashtable ht)
    {
        SetParameters(ht);
        return ExecuteReader(query);
    }

    /// <summary>
    /// 查詢資料是否存在
    /// </summary>
    /// <param name="query">指令</param>
    /// <returns></returns>
    public bool Exists(string query)
    {
        object obj;
        bool isExists = false;
        int iResult = 0;

        command.CommandText = query;
        connection.Open();

        isError = false;
        try
        {
            obj = command.ExecuteScalar();

            if (int.TryParse(Convert.ToString(obj), out iResult))
            {
                if (iResult > 0)
                    isExists = true;
            }
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
            isError = true;
        }
        finally
        {
            connection.Close();
        }

        return isExists;
    }

    /// <summary>
    /// 查詢資料是否存在
    /// </summary>
    /// <param name="query">指令</param>
    /// <param name="ht">參數</param>
    /// <returns></returns>
    public bool Exists(string query, Hashtable ht)
    {
        SetParameters(ht);
        return Exists(query);
    }

    /// <summary>
    /// 將資料庫連線開啟或關閉
    /// </summary>
    /// <param name="strStatus">狀態字串(open or close)</param>
    public void CallConnection(string strStatus)
    {
        switch (strStatus.ToLower())
        {
            case "open":
                if (connection.State == ConnectionState.Closed)
                    connection.Open();
                break;
            case "close":
                if (connection.State == ConnectionState.Open)
                    connection.Close();
                break;

        }
    }

    /// <summary>
    /// 設定參數
    /// </summary>
    /// <param name="ht">參數</param>
    private void SetParameters(Hashtable ht)
    {
        command.Parameters.Clear();
        foreach (DictionaryEntry de in ht)
            command.Parameters.AddWithValue(Convert.ToString(de.Key),
            Convert.ToString(de.Value));
    }
}

回C#目錄
回首頁

2012年4月10日 星期二

Bootstrap 於 Asp.net 的基本使用

Bootstrap 為一個 Open Source ( 開放程式碼 ) 的前台開發工具包,是一個簡單、靈活的 HTML、CSS、Javascript 的 UI 套件。
通常好的 UI 能讓瀏覽者多留 3 - 5 秒,當然,最重要的還是內容。但是可以因為這 3 - 5 秒讓瀏覽者注意到內容,那 UI 算是很重要的一塊。
Bootstrap 使得網頁開發者不需要再為 UI 介面設計所煩惱,它提供了整體化的設計和網頁控制項的美化,要單用或全用都很方便,引入 css 檔案或 js 檔案,在配合 css class 的使用,即可達到美化作用。

以下就介紹 Bootstrap 於 Asp.net 的使用流程:

1.

首先到 Bootstrap 下載檔案

2.

下載完解壓縮出來會有以下路徑資料夾

3.

在 css 下有兩個檔案,分別為 bootstrap.css 和 bootstrap.min.css

4.

將這兩個檔案複製下來,放入 Asp.net 專案內的 css 分類資料夾下

5.

接著在主板頁面 ( *.master ) 或者是網頁 ( *.aspx、*.html ) 中引用

6.

在頁面上可以先做個實驗,拉一個按鈕 ( Button ) 到頁面上

7.

回到 Bootstrap 的官方網頁,看看Bootstrap 按鈕如何使用

8.

最後我們可以套用 css,在 Asp.net 有 Intellisense ( 智能提示 ) 可以方便的套用,這個案例我們使用的類別是 btn btn-primary

9.

最後執行後就可以看到套用的是否成功,LOOK,是不是很舒服?


回aspnet目錄
回首頁

2012年4月9日 星期一

GridView 新增、刪除、修改以及排序

在 Asp.net 中 GridView 也可以做很多的事情,不只有顯示資料而已。

最近研究了在 GridView 中也能新增、刪除、修改以及排序,參考了兩篇文章

GridView 排序
GridView 新刪修

經過稍加修改後,使用微軟範例資料庫 NorthWind ( 北風 ) 做測試,終於完成,以下為 *.aspx 程式碼:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" 
    OnRowEditing="gv_RowEditing" OnRowCancelingEdit="gv_RowCancelingEdit"
    OnRowUpdating="gv_RowUpdating" BackColor="#DDDDDD" BorderStyle="None"
    BorderWidth="1px" CellPadding="5" CellSpacing="1" GridLines="None"
    Style="line-height: 22px; width: 100%;" onrowdeleting="gv_RowDeleting" 
    AllowPaging="True" onpageindexchanging="gv_PageIndexChanging" 
    PageSize="10" AllowSorting="True" onsorting="gv_Sorting">
    <RowStyle BackColor="#ffffff" ForeColor="Black" />
    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
    <PagerStyle BackColor="#ffffff" HorizontalAlign="left" />
    <HeaderStyle BackColor="#efefef" Font-Bold="True" />
    <AlternatingRowStyle BackColor="#f7fafe" />
    <EmptyDataTemplate>
        Sorry, No any data.
    </EmptyDataTemplate>
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:LinkButton ID="lbInsert" runat="server" Width="70px" 
                onclick="lbInsert_Click">新增</asp:LinkButton>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:LinkButton ID="lbEdit" runat="server" 
                CommandName="Edit">編輯</asp:LinkButton> 
                |
                <asp:LinkButton ID="lbDelete" runat="server" 
                OnClientClick="javascript:return confirm('確定刪除?')" 
                CommandName="Delete">刪除</asp:LinkButton>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="lbUpdate" runat="server" 
                CommandName="Update">更新</asp:LinkButton>
                |
                <asp:LinkButton ID="lbCancelUpdate" runat="server" 
                CommandName="Cancel">取消</asp:LinkButton>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:LinkButton ID="lbSave" runat="server" 
                onclick="lbSave_Click">儲存</asp:LinkButton>
                |
                <asp:LinkButton ID="lbCancelSave" runat="server" 
                onclick="lbCancelSave_Click">取消</asp:LinkButton>
            
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="客戶編號" SortExpression="CustomerID">
            <ItemTemplate>
                <asp:Label ID="lblCustomerID" runat="server" 
                Text='<%# Eval("CustomerID") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="lblCustomerIDEdit" runat="server" 
                Text='<%# Eval("CustomerID") %>'></asp:Label>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbCustomerIDFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="公司名稱" SortExpression="CompanyName">
            <ItemTemplate>
                <asp:Label ID="lblCompanyName" runat="server" 
                Text='<%# Eval("CompanyName") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbCompanyNameEdit" runat="server" 
                Text='<%# Eval("CompanyName") %>' ></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbCompanyNameFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="聯絡人姓名" SortExpression="ContactName">
            <ItemTemplate>
                <asp:Label ID="lblContactName" runat="server" 
                Text='<%# Eval("ContactName") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbContactNameEdit" runat="server" 
                Text='<%# Eval("ContactName") %>'></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbContactNameFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="聯絡人職稱" SortExpression="ContactTitle">
            <ItemTemplate>
                <asp:Label ID="lblContactTitle" runat="server" 
                Text='<%# Eval("ContactTitle") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbContactTitleEdit" runat="server" 
                Text='<%# Eval("ContactTitle") %>'></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbContactTitleFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="地址" SortExpression="Address">
            <ItemTemplate>
                <asp:Label ID="lblAddress" runat="server" 
                Text='<%# Eval("Address") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbAddressEdit" runat="server" 
                Text='<%# Eval("Address") %>'></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbAddressFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="城市" SortExpression="City">
            <ItemTemplate>
                <asp:Label ID="lblCity" runat="server" 
                Text='<%# Eval("City") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbCityEdit" runat="server" 
                Text='<%# Eval("City") %>'></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbCityFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="地區" SortExpression="Region">
            <ItemTemplate>
                <asp:Label ID="lblRegion" runat="server" 
                Text='<%# Eval("Region") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbRegionEdit" runat="server" 
                Text='<%# Eval("Region") %>'></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbRegionFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="郵遞區號" SortExpression="PostalCode">
            <ItemTemplate>
                <asp:Label ID="lblPostalCode" runat="server" 
                Text='<%# Eval("PostalCode") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbPostalCodeEdit" runat="server" 
                Text='<%# Eval("PostalCode") %>'></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbPostalCodeFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="國家" SortExpression="Country">
            <ItemTemplate>
                <asp:Label ID="lblCountry" runat="server" 
                Text='<%# Eval("Country") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbCountryEdit" runat="server" 
                Text='<%# Eval("Country") %>'></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbCountryFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="電話" SortExpression="Phone">
            <ItemTemplate>
                <asp:Label ID="lblPhone" runat="server" 
                Text='<%# Eval("Phone") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbPhoneEdit" runat="server" 
                Text='<%# Eval("Phone") %>'></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbPhoneFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="傳真" SortExpression="Fax">
            <ItemTemplate>
                <asp:Label ID="lblFax" runat="server" 
                Text='<%# Eval("Fax") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="tbFaxEdit" runat="server" 
                Text='<%# Eval("Fax") %>'></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="tbFaxFooter" runat="server" 
                Text=""></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

而 *.cs 檔要引用三個參考,
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

程式碼:
private SqlConnection connection;
private SqlCommand command;
private SqlDataAdapter adapter;
private DataTable dt;

private string strConnection;
private string strConnectionName = "NorthwindConnectionString";

protected void Page_Load(object sender, EventArgs e)
{
    /* 建立資料庫連線 */
    strConnection = ConfigurationManager.
        ConnectionStrings[strConnectionName].ConnectionString;
    connection = new SqlConnection(strConnection);
    command = new SqlCommand();
    command.Connection = connection;

    if (!IsPostBack)
        GVGetData();
}

/// <summary>
/// 取得資料
/// </summary>
private DataTable GetData()
{
    dt = new DataTable();
    command.CommandText = "SELECT * FROM Customers ";
    adapter = new SqlDataAdapter(command);

    adapter.Fill(dt);

    return dt;
}

/// <summary>
/// 取得資料
/// </summary>
private void GVGetData()
{
    DataTable _dt;

    if (ViewState["se"] == null)
    {
        _dt = GetData();
        gv.DataSource = _dt;
        gv.DataBind();
    }
    else
    {
        string se = Convert.ToString(ViewState["se"]);
        SortDirection sd = (SortDirection)ViewState["sd"];
        this.GVGetData(sd, se);
    }
}

/// <summary>
/// 取得排序資料
/// </summary>
private void GVGetData(SortDirection pSortDirection, 
    string pSortExpression)
{
    DataTable _dt = GetData();

    string sSort = string.Empty;
    if (pSortDirection == SortDirection.Ascending)
    {
        sSort = pSortExpression;
    }
    else
    {
        sSort = string.Format("{0} {1}", pSortExpression, "DESC"); 
    }

    DataView dv = _dt.DefaultView;
    dv.Sort = sSort;

    gv.DataSource = dv;
    gv.DataBind();

}

/// <summary>
/// 編輯資料
/// </summary>
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
    gv.EditIndex = e.NewEditIndex;

    GVGetData();
}

/// <summary>
/// 取消編輯
/// </summary>
protected void gv_RowCancelingEdit(object sender, 
    GridViewCancelEditEventArgs e)
{
    gv.EditIndex = -1;

    GVGetData();
}

/// <summary>
/// 更新資料
/// </summary>
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string strCustomerID, strCompanyName, strContactName, strContactTitle, strAddress, 
           strCity, strRegion, strPostalCode, strCountry, strPhone, strFax;

    strCustomerID = ((Label)gv.Rows[e.RowIndex].Cells[0].
        FindControl("lblCustomerIDEdit")).Text;
    strCompanyName = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbCompanyNameEdit")).Text;
    strContactName = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbContactNameEdit")).Text;
    strContactTitle = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbContactTitleEdit")).Text;
    strAddress = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbAddressEdit")).Text;
    strCity = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbCityEdit")).Text;
    strRegion = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbRegionEdit")).Text;
    strPostalCode = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbPostalCodeEdit")).Text; ;
    strCountry = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbCountryEdit")).Text;
    strPhone = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbPhoneEdit")).Text;
    strFax = ((TextBox)gv.Rows[e.RowIndex].Cells[0].
        FindControl("tbFaxEdit")).Text;

    /* 更新資料驗證作業 
       ...
       ...
       ...
    */

    /* 更新資料 */
    command.Parameters.Clear();
    command.Parameters.AddWithValue("customerID", strCustomerID);
    command.Parameters.AddWithValue("companyName", strCompanyName);
    command.Parameters.AddWithValue("contactName", strContactName);
    command.Parameters.AddWithValue("contactTitle", strContactTitle);
    command.Parameters.AddWithValue("address", strAddress);
    command.Parameters.AddWithValue("city", strCity);
    command.Parameters.AddWithValue("region", strRegion);
    command.Parameters.AddWithValue("postalCode", strPostalCode);
    command.Parameters.AddWithValue("country", strCountry);
    command.Parameters.AddWithValue("phone", strPhone);
    command.Parameters.AddWithValue("fax", strFax);

    command.CommandText = 
        @"UPDATE Customers SET CompanyName=@companyName, " +
        @"ContactName=@contactName, ContactTitle=@contactTitle, " +
        @"Address=@address, City=@city, Region=@region, " +
        @"PostalCode=@postalCode, Country=@country, " +
        @"Phone=@phone, Fax=@fax " +
        @"WHERE CustomerID=@customerID ";

    connection.Open();
    command.ExecuteNonQuery();
    connection.Close();

    gv.EditIndex = -1;

    GVGetData();
}

/// <summary>
/// 刪除資料
/// </summary>
protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    string strCustomerID;

    strCustomerID = ((Label)gv.Rows[e.RowIndex].Cells[0].
        FindControl("lblCustomerID")).Text;

    /* 刪除資料 */
    command.Parameters.Clear();
    command.Parameters.AddWithValue("customerID", strCustomerID);

    command.CommandText = 
        "DELETE FROM Customers WHERE CustomerID=@customerID ";

    connection.Open();
    command.ExecuteNonQuery();
    connection.Close();

    GVGetData();
}

protected void lbInsert_Click(object sender, EventArgs e)
{
    gv.FooterRow.Visible = true;
}

protected void lbCancelSave_Click(object sender, EventArgs e)
{
    gv.FooterRow.Visible = false;
}

/// <summary>
/// 儲存資料
/// </summary>
protected void lbSave_Click(object sender, EventArgs e)
{
    string strCustomerID, strCompanyName, strContactName, strContactTitle, strAddress,
           strCity, strRegion, strPostalCode, strCountry, strPhone, strFax;

    strCustomerID = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbCustomerIDFooter")).Text;
    strCompanyName = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbCompanyNameFooter")).Text;
    strContactName = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbContactNameFooter")).Text;
    strContactTitle = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbContactTitleFooter")).Text;
    strAddress = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbAddressFooter")).Text;
    strCity = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbCityFooter")).Text;
    strRegion = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbRegionFooter")).Text;
    strPostalCode = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbPostalCodeFooter")).Text; ;
    strCountry = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbCountryFooter")).Text;
    strPhone = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbPhoneFooter")).Text;
    strFax = ((TextBox)gv.FooterRow.Cells[0].
        FindControl("tbFaxFooter")).Text;

    /* 新增資料驗證作業 
       ...
       ...
       ...
    */

    /* 更新資料 */
    command.Parameters.Clear();
    command.Parameters.AddWithValue("customerID", strCustomerID);
    command.Parameters.AddWithValue("companyName", strCompanyName);
    command.Parameters.AddWithValue("contactName", strContactName);
    command.Parameters.AddWithValue("contactTitle", strContactTitle);
    command.Parameters.AddWithValue("address", strAddress);
    command.Parameters.AddWithValue("city", strCity);
    command.Parameters.AddWithValue("region", strRegion);
    command.Parameters.AddWithValue("postalCode", strPostalCode);
    command.Parameters.AddWithValue("country", strCountry);
    command.Parameters.AddWithValue("phone", strPhone);
    command.Parameters.AddWithValue("fax", strFax);

    command.CommandText = 
        @"INSERT INTO Customers (CustomerID, CompanyName, " + 
        @"ContactName, ContactTitle, Address, City, Region, " +
        @"PostalCode, Country, Phone, Fax) VALUES (@customerID, " +
        @"@companyName, @contactName, @contactTitle, @address, " +
        @"@city, @region, @postalCode, @country, @phone, @fax )";

    connection.Open();
    command.ExecuteNonQuery();
    connection.Close();

    GVGetData();
}

/// <summary>
/// 換頁
/// </summary>
protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gv.PageIndex = e.NewPageIndex;
    GVGetData();
}

/// <summary>
/// 排序
/// </summary>
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
    string se = ViewState["se"] != null ? 
        Convert.ToString(ViewState["se"]) : string.Empty;
    SortDirection sd = ViewState["sd"] != null ? 
        (SortDirection)ViewState["sd"] : SortDirection.Ascending;

    if (string.IsNullOrEmpty(se))
    {
        se = e.SortExpression;
        sd = SortDirection.Ascending;
    }

    // 如果欄位與本來不同
    if (se != e.SortExpression)
    {
        // 切換為目前所指定欄位
        se = e.SortExpression;

        // 指定排列方式為升冪
        sd = SortDirection.Ascending;
    }
    // 如果欄位與本來相同
    else
    {
        // 切換升冪為降冪,降冪為升冪
        if (sd == SortDirection.Ascending)
            sd = SortDirection.Descending;
        else
            sd = SortDirection.Ascending;
    }

    // 紀錄欄位與排列方式 ( 升冪或降冪 )
    ViewState["se"] = se;
    ViewState["sd"] = sd;

    GVGetData(sd, se);
}

顯示:
新增:
刪除:
修改:
排序:

回aspnet目錄
回首頁



2012年4月3日 星期二

VS加上AjaxControlToolkit工具

VS預設的AJAX工具很少

已經越來越無法滿足客戶需求

很多就會配合其他語言(例如JQuery)去做出客戶要的網頁

相對的設計與維護也會較為困難

AjaxControlToolkit提供了許多好用的AJAX工具給大家使用

官方網站
http://ajaxcontroltoolkit.codeplex.com/

AjaxControlToolkit
.net 4.0
AjaxControlToolkit.Binary.NET4.zip
.net 3.5
AjaxControlToolkit.Binary.NET35.zip


下載解壓縮(建議解壓縮到C,這樣才比較不會被誤刪)
裡面有很多語言的資料夾
試個人情況保留所需的即可

開啟VS>工具箱
任意一個標籤右鍵>加入索引標籤>打上標籤名稱(想在已有標籤內加入可略過此步驟)
要加入的標籤右鍵>選擇項目(這邊會要等一下)
.Net Framework元件>瀏覽>選取剛解壓縮出來的AjaxControlToolkit.dll
在原本.Net Framework元件就會多出從dll內取出的工具
這時可以選擇是否新增或取消
最後點下確認
這樣就將AjaxControlToolkit加入到VS工具箱了

回aspnet目錄
回首頁