Thursday, October 18, 2012

GridView Paging and Sorting


I just want to share how I make my paging and sorting in C#.  I had made a lot of styles before but this is the one that I used most, so in all of my Grid Views, here is what I do.
First you set up your GridView with the following properties:
<asp:GridView ID="myGridView" runat="server" 
AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True"
EmptyDataText="No Record Found" OnPageIndexChanging="myGridView_PageIndexChanging"
OnSorting="myGridView_Sorting" PageSize="15" >
AllowPaging and AllowSorting from the name itself allow the following attributes.  OnPageIndexChangingraises the PageIndexChanging event and OnSorting (yup you guessed it right) occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation.
I also used a drop down list for Paging with a combination of images.  So this is how my PagerTemplate looks like:
<PagerTemplate>
 <asp:ImageButton ID="imgPageFirst" runat="server" 
  ImageUrl="~/Images/Icons/PageFirst.png"
  CommandArgument="First" CommandName="Page" 
  OnCommand="imgPageFirst_Command">
 </asp:ImageButton>
 <asp:ImageButton ID="imgPagePrevious" 
  runat="server" ImageUrl="~/Images/Icons/PagePrevious.png"
  CommandArgument="Prev" CommandName="Page" 
  OnCommand="imgPagePrevious_Command">
 </asp:ImageButton>
 <asp:DropDownList ID="ddCurrentPage" runat="server" 
  CssClass="Normal" AutoPostBack="True"
  OnSelectedIndexChanged="ddCurrentPage_SelectedIndexChanged">
 </asp:DropDownList>
 <asp:Label ID="lblOf" runat="server" Text="of" CssClass="Normal"></asp:Label>
 <asp:Label ID="lblTotalPage" runat="server" CssClass="Normal"></asp:Label>
 <asp:ImageButton ID="imgPageNext" runat="server" 
  ImageUrl="~/Images/Icons/PageNext.png"
  CommandArgument="Next" CommandName="Page" 
  OnCommand="imgPageNext_Command"></asp:ImageButton>
 <asp:ImageButton ID="imgPageLast" runat="server" 
  ImageUrl="~/Images/Icons/PageLast.png"
  CommandArgument="Last" CommandName="Page" 
  OnCommand="imgPageLast_Command"></asp:ImageButton>
