Archive for April, 2015

How to wrap text in GridView Template columns in Asp.net.

Introduction:

Usually Gridview columns don’t wrap when the text content in the Gridview columns overflows the allocated width, it will keep expanding which makes the Gridview looks a bit odd.  To resolve this issue we need a custom implementation which will assign word wrap dynamically to GridView columns.

Problem Demo is given below

In my previous article I have explained the way to apply column wrap in GridView BoundField column. In this article I am going to explain how to apply word wrap for GridView’s Template columns.

Implementation:

You need to subscribe to GridView RowDatabound event and then apply the css styles to your respective columns in GridView.

         /// <summary>
        /// Handles the RowDataBound event of the GridView6 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void GridView6_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //here change the column index as per your GridVIew Design
                e.Row.Cells[0].Attributes.Add("style", "word-break:break-all;word-wrap:break-word;");
            }
        }

Complete Code

HTML

        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:GridView ID="GridView6" runat="server" AutoGenerateColumns="False" DataKeyNames="FirstName" ForeColor="#333333" GridLines="Both" Width="250" OnRowDataBound="GridView6_RowDataBound">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="Description" ItemStyle-Width="100px" HeaderStyle-Width="250px" >
                    <ItemTemplate>
                        <asp:Label ID="lblDescription" runat="server" Text='<%#Eval("FirstName") %>' Width="250" ></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

C#:

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Assign the data to GridView
                GridView6.DataSource = this.Get_LongText();
                //Bind the Grid
                GridView6.DataBind();
            }
        }

        //Populate some dummy data
        public DataTable Get_LongText()
        {

            DataTable dt = new DataTable();
            DataRow dr;
            string Item = "ThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtext,ThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtext,Fruit2,Fruit3";
            string[] list = Item.Split(',');
            string Item2 = "ThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtext,ThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtext,Fruit2,Fruit3";
            string[] list2 = Item2.Split(',');
            dt.Columns.Add("FirstName", typeof(string));
            dt.Columns.Add("LastName", typeof(string));
            for (int i = 0; i < list.Length; i++)
            {
                dr = dt.NewRow();
                dr["FirstName"] = list[i];
                dr["LastName"] = list2[i];
                dt.Rows.Add(dr);
            }
            return dt;
        }

protected void GridView6_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //here change the column index as per your GridVIew Design
                e.Row.Cells[0].Attributes.Add("style", "word-break:break-all;word-wrap:break-word;");
            }
        }

Demo

, , , ,

Leave a comment

How to wrap text in GridView Bound columns in Asp.net.

Introduction:

Usually Gridview columns don’t wrap when the text content in the Gridview columns overflows the allocated width, it will keep expanding which makes the Gridview looks a bit odd.  To resolve this issue we need a custom implementation which will assign word wrap dynamically to Gridview columns. 

Implementation:

In this article I am going to explain how to apply word wrap for GridView’s BoundField columns. To add word wrap in Gridview we can make use of word-break css style property.

You can follow the below steps to assign the css word wrap to your Gridivew.

First add the below css style to your page.

<style type="text/css">
        .WordWrap {
            width: 100%;
            word-break: break-all;
        }
    </style>

Then add a div as a container control for you Gridivew. We need to assign the css style to this container div

<div class="WordWrap">
     <%--Add your gridview here--%>
</div>

That’s it now you have word wrap applied to your Gridview.

