Saturday, 25 October 2014

Something about Empty String

In this article, i am going to explain meaning of an Empty String in int type column.
create table tblEmptyString (SrNo int null)
insert into tblEmptyString (SrNo) values (1)
insert into tblEmptyString (SrNo) values (2)
insert into tblEmptyString (SrNo) values ('')
insert into tblEmptyString (SrNo) values (null)

select * from tblEmptyString

Output

As we can see, implicit conversion of the empty string to a value of 0 happened here. These Issues sometimes can create problems for us. So from now, we have to care about Empty String more.

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

Saturday, 18 October 2014

CSS tooltip on hover

In this article, i am going to show how to apply custom styles on Tooltip.

Aspx Code

   <table style="width: 300px;">
        <tr>
            <td>Username:
            </td>
            <td>
                <a href="#" accesskey="Please enter your username" class="tooltipshow">
                    <input id="txtUsername" type="text" /></a>
            </td>
        </tr>
        <tr>
            <td>Password:
            </td>
            <td>
                <a href="#" accesskey="Please enter your password" class="tooltipshow">
                    <input id="txtPassword" type="text" /></a>
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input id="btnSubmit" type="button" value="Login" />
            </td>
        </tr>
    </table>

 CSS Code

.tooltipshow {
display:inline;
position:relative;
text-decoration:none;
top:0;
left:10px;
}

.tooltipshow:hover:after {
background:rgba(0,0,0,.8);
border-radius:5px;
top:-5px;
color:#fff;
content:attr(accesskey);
left:160px;
position:absolute;
z-index:98;
width:150px;
padding:5px 15px;
}

.tooltipshow:hover:before {
border:solid;
bottom:20px;
content:"";
left:155px;
position:absolute;
z-index:99;
top:3px;
border-color:transparent #000;
border-width:6px 6px 6px 0;
}

In CSS, we have set the content attribute to content: attr(accesskey); this property will display the tooltip by using the accesskey attribute of the anchor tag. Whatever we pass in to the accesskey attribute of the anchor tag it will be displayed as a tooltip. Have something to add to this post? Share it in the comments.
 Output

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

Saturday, 11 October 2014

Bind Category and Subcategory in asp.net

In this article, i am going to explain how to maintain Category and Subcategory hierarchy in asp.net.

Aspx Page

   <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblMsg" runat="server"></asp:Label>
            <ul>
                <asp:Repeater ID="repCategory" runat="server" OnItemDataBound="repCategory_ItemDataBound">
                    <ItemTemplate>
                        <li>
                            <asp:Label Font-Size="Large" Font-Bold="true" ID="lblCategoryName" runat="server"
                                Text='<%# Eval("CategoryName") %>' />
                        </li>
                        <ul>
                            <asp:Repeater ID="repSubCategory" runat="server">
                                <ItemTemplate>
                                    <li style="background-color:lightblue">
                                        <asp:HyperLink ID="hlkSubCategory" runat="server" Text='<%# Eval("SubCategoryName")%>' />
                                    </li>
                                </ItemTemplate>
                            </asp:Repeater>
                        </ul>
                    </ItemTemplate>
                </asp:Repeater>
            </ul>
        </div>
    </form>

 CS Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class Category : System.Web.UI.Page
{
    string strConnection = @"Data Source=AMREEK\SQLEXPRESS; uid=sa; pwd=12345;database=demo;";
    
    protected void Page_Load(object sender, EventArgs e)
    {
        BindData();
    }

    private void BindData()
    {
        try
        {
            SqlConnection myConnection = new SqlConnection(strConnection);
            SqlCommand myCommand = new SqlCommand("[dbo].[GetCategoryWithSubCategory]", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter ad = new SqlDataAdapter(myCommand);
            DataSet ds = new DataSet();
            ad.Fill(ds);
            // Attach the relationship to the dataSet with relationship name, parent column, child column
            ds.Relations.Add(new DataRelation("CategoriesRelation", ds.Tables[0].Columns["CategoryID"],
            ds.Tables[1].Columns["CategoryID"]));
            repCategory.DataSource = ds.Tables[0];
            repCategory.DataBind();
        }

        catch(Exception ex)
        { Response.Write(ex.Message); }

    }

    protected void repCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item ||
        e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DataRowView drv = e.Item.DataItem as DataRowView;
            Repeater innerRep = e.Item.FindControl("repSubCategory") as Repeater;
            innerRep.DataSource = drv.CreateChildView("CategoriesRelation");
            innerRep.DataBind();
        }
    }
}