</PagerTemplate>
I made the AutoPostBack Property set to true so when a user changes the dropdown values, it will change page.  Now here is the code behind.
public partial class PageControls_SampleTaskList : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTaskList();
        }
    }

    //Bind your Grid View here
    private void BindTaskList()
    {
        DataSet myDataSet = null; //Set your Dataset here
        SetViewState(myDataSet);

        myGridView.DataSource = GetViewState();
        myGridView.DataBind();
    }

    private DataSet GetViewState()
    {
        //Gets the ViewState
        return (DataSet)ViewState["myDataSet"];
    }

    private void SetViewState(DataSet myDataSet)
    {
        //Sets the ViewState
        ViewState["myDataSet"] = myDataSet;
    }

    protected void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        DataSet myDataSet = GetViewState();
        DataTable myDataTable = myDataSet.Tables[0];
        myGridView.DataSource = SortDataTable(myDataTable, true);

        myGridView.PageIndex = e.NewPageIndex;
        myGridView.DataBind();
    }

    //This is invoked when the grid column is Clicked for Sorting, 
    //Clicking again will Toggle Descending/Ascending through the Sort Expression
    protected void myGridView_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataSet myDataSet = GetViewState();
        DataTable myDataTable = myDataSet.Tables[0];
        GridViewSortExpression = e.SortExpression;

        //Gets the Pageindex of the GridView.
        int iPageIndex = myGridView.PageIndex;
        myGridView.DataSource = SortDataTable(myDataTable, false);
        myGridView.DataBind();
        myGridView.PageIndex = iPageIndex;
    }

    //Gets or Sets the GridView SortDirection Property
    private string GridViewSortDirection
    {
        get
        {
            return ViewState["SortDirection"] as string ?? "ASC";
        }
        set
        {
            ViewState["SortDirection"] = value;
        }
    }
    //Gets or Sets the GridView SortExpression Property
    private string GridViewSortExpression
    {
        get
        {
            return ViewState["SortExpression"] as string ?? string.Empty;
        }
        set
        {
            ViewState["SortExpression"] = value;
        }
    }

    //Toggles between the Direction of the Sorting
    private string GetSortDirection()
    {
        switch (GridViewSortDirection)
        {
            case "ASC":
                GridViewSortDirection = "DESC";
                break;
            case "DESC":
                GridViewSortDirection = "ASC";
                break;
        }
        return GridViewSortDirection;
    }

    //Sorts the ResultSet based on the SortExpression and the Selected Column.
    protected DataView SortDataTable(DataTable myDataTable, bool isPageIndexChanging)
    {
        if (myDataTable != null)
        {
            DataView myDataView = new DataView(myDataTable);
            if (GridViewSortExpression != string.Empty)
            {
                if (isPageIndexChanging)
                {
                    myDataView.Sort = string.Format("{0} {1}",
                    GridViewSortExpression, GridViewSortDirection);
                }
                else
                {
                    myDataView.Sort = string.Format("{0} {1}",
                    GridViewSortExpression, GetSortDirection());
                }
            }
            return myDataView;
        }
        else
        {

            return new DataView();
        }
    }

    protected void myGridView_DataBound(object sender, EventArgs e)
    {
        //Custom Paging
        GridViewRow myGridViewRow = myGridView.TopPagerRow;

        if (myGridViewRow == null) return;

        //Get your Controls from the GridView, in this case 
        //I use a DropDown Control for Paging
        DropDownList ddCurrentPage = 
 (DropDownList)myGridViewRow.Cells[0].FindControl("ddCurrentPage");
        Label lblTotalPage = (Label)myGridViewRow.Cells[0].FindControl("lblTotalPage");

        if (ddCurrentPage != null)
        {
            //Populate Pager
            for (int i = 0; i < myGridView.PageCount; i++)
            {
                int iPageNumber = i + 1;
                ListItem myListItem = new ListItem(iPageNumber.ToString());

                if (i == myGridView.PageIndex)
                    myListItem.Selected = true;

                ddCurrentPage.Items.Add(myListItem);
            }
        }

        // Populate the Page Count
        if (lblTotalPage != null)
            lblTotalPage.Text = myGridView.PageCount.ToString();

    }

    //Change to a different page when the DropDown Page is changed
    protected void ddCurrentPage_SelectedIndexChanged(object sender, EventArgs e)
    {
        {
            GridViewRow myGridViewRow = myGridView.TopPagerRow;
            DropDownList ddCurrentPage = 
  (DropDownList)myGridViewRow.Cells[0].FindControl("ddCurrentPage");

            myGridView.PageIndex = ddCurrentPage.SelectedIndex;

            //Popultate the GridView Control
            DataSet myDataSet = GetViewState();
            DataTable myDataTable = myDataSet.Tables[0];

            myGridView.DataSource = SortDataTable(myDataTable, true);
            myGridView.DataBind();
        }
    }

    //Images for |<, <<, >>, and >|
    protected void imgPageFirst_Command(object sender, CommandEventArgs e)
    {
        Paginate(sender, e);
    }
    protected void imgPagePrevious_Command(object sender, CommandEventArgs e)
    {
        Paginate(sender, e);
    }
    protected void imgPageNext_Command(object sender, CommandEventArgs e)
    {
        Paginate(sender, e);
    }
    protected void imgPageLast_Command(object sender, CommandEventArgs e)
    {
        Paginate(sender, e);
    }

    protected void Paginate(object sender, CommandEventArgs e)
    {
        // Get the Current Page Selected
        int iCurrentIndex = myGridView.PageIndex;

        switch (e.CommandArgument.ToString().ToLower())
        {
            case "first":
                myGridView.PageIndex = 0;
                break;
            case "prev":
                if (myGridView.PageIndex != 0)
                {
                    myGridView.PageIndex = iCurrentIndex - 1;
                }
                break;
            case "next":
                myGridView.PageIndex = iCurrentIndex + 1;
                break;
            case "last":
                myGridView.PageIndex = myGridView.PageCount;
                break;
        }

        //Populate the GridView Control
        DataSet myDataSet = GetViewState();
        DataTable myDataTable = myDataSet.Tables[0];

        myGridView.DataSource = SortDataTable(myDataTable, true);
        myGridView.DataBind();
    }
}
I hope this post has been informative!

