Tuesday, 24 June 2014

How to Set MaxLength property for ASP.NET Multiline Textbox

Once there was a requirement in a project where I had to set the max length of TextBox in Multiline mode so I just set the MaxLength property of TextBox to the length which was required but it doesn’t worked. When i Searched on this, i found that when we put TextBox in our WebForm it’ll be rendered to HTML <input> tag but when we set the TextMode to multiline it’ll be rendered to <textarea> tag not an <input > tag, and MaxLength attribute is in <input> but it’s not for <textarea>. That's why i had to face this problem. Finally, I solved this problem by making javascript function.

aspx page

<asp:TextBox ID="txtName" runat="server" TextMode="MultiLine" onkeypress="return SetMaxLength(this,10);">

javascript function

    // maxLength value supplied by user
      function SetMaxLength(txt, maxLength) {

          if (txt.value.length >= (maxLength)) {
                return false;
          }
          else {
                return true;
          }
      }
As you can see, i am passing 10 in it that's why it will make the max number of characters user can input in the TextBox is 10. You can set it to accrording to your requirement. That's it.. Hope it will help you..


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

Saturday, 21 June 2014

How to find non-matching rows using EXCEPT in SQL

In this article, i am going to explain how to select non-matching rows using EXCEPT in SQL. I am creating two temporary table to demonstrate the same.In Short, EXCEPT operator returns all distinct rows from left hand side table which does not exist in right hand side table. One more interesting point to know, NOT IN also works like EXCEPT operator but it will not remove duplicate rows from the result.

to create and insert table data
create table #one (id int,name nvarchar(50))
insert into #one (id , name) values(1,'a') 
insert into #one (id , name) values(2,'b') 
insert into #one (id , name) values(3,'c') 

create table #two (id int,name nvarchar(50))
insert into #two (id , name) values(1,'a') 
insert into #two (id , name) values(3,'b') 
insert into #two (id , name) values(4,'c') 

to select by using query
select id from #one EXCEPT select id from #two 

Output


One basic rule of EXCEPT operator, you must have to specify number of columns and order same in all queries.

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

Sunday, 8 June 2014

Persisting Row Selection of Data Controls in ASP.NET

Some times we need show large amount of data like hundred of rows but its very difficult to show that in a single web page so we use the paging mechanism to handle this kind of situation. ASP.NET Data Controls row selection feature was based on row index , this of course produce an issue if you try to select an item in the first page then navigate to the second page without select any record you will find the same row selected in the second page( this occurs due to same row index).

For Example:
  • Select the third row in the GridView.
  • Navigate to second page without doing any selection
  • You will find the third row in the second page selected.

I discovered that Microsoft has introduced a new property in ASP .Net 4.0 for data bound control like GridView,ListView named as EnablePersistedSelection. Now you are thinking why EnablePersistedSelection introduced ??

It is a new feature which replace the old selection mechanism which based on row index to be based on the row data key instead.

So now by making EnablePersistedSelection="True", if a row is selected on first page, later you move to next page, no row is selected on the next page but on returning back to first page, old row is still selected.Here is the code for that:-
 <asp:GridView ID="PersistedGridView" runat="server" EnablePersistedSelection="true">
 </asp:GridView>
Don't forget to add the DataKeyNames when you enable this property, since the property is fully based on the DataKeyNames associated with that row.If not, following error occurs:-

That’s it.. Hope it will help you..

Happy Programming...

Friday, 6 June 2014

How to add Expand And Collapse Feature In REPEATER Control

There are many times when a we all needs to Expand and Collapse text on a website. This feature is especially useful when it comes to setting up FAQs or creating quiz features.In this article, i am going to give complete overview on how to add Expand and Collapse feature in ASP.NET using JavaScript function.


aspx.cs page


aspx page

