Sunday, 27 April 2014

Difference between onClick & onSubmit events in HTML

Solution:-

S.NoonClick()onSubmit()
1
Event Category:
onClick() is a mouse event
Event Category:
onSubmit() is a form event
2
When it occurs:
This event occurs when a user click on mouse button
When it occurs:
This event occurs when we try to submit a form







That’s it!!…..Happy Programming...

Thursday, 24 April 2014

Show all GridView Rows in EditMode on Button Click in ASP.NET

dotnetcodingcircle: Show all GridView Rows in EditMode on Button Click
Sometimes, in the application we have a requirement that we need to show all GridView rows in edit mode. This means that all the rows will contain textboxes and the data should be visible in the textboxes. After done with editing we can update and get back to the view mode. 

The first task is the create a GridView and add two buttons(one for edit, other for update) like this :-

<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Label ID="lblPrice" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("price") %>' />
                            <asp:TextBox ID="txtPrice" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("price") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Label ID="lblQuantity" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("quantity") %>' />
                            <asp:TextBox ID="txtQuantity" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("quantity") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <asp:Button ID="editButton" runat="server" Text="Edit Button" OnClick="editButton_Click" />
            <asp:Button ID="updateButton" runat="server" Text="Update Button" OnClick="updateButton_Click" />

As, you can see in the aspx page that both my labels and the textboxes are in the ItemTemplate and their visibility depends on the 'IsInEditMode' property. Now let us see aspx.cs page

    public bool isEditMode = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindData();
        }
    }

    protected bool IsInEditMode
    {
        get { return this.isEditMode; }
        set { this.isEditMode = value; }
    }

    void bindData()
    {
        string connectionString = "Server=localhost;Database=master;Trusted_Connection=true";
        SqlConnection myConnection = new SqlConnection(connectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT price, quantity FROM demo", myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds);
        gvOrders.DataSource = ds;
        gvOrders.DataBind();
    }

    protected void editButton_Click(object sender, EventArgs e)
    {
        isEditMode = true;
        bindData();
    }

    protected void updateButton_Click(object sender, EventArgs e)
    {
        isEditMode = false;
        bindData();
        lblChatText.Text = "Gridview data updated succesfully";
    }



That’s it!!…..Happy Programming...

Friday, 18 April 2014

How to sort data in GridView in ASP.NET

In this article, i am going to give some overview on how to Sort the data when user click on Gridview Header Cell. While doing this, I developed a good piece of code which I do feel will help most of you in your development activity. 

Some Steps to enable Sorting :-
  1. Set AllowSorting="True" Property of GridView to enable sorting.
  2. Set SortExpression property of each column.
  3. Declare Sorting Event Name by just giving value in OnSorting in GridView.
aspx Page
<asp:GridView ID="gvOrders" Width="25%" runat="server" AutoGenerateColumns="False" AllowSorting="true" OnSorting="gvOrders_Sorting">
                  <Columns>
                      <asp:TemplateField HeaderText="Data Items" HeaderStyle-BackColor="Black">
                          <ItemTemplate>
                              <asp:Label ID="lblDataItem" runat="server" Text='<%# Container.DataItemIndex %>'></asp:Label>
                          </ItemTemplate>
                      </asp:TemplateField>
                      <asp:TemplateField HeaderText="Price" SortExpression="price">
                          <ItemTemplate>
                              <asp:Label ID="lblPrice" runat="server" Text='<%# Eval("price") %>' />
                          </ItemTemplate>
                      </asp:TemplateField>
                      <asp:TemplateField HeaderText="Quantity" SortExpression="quantity">
                          <ItemTemplate>
                              <asp:Label ID="lblQuantity" runat="server" Text='<%# Eval("quantity") %>' />
                          </ItemTemplate>
                      </asp:TemplateField>
                  </Columns>
 </asp:GridView>

aspx.cs Page
   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gvOrders.DataSource = bindData();
            gvOrders.DataBind();
        }
    }

    DataTable bindData()
    {
        string connectionString = "Server=localhost;Database=master;Trusted_Connection=true";
        SqlConnection myConnection = new SqlConnection(connectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT price, quantity FROM demo", myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds);
        return ds.Tables[0];
    }

    protected void gvOrders_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortingDirection = string.Empty;
        if (gridviewDirection == SortDirection.Ascending) // if ascending, make it descending
        {
            gridviewDirection = SortDirection.Descending;
            sortingDirection = "Desc";
        }
        else
        {
            gridviewDirection = SortDirection.Ascending; // if descending, make it ascending
            sortingDirection = "Asc";
        }

        DataView sortedView = new DataView(bindData()); // get gridview data and store it in dataview
        sortedView.Sort = e.SortExpression + " " + sortingDirection; // format(Column_Name [ASC|DESC])
        gvOrders.DataSource = sortedView;
        gvOrders.DataBind(); // bind gridview data after sorting in appropriate format
    }