source http://www.codeproject.com/Articles/67520/GridView-Paging-and-Sorting

Wednesday, October 17, 2012

Sorting GridView Manually


            GridView control produces automatic sorting and paging behavior when bound to the SqlDataSource control. This is good news for developers who are using SqlDataSource. If you are using some other data source to populate the GridView you might need to add these features manually. In this article I will show you that how you can sort the columns of the GridView control when using a DataSet as the data source for the GridView.
Introduction:
GridView control produces automatic sorting and paging behavior when bound to the SqlDataSource control. This is good news for developers who are using SqlDataSource. If you are using some other data source to populate the GridView you might need to add these features manually. In this article I will show you that how you can sort the columns of the GridView control when using a DataSet as the data source for the GridView.

Populating the GridView Control:
Let's first populate the GridView control with some data. In this article I will be using theNorthwind database which is installed by default when you install SQL SERVER 7 orSQL SERVER 2000 database. Take a look at the code below which populates the GridView control.


private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";


private DataSet GetData(){
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}

As, you can see I am using simple DataSet container to populate the GridView control. Now, let's talk about sorting.

GridView HTML Code:
The first thing that you must notice is that I am not using any template columns in this article. The columns are generated automatically for the GridView control which are bound to the data source. Take a look at the HTML generated by the GridView control to have a clear picture.

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting"></asp:GridView>

The AllowSorting property has to be set to true so that it will render the GridView columns as links which can be clicked to fire the OnSortingevent.

Sorting GridView Columns:
Sorting can be done in different ways but in this article I will show you that how you sort in ascending and descending order. The first thing you need to have is a property which returns you the sort direction. The sort direction represents that if the column has to be sorted in ascending or descending order. 

public SortDirection GridViewSortDirection{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}

The GridViewSortDirection is a simple property which returns the new sort direction for the GridView control. Since, the header of the column triggers a postback that is why I am saving the last sort direction into the ViewState object. Once, I know the last direction I can give the user the new sort direction. This means that if the column was sorted in ascending order then the new direction has to be descending.
Now, let's take a look at the GridView_OnSorting event which is fired when you click the header of the column to sort it.

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e){
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}

The first line gets the name of the column that is clicked. This means that if you clicked on the CategoryName column the e.SortExpressionwill contain "CategoryName". The code is pretty simple, I check that if the last sort direction is ascending if so, then I sort the data in descending order and vice versa. The SortGridView method is responsible for the actual sort. Take a look at the SortGridView method given below:

private void SortGridView(string sortExpression,string direction){
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}

The SortGridView method takes the sortExpression and the direction as the parameters. The GetData method gets the data from the database.At this point it is a good idea to put the DataTable object into a Cache object so you don't have to fetch the data from the database on each request. A DataView is created on the DataTable and is sorted using the sortExpression and the direction. Finally, the DataView object is used to populate the GridView. 
I hope you liked the article, happy coding!


Friday, September 7, 2012

WinApp enter in text box


C# - WinApp enter in text box
Note เพื่อลืม
Code พิมข้อความใน textbox แล้วสามารถ enter เรียกให้ไปกดปุ่มหรือมี event เดียวกับการกดปุ่ม

วางในส่วน Form1.Designer.cs
this.textbox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKey);

วางในส่วน Form1.cs
private void CheckKey(object sender,KeyPressEventArgs e)
{
       if (e.KeyChar == (char)13)  // 13 มีค่าเท่ากับ enter
      {
            Button_Click(sender, e); // ส่ง event เดียวกับ การไปคลิก Button
      }
}

หากต้องการกด enter ที่ textbox แล้วไปที่่ control ตัวต่อไป

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
      
if (e.KeyChar == (char)13)
      {
        e.Handled = 
true;
        
SendKeys.Send("{TAB}");
      }
    }



หากต้องการใ้ห้เลื่อนไปยัง control ที่เราต้องการ 


private void TextBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
 if (e.KeyChar == Strings.Chr(13)) {
  TextBox2.Focus();
 }

}