Monday 27 August 2012

Using List View Control

Many times we need to show data to the user in List Views. For demonstration purpose I have extracted this sample from a project which search Ayah text from entering some text in search box.

As you can see that first thing is ListView which contains data source as "SqlDataSource1" which is given at the end of code.  That SqlDataSource contains mandatory tags which are easy to learn.

Now come to the ListView code:

First of all we have to define a overall layout of List View. How we want to show our contents to the user. As you can see that I have shown the Title (the keywords to be searched) using property GetTextBoxText and under that another property which shows how many results found by GetTotalResults.

under these two things there is a ul which is actually a container of list items li. Notice that li has the id "itemPlaceholder". This li will contain items of the list.

 After the list we have DataPager component in our layout. DataPager has three main things one is FirstPage second is the numeric page numbers and third is the LastPage. we will just have to give PagedControlID as ListView's ID. At this point our main layout is completed.

ItemTemplate contains your customized code which will show your items in List


[code]
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" >
                   
                    <LayoutTemplate>
                    <i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Search Result for: <b><%=GetTextBoxText%></b></i>
                    <p>Total results found: <%=GetTotalResults%></p>
                        <ul ID="itemPlaceholderContainer" runat="server"
                            style="font-family: Verdana, Arial, Helvetica, sans-serif;">
                            <li runat="server" id="itemPlaceholder" />
                        </ul>
                        <div style="text-align: center;background-color: #CCCCCC;font-family: Verdana, Arial, Helvetica, sans-serif;color: #000000;">
                            <asp:DataPager ID="DataPager1" runat="server" PageSize="10" PagedControlID= "ListView1">
                                <Fields>
                                    <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
                                        ShowNextPageButton="False" ShowPreviousPageButton="False" />
                                    <asp:NumericPagerField />
                                    <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True"
                                        ShowNextPageButton="False" ShowPreviousPageButton="False" />
                                </Fields>
                            </asp:DataPager>
                        </div>
                       
                    </LayoutTemplate>
<ItemTemplate>
                        <li style="background-color: #DCDCDC;color: #000000;"><b>AyahText:</b>
                            <asp:Label ID="AyahTextLabel" runat="server" Text='<%#HighlightKeywords(""+Eval("AyahText"),txt_search.Text)%>' />
                            <br />
                        </li>
                        <br />
                        <i><asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# String.Format("AyahDetail.aspx?chno={0}&ayahno={1}", Eval("ChapterID"),Eval("VerseIdBegin")) %>'>Sura Name:&nbsp;<%#DataHandling.GetSurahName(Convert.ToInt32(Eval("ChapterID")))%>&nbsp; Ayah No:&nbsp;<%#Eval("VerseIdBegin")%></asp:HyperLink></i>
                        </ItemTemplate>

                        <AlternatingItemTemplate>
                           
                            <li style="background-color: #FFF8DC;"><b>AyahText:</b>
                                <asp:Label ID="AyahTextLabel" runat="server" Text='<%#HighlightKeywords(""+Eval("AyahText"),txt_search.Text)%>' />
                                <br />
                            </li>
                            <br />
                        <i><asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# String.Format("AyahDetail.aspx?chno={0}&ayahno={1}", Eval("ChapterID"),Eval("VerseIdBegin")) %>'>Sura Name:&nbsp;<%#DataHandling.GetSurahName(Convert.ToInt32(Eval("ChapterID")))%>&nbsp; Ayah No:&nbsp;<%#Eval("VerseIdBegin")%></asp:HyperLink></i>
                        </AlternatingItemTemplate>

                    <ItemSeparatorTemplate>
                       
                        <hr /><br />
                        </ItemSeparatorTemplate>
                    </asp:ListView>