Now here, I am storing direction in ViewState i.e.(Ascending or Descending). 


    public SortDirection gridviewDirection
    {
        get
        {
           if (ViewState["directionState"] == null)
           {
               ViewState["directionState"] = SortDirection.Ascending; // to set default value ascending
           }
           return (SortDirection)ViewState["directionState"];
        }

        set
        { ViewState["directionState"] = value; }
    }
To show all gridview rows in edit mode http://dotnetcodingcircle.blogspot.in/2014/04/show-all-gridview-rows-in-editmode-on.html


That’s it!!…..Happy Programming...

Friday, 11 April 2014

Allow only One Decimal & Numerics Value in textbox in C# ASP.NET using JAVASCRIPT

Below is the function which will validate the text box value and will only allow one decimal and Numerics value in it.

Aspx Page:
<asp:TextBox ID="txtAmount" placeholder="Enter Amount Here" onkeypress="return onlyOneDotAndNumbers(this,event);" runat="server"></asp:TextBox>

Javascript Function:
 function onlyOneDotAndNumbers(txt, event) {
            var charCode = (event.which) ? event.which : event.keyCode
            if (charCode == 46) {
                if (txt.value.indexOf(".") < 0)
                    return true;
                else
                    return false;
            }

            if (txt.value.indexOf(".") > 0) {
                var txtlen = txt.value.length;
                var dotpos = txt.value.indexOf(".");
                if ((txtlen - dotpos) > 2)
                    return false;
            }

            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;

            return true;
        }

That’s it!!…..Happy Programming...

Sunday, 6 April 2014

How to Remove Unwanted Whitespace(s) between Words in C#

When dealing with user input (especially on web), we do not have control over some strange things. One common issue when user enter text, places too many spaces between words. A lot of times this is due to some copy and paste issue such as a user pasting text from a Microsoft Word document.

The common thought might be to add a bunch of replace methods to replace 2 spaces with 1, 3 spaces with 1, 4 spaces with 1, etc. Something like this :

enteredString = enteredString.Replace("  ", " ");
enteredString = enteredString.Replace("   ", " ");
enteredString = enteredString.Replace("    ", " ");


The main issue here is that you need to know in advance, for how many spaces you are looking to make this work correctly. For Example :-  In above case, if the string had more than 4 spaces, then things get disorderly. we could manually parse the string character by character, use peek and compare to find and remove spaces but there is actually an easier way to do this.


Using the method below, no matter how many spaces together in the string, this method will remove them and replace with a single space.

 public static string MoveOutExtraSpace(string enteredString)
 {
     enteredString = enteredString.Replace(" ", "()");
     enteredString = enteredString.Replace(")(", "");
     enteredString = enteredString.Replace("()", " ");
     enteredString = enteredString.Trim(); // for start and end space
     return enteredString;
 }

That’s it!!…..Happy Programming...