Complete sample code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style type="text/css">
        .WordWrap {
            width: 100%;
            word-break: break-all;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div class="WordWrap">
            <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:GridView ID="GridView6" runat="server" AutoGenerateColumns="False" DataKeyNames="FirstName"
                ForeColor="#333333" GridLines="Both" Width="50%">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:BoundField HeaderText="FirstName" DataField="FirstName">
                        <ItemStyle Width="35" />
                        <HeaderStyle Width="100px" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="LastName" DataField="LastName">
                        <ItemStyle Width="50" />
                        <HeaderStyle Width="100px" />
                    </asp:BoundField>
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

C#:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Assign the data to GridView
                GridView6.DataSource = this.Get_LongText();
                //Bind the Grid
                GridView6.DataBind();
            }
        }

        //Populate some dummy data
        public DataTable Get_LongText()
        {

            DataTable dt = new DataTable();
            DataRow dr;
            string Item = "ThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtext,ThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtext,Fruit2,Fruit3";
            string[] list = Item.Split(',');
            string Item2 = "ThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtext,ThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtextThisisalongtext,Fruit2,Fruit3";
            string[] list2 = Item2.Split(',');
            dt.Columns.Add("FirstName", typeof(string));
            dt.Columns.Add("LastName", typeof(string));
            for (int i = 0; i < list.Length; i++)
            {
                dr = dt.NewRow();
                dr["FirstName"] = list[i];
                dr["LastName"] = list2[i];
                dt.Rows.Add(dr);
            }
            return dt;
        }

Demo Image

, , , ,

1 Comment

Move focus to next TextBox automatically when user types in the Textbox in Asp.Net

Introduction:

In this article I am going to explain how to move the focus to next textbox when user types in textbox and the total character count cross the limit of maxlength property.

Prerequisites:

You need to add the necessary JQuery files to your page prior to use this plugin. In this example I have used the online JQuery CDN files available. If you don’t want to use the online available cdn file then you can manually add the jquery files to your solution. I have explained the steps here in detail.

Implementation:

Here we are make use of .attr() method in Jquery to get the maxlength property of textbox at runtime and then checks if the textbox character count crosses the length. Based on this we will move the focus to next textbox.

Sample Code

 <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
         <script>
             // A $( document ).ready() block.
             $(document).ready(function () {
                 //Attach key up event handler
                 $('#<%= TextBox1.ClientID %>').keyup(function () {
                     //check if user typed three characters
                     if (this.value.length == $(this).attr('maxlength')) {
                         //move the focus to another textbox
                         $('#<%= TextBox2.ClientID %>').focus();
                     }
                 });
                 $('#<%= TextBox2.ClientID %>').keyup(function () {
                    if (this.value.length == $(this).attr('maxlength')) {
                         $('#<%= TextBox3.ClientID %>').focus();
                     }
                 });
             });
         </script>
 
         <asp:TextBox runat="server" ID="TextBox1" MaxLength="3" Width="50"></asp:TextBox>
         <asp:TextBox runat="server" ID="TextBox2" MaxLength="2" Width="50"></asp:TextBox>
         <asp:TextBox runat="server" ID="TextBox3" MaxLength="2" Width="50"></asp:TextBox>
 

Demo

, , , ,

1 Comment

how to create Cascading Dropdown list in Asp.Net

Introduction

In this article I am going to explain how to create Cascading Dropdown list in Asp.net from database. The Cascading Dropdown list loads data based on the value selected in parent dropdown list.

For ex: if you have Dropdownlist1 and Dropdownlist2 then Dropdownlist2 will be populated based on the value selected in Dropdownlist1.

Complete Code:

To load data based on the value selected in dropdown list, we will be using the SelectedIndexChanged event in dropdown list and then load the data in dropdown list.

HTML:

In Dropdownlist1 we will be using selectedindexchanged event to fill the dropdownlist2.

asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
                        AutoPostBack="true">
                    </asp:DropDownList>
                    

                    <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
                </ContentTemplate>
            </asp:UpdatePanel>

C#:

First dropdownlist we will populate as we normally populate the dropdownlist from database like given below

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Load the first dropdownlist
                LoadDropDown();
            }
        }
        //This method is used to load the first dropdownlist
        public void LoadDropDown()
        {
            //Get your connection string
            string connstring = ConfigurationManager.ConnectionStrings["Adventure WorksConnectionString"].ToString();
            //Create connection here
            using (SqlConnection conn = new SqlConnection(connstring))
            {
                //Sample Query here; You need to update the query as per your need
                string sqlquery = "SELECT TOP 100 a.city as City FROM Person.Address a";
                //Create SQLCommand object
                using (SqlCommand cmd = new SqlCommand(sqlquery, conn))
                {
                    //Open the SQLConnection
                    conn.Open();
                    //Execute the query
                    SqlDataReader rdr = cmd.ExecuteReader();

                    //Assign the values to dropdownlist
                    DropDownList1.DataSource = rdr;
                    //Set the DataValueField of dropdownlist
                    DropDownList1.DataValueField = "City";
                    //Set the DataTextField of dropdownlist
                    DropDownList1.DataTextField = "City";
                    //Bind the dropdownlist
                    DropDownList1.DataBind();
                }
            }
        }