//---------------------------------------------------------------------------------------------------------------------
//---------------------------------SQL Data Source---------------------------------------------------------------

 <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                        ConnectionString="<%$ ConnectionStrings:QuranConnectionString2 %>"
                      
                        SelectCommand="SELECT * FROM [Quran] WHERE (([QuranID] = @QuranID) AND ([AyahText] LIKE '%' + @AyahText + '%') OR ([Keywords] LIKE '%' + @Keywords + '%'))">
                        <SelectParameters>
                            <asp:Parameter DefaultValue="100" Name="QuranID" Type="Decimal" />
                            <asp:ControlParameter ControlID="txt_search" Name="AyahText"
                                PropertyName="Text" Type="String" />
                            <asp:ControlParameter ControlID="txt_search" Name="Keywords"
                                PropertyName="Text" Type="String" />
                        </SelectParameters>
</asp:SqlDataSource>

[/code]

Tuesday 14 August 2012

Searching Words from Paragraph

Following method is helpful when we have to search specific word or words separated by specific symbol (here space and ,). This will highlight those words using CSS.

[Code]

public string HighlightKeywords(string input, string keywords)
    {
        if (input == string.Empty || keywords == null)
        {
            return input;
        }
        char[] splt = { ' ', ',' };
        string[] sKeywords = keywords.Split(splt);
        foreach (string sKeyword in sKeywords)
        {
            try
            {

// here highlight is a class in CSS.

                input = Regex.Replace(input, sKeyword, string.Format("<span class=\"highlight\">{0}</span>", "$0"), RegexOptions.IgnoreCase);
            }
            catch
            {
                //
            }
        }
        return input;
    }

//CSS class

.highlight
{
    background-color:Yellow;
    font-style:italic;
}

[/Code]

Tuesday 7 August 2012

Create an JQuery Advertising Div on page which will disappear after some time.


Following function is useful for auto hiding a div from a page using JQuery
just copy and paste it in head tags

[code]
<script type="text/javascript">
        $(function () {
            $(document).ready(function () {
                setTimeout(function () {
                    $('#YOUR DIV ID').fadeOut('slow');
                }, 5000);   //<--- Time in miliseconds after which div will hide.
            });
        });
    </script>
[/code]

Sunday 5 August 2012

Dynamic Parameter SQL Query.

If in case you have multiple search boxes in which query can be made on any text box entry (as shown in above screenshot). Code will be as follows, in which Dynamic query will be generated (Search Button Click Event Code).

[Code]


        StringBuilder query = new StringBuilder();

        string name, cnic, email, empno;
        name = txtName.Text.Trim();
        cnic = txtCNIC.Text.Trim();
        email = txtEmailAssigned.Text.Trim();
        empno = txtEmployeeNo.Text.Trim();

        List<TextBox> txtBoxes = new List<TextBox>();

        txtBoxes.Add(txtName);
        txtBoxes.Add(txtEmailAssigned);
        txtBoxes.Add(txtCNIC);
        txtBoxes.Add(txtEmployeeNo);

        query.Append("SELECT * FROM EmailTable");
        bool containstext = false;

        //Following foreach will check whether any text box contains some text or not

        foreach (TextBox tb1 in txtBoxes)
        {
            if (tb1.Text.Length != 0)
            {
                containstext = true;
            }
        }

        if (containstext)
        {
            int counter = 0;
            query.Append(" WHERE");
            string condition = "";

            foreach (TextBox tb in txtBoxes)
            {
                condition = string.Empty;
                condition = tb.Text;

                if (!string.IsNullOrEmpty(condition))
                {
                    switch (tb.ID)
                    {
                        case "txtName":
                            condition = " fname LIKE '%" + condition + "%'";
                            counter++;
                            break;
                        case "txtEmailAssigned":
                            condition = " email_assigned LIKE '%" + condition + "%'";
                            counter++;
                            break;
                        case "txtCNIC":
                            condition = " cnic LIKE '%" + condition + "%'";
                            counter++;
                            break;
                        case "txtEmployeeNo":
                            condition = " empno LIKE '%" + empno + "%'";
                            counter++;
                            break;
                    }

                    if (counter > 1)
                    {
                        condition = " AND " + condition;
                    }
                }

                query.Append(condition);
            }

            query.Append("AND disable IS NULL AND deleted IS NULL");
            //Response.Write(query);
           
            DataSet ds = dh.GetEmployeeDetail(query.ToString());

            GridView1.DataSource = ds;
            GridView1.DataBind();

[/Code]