SQL Query 

-- category table --
create table category
(
categoryId int identity primary key not null,
categoryName nvarchar(100) not null
)

insert category values ('a')
insert category values ('b')
insert category values ('c')
select * from category


-- sub category table --
create table subcategory
(
categoryId int not null FOREIGN KEY REFERENCES category(categoryId),
subcategoryId int identity not null,
subcategoryName nvarchar(100) not null,
)

insert subcategory values (1,'one')
insert subcategory values (1,'two')
insert subcategory values (1,'three')
insert subcategory values (2,'one')
insert subcategory values (2,'two')
insert subcategory values (3,'one')
insert subcategory values (3,'two')
insert subcategory values (3,'three')
insert subcategory values (3,'four')
select * from subcategory



-- procedure to select both tables data --
Go
Create PROCEDURE [dbo].[GetCategoryWithSubCategory]
AS

-- only those categories selected whose sub-categories exist
SELECT * FROM category WHERE CategoryID IN
( SELECT CategoryID FROM subcategory )

-- select all records from subcategories, here p just used as alias
SELECT p.subcategoryId , p.SubCategoryName ,p.CategoryID FROM subcategory p
Go
 Output

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

Friday, 3 October 2014

How to Add Dynamic Rows in Gridview in ASP.NET

In this article, i am going to show how to add dynamic rows in gridview control..

aspx page

 <asp:GridView ID="gvRecords" runat="server" OnRowCommand="gvRecords_RowCommand" DataKeyNames="SrNo" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Sr No.">
                <ItemTemplate>
                    <asp:TextBox ID="txtSrNo" runat="server" Text='<%# Eval("SrNo") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Name">
                <ItemTemplate>
                    <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Salary">
                <ItemTemplate>
                    <asp:TextBox ID="txtAmount" runat="server" Text='<%# Eval("Salary") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:ButtonField ButtonType="Button" CommandName="cmd_delete" Text="Delete" />
        </Columns>
    </asp:GridView>
    <asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />

cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class dynamicgridview : System.Web.UI.Page
{
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gvRecords.DataSource = GetTableWithInitialData(); // get initial data
            gvRecords.DataBind();
        }
    }

    public DataTable GetTableWithInitialData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("SrNo", typeof(string));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Salary", typeof(double));

        table.Rows.Add(1, "Manpreet", 25000);
        table.Rows.Add(2, "Gurpreet", 20000);
        table.Rows.Add(3, "Prabhjot", 33000);
        SaveGridInViewstate(table);
        return table;
    }

    protected void btnAddRow_Click(object sender, EventArgs e)
    {
        DataTable dt = GetTableWithNoData(); // get table structure by calling the specified function
        DataRow dr;

        foreach (GridViewRow gvr in gvRecords.Rows)
        {
            dr = dt.NewRow();

            TextBox txtSrNo = gvr.FindControl("txtSrNo") as TextBox;
            TextBox txtName = gvr.FindControl("txtName") as TextBox;
            TextBox txtAmount = gvr.FindControl("txtAmount") as TextBox;
            dr[0] = txtSrNo.Text;
            dr[1] = txtName.Text;

            if (txtAmount.Text == string.Empty)
            {
                dr[2] = DBNull.Value;
            }

            else
            {
                dr[2] = txtAmount.Text;
            }

            dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
        }

        dr = dt.NewRow(); // add new empty row
        dt.Rows.Add(dr);

        gvRecords.DataSource = dt; // bind newly created datatable to grid
        gvRecords.DataBind();
        SaveGridInViewstate(dt);
    }

    public DataTable GetTableWithNoData() // returns only table structure 
    {
        DataTable table = new DataTable();
        table.Columns.Add("SrNo", typeof(string));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Salary", typeof(double));
        return table;
    }

    // save datatable into viewstate which would be useful for deletion
    public void SaveGridInViewstate(DataTable dt)
    {
        ViewState["gvRecords"] = dt;
    }

    protected void gvRecords_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "cmd_delete")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            if (ViewState["gvRecords"] != null)
            {
                dt = ViewState["gvRecords"] as DataTable;
                DataRow row = dt.Rows[index];
                dt.Rows.Remove(row);
                gvRecords.DataSource = dt; // bind newly created datatable to grid
                gvRecords.DataBind();
            }
        }
    }
}
Output

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