Populating the second Dropdown list:

Here basically we will get the dropdown list values from database based on the value selected in dropdownlist like given below

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Get your connection string
            string connstring = ConfigurationManager.ConnectionStrings["Adventure WorksConnectionString"].ToString();
            //Create connection here
            using (SqlConnection conn = new SqlConnection(connstring))
            {
                //Sample Query here; You need to update the query as per your need
                string sqlquery = "SELECT TOP 100 a.AddressLine1 as AddressLine FROM Person.Address a where a.City =@City";
                //Create SQLCommand object
                using (SqlCommand cmd = new SqlCommand(sqlquery, conn))
                {
                    //Open the SQLConnection
                    conn.Open();

                    //Pass the value selected in previous dropdownlist as parameter to this query
                    cmd.Parameters.AddWithValue("@City", DropDownList1.SelectedItem.Text);
                    //Execute the query
                    SqlDataReader rdr = cmd.ExecuteReader();

                    //Assign the values to dropdownlist
                    DropDownList2.DataSource = rdr;
                    //Set the DataValueField of dropdownlist
                    DropDownList2.DataValueField = "AddressLine";
                    //Set the DataTextField of dropdownlist
                    DropDownList2.DataTextField = "AddressLine";
                    //Bind the dropdownlist
                    DropDownList2.DataBind();
                }
            }
        }

Demo

, , , , ,

1 Comment

How to load Dropdownlist from database in MVC or Populate Dropdownlist in MVC from database

Introduction:

In this article I am going to explain an easy way to populate dropdownlist in MVC.  There are lots of other options to populate dropdownlist in MVC, However here I am going to explain two options which I have come across.

Solution:

Model:

First you need to create a class in the Model. In this example I have used the DatabaseFirst approach.

You can use the below steps to generate the class files

  • Right click on the Model folder
  • Select Add option
  • And then select the New Item option
  • Select the Net Entity Data Model option and Provide a name for it
  • In the Entity Data Model Wizard, selectEF Designer from database and click on Next

If you already have connection string configured then you can select that from the available list.

If you don’t have the connection string configured then use the New Connection option and create the connection

  • Expand the Table option and then select the tables which you want
  • Click on Finish
  • You will have necessary class files generated in your solution now

Untitled

You can get more details about how to use DatabaseFirst approach from this link.

Controller:

Once the needed model files are generated now we need to create the code to get the data from database and then pass it to view for dropdownlist.

You can use the below code to get the value from database and pass it to ViewBag

 public ViewResult Index()
         {
             //Create db context object here 
             AdventureWorksDbContext dbContext = new AdventureWorksDbContext();
             //Get the value from database and then set it to ViewBag to pass it View
             IEnumerable<SelectListItem> items = dbContext.Employees.Select(c => new SelectListItem
                   {
                       Value = c.JobTitle,
                       Text = c.JobTitle
 
                   });
             ViewBag.JobTitle = items;
             return View();
         }
 

View:

Now you need to assign the values in ViewBag to dropdownlist like given below

@Html.DropDownList("JobTitle", "Select a Value")

You will have the dropdownlist populated with data now

, , , , ,

6 Comments

LensZoom in elevateZoom – Jquery Zoom in Plugin for ASP.Net

Introduction:

This is a continuation to the article which I published on the elevateXoom Plugin. In this article I am going to explain one major feature of elevateZoom plugin called LensZoom.

elevateZoom Plugin :