<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">
        function ExpandableDisplay(id) {
            // 'd' was concatenated to get id of description text
            var descelem = document.getElementById('d' + id);
            if (descelem) {
                if (descelem.style.display != 'block') {
                    descelem.style.display = 'block';
                    descelem.style.visibility = 'visible';
                }
                else {
                    descelem.style.display = 'none';
                    descelem.style.visibility = 'hidden';
                }
            }
        }
    </script>

    <style type="text/css">
        .header { font-size: larger; margin: 10px; font-weight: bold; cursor: pointer; background-color: #cccccc; font-family: Verdana; }
        .description { display: none; margin: 15px; visibility: hidden; font-family: Verdana; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Repeater ID="repeaterItems" runat="server">
            <ItemTemplate>
                <%--'h' used for making it header text--%>
                <div id='h<%# DataBinder.Eval(Container, "ItemIndex") %>' class="header"
                    onclick='ExpandableDisplay(<%# DataBinder.Eval(Container, "ItemIndex") %>);'>
                    <b>Price: </b><%# DataBinder.Eval(Container.DataItem, "price") %><b> Rs.</b>
                </div>
                <%--'d' used for making it description text--%>
                <div id='d<%# DataBinder.Eval(Container, "ItemIndex") %>' class="description">
                    <b>Quantity Available:</b> <%# DataBinder.Eval(Container.DataItem, "quantity") %><br />
                </div>
            </ItemTemplate>
        </asp:Repeater>

    </form>
</body>
</html>

Expand and Collapse Output




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

Thursday, 5 June 2014

Implement Paging in DataList using ASP.NET

When building ASP.NET Web applications, one of the most common tasks is displaying data. ASP.NET offers a powerful data Web control - the DataList but imposes some limitations on its paging capabilities. Therefore, i am going to explain how to implement paging in DataList using ASP.NET.

aspx page

<form id="form1" runat="server">
        <table>
            <asp:DataList ID="dltItems" runat="server">
                <HeaderTemplate>
                    <h2>Item Details </h2>
                </HeaderTemplate>
                <ItemTemplate>
                    <tr>
                        <td>
                            <h4>Price</h4>
                        </td>
                        <td>
                            <h4>Quantity</h4>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <h5><%#Eval("price") %></h5>
                        </td>
                        <td>
                            <h5><%#Eval("quantity") %></h5>
                        </td>
                    </tr>
                </ItemTemplate>
            </asp:DataList>
        </table>
        <table>
            <tr>
                <td>
                    <asp:Button ID="btnfirst" runat="server" Font-Bold="true" Text="<<" OnClick="btnfirst_Click" /></td>
                <td>
                    <asp:Button ID="btnprevious" runat="server" Font-Bold="true" Text="<" OnClick="btnprevious_Click" /></td>
                <td>
                    <asp:Button ID="btnnext" runat="server" Font-Bold="true" Text=">" OnClick="btnnext_Click" /></td>
                <td>
                    <asp:Button ID="btnlast" runat="server" Font-Bold="true" Text=">>" OnClick="btnlast_Click" /></td>
            </tr>
        </table>
    </form>

aspx.cs page

    PagedDataSource pdsPaging = new PagedDataSource();
    int startPosition;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["vspaging"] = 0;
        }

        startPosition = Convert.ToInt32(ViewState["vspaging"].ToString());
        bindData();
    }

    void bindData()
    {
        string connectionString = "Server=localhost;Database=shopping;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);
        pdsPaging.DataSource = ds.Tables[0].DefaultView; //returns dataview
        pdsPaging.PageSize = 4; // specify no. of rows bind at startup
        pdsPaging.AllowPaging = true; // make it true to allow paging
        pdsPaging.CurrentPageIndex = startPosition;
        dltItems.DataSource = pdsPaging;
        dltItems.DataBind(); // bind data in datalist
    }

    protected void btnfirst_Click(object sender, EventArgs e)
    {
        startPosition = 0; // set it zero to go to first page
        bindData();
    }

    protected void btnprevious_Click(object sender, EventArgs e)
    {
        startPosition = Convert.ToInt32(ViewState["vspaging"].ToString());
        startPosition -= 1; // subtract one from actual postion
        ViewState["vspaging"] = startPosition; // set new value in viewstate
        bindData();
    }

    protected void btnnext_Click(object sender, EventArgs e)
    {
        startPosition = Convert.ToInt32(ViewState["vspaging"].ToString());
        startPosition += 1; // add one in actual postion
        ViewState["vspaging"] = startPosition; // set new value in viewstate
        bindData();
    }

    protected void btnlast_Click(object sender, EventArgs e)
    {
        // subtract one from no. of total pages because index starts from zero
        startPosition = pdsPaging.PageCount - 1;
        bindData();
    }

Paging Output



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