elevateXoom is a Jquery plugin which will xoom the image in a detail preview on mouse hover. In this example I will show to how to implement eleavteZoom plugin in Asp.Net.

Prerequisite’s:

You need to add the necessary JQuery files to your page prior to use this plugin. In this example I have used the online JQuery CDN files available. If you don’t want to use the online available cdn file then you can manually add the jquery files to your solution. I have explained the steps here in detail.

Implementation Details:

First add the JQuery reference and elevateXoom js file in your page

  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script src="Script/jquery.elevateZoom-3.0.8.min.js" type="text/javascript"></script>

Then add the required images in your page which needs to display in details preview on mouse hover.

You need to ensure that you have set two attributes to your image tag to make the elevateXoom plugin to work they are

  • “src” which holds the initial image which will get displayed
  • “data-zoom-image” which holds the expanded image which get displayed when previewed
 <img id="img1" src="http://i.imgur.com/6xIjDIB.jpg" data-zoom-image="http://i.imgur.com/HZtdHKc.jpg" />

To enable the LensZoom feature in elevateXoom plugin you need to set the zoomType to Lens. You can also set properties like lensShape and LensSize to make the feature more effective.

<script>
        // A $( document ).ready() block.
        $(document).ready(function () {
            //Attach the elevateZoom image to image
            $("#img1").elevateZoom({
                zoomType: "lens",
                lensShape: "round",
                lensSize: 100
            });
        });
    </script>

Complete Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="Script/jquery.elevateZoom-3.0.8.min.js" type="text/javascript"></script>
    <script>
        // A $( document ).ready() block.
        $(document).ready(function () {
            //Attach the elevateZoom image to image
            $("#img1").elevateZoom({
                zoomType: "lens",
                lensShape: "round",
                lensSize: 100
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <img id="img1" src="http://i.imgur.com/6xIjDIB.jpg" data-zoom-image="http://i.imgur.com/HZtdHKc.jpg" />
    </form>
</body>
</html>

Demo

, , , , , ,

Leave a comment

elevateZoom – Jquery Zoomin Plugin

Introduction:

Recently I have come across an excellent Jquery Zoom in plugin. In this article I am going to explain details about the same – elevateZoom Plugin.

elevateZoom Plugin :

elevateXoom is a Jquery plugin which will xoom the image in a detail preview on mouse hover. In this example I will show to how to implement eleavteZoom plugin in Asp.Net

Prerequisite’s:

You need to add the necessary JQuery files to your page prior to use this plugin. In this example I have used the online JQuery CDN files available. If you don’t want to use the online available cdn file then you can manually add the jquery files to your solution. I have explained the steps here in detail.

Implementation Details:

First add the JQuery reference and elevateXoom js file in your page

  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script src="Script/jquery.elevateZoom-3.0.8.min.js" type="text/javascript"></script>

Then add the required images in your page which needs to display in details preview on mouse hover.

You need to ensure that you have set two attributes to your image tag to make the elevateXoom plugin to work they are

  • “src” which holds the initial image which will get displayed
  • “data-zoom-image” which holds the expanded image which get displayed when previewed.
<img id="zoom_01" src="http://i.imgur.com/6xIjDIB.jpg" data-zoom-image="http://i.imgur.com/HZtdHKc.jpg" />

Complete Code

 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
     <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
     <script src="Script/jquery.elevateZoom-3.0.8.min.js" type="text/javascript"></script>
     <script>
         // A $( document ).ready() block.
         $(document).ready(function () {
             //Attach the elevateZoom image to image
             $("#zoom_01").elevateZoom();
         });
     </script>
 </head>
 <body>
     <form id="form1" runat="server">
         <div>
             <img id="zoom_01" src="http://i.imgur.com/6xIjDIB.jpg" data-zoom-image="http://i.imgur.com/HZtdHKc.jpg" />
         </div>
     </form>
 </body>
 </html>
 

I have explained only the basic implementation of elevatedZoom plugin, however this plugin have lots of other features , you will get more details from this link

Demo

, , , , ,

Leave a comment