DataGrid, GridView, DataList and Repeater Control in ASP.net

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 5 Comments on DataGrid, GridView, DataList and Repeater Control in ASP.net

DataGrid, GridView, DataList and Repeater Control in ASP.net

In Previous articles, i have written article about DataGrid.

http://JitendraZaa.com/blog/microsoft/net/datagrid-example-part-1/

http://JitendraZaa.com/blog/microsoft/net/datagrid-example-sorting-%E2%80%93-part-2/

http://JitendraZaa.com/blog/microsoft/net/asp-net-datagrid-basic-questions/

DataGrid, GridView and DataList controls are derived from the WebControl class, while the Repeater control is derived from the Control class. The WebControl class contains a number of properties, such as BackColor, ForeColor, CssClass, BorderStyle and so on.
In ASP .NET basically there are four kinds of the Data Presentation Controls.

  • GridView (more options)
  • DataGrid
  • DataList
  • Repeater (less options)

List of different abilities of Repeater Control, Datalist Control and GridView Control features.

Continue reading “DataGrid, GridView, DataList and Repeater Control in ASP.net”

Row expand collapse using jquery and Ajax

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , , , , , with 3 Comments on Row expand collapse using jquery and Ajax

Using JQuery and Ajax to expand and collapse the row in ASP.NET

This article describes how to expand and collapse rows of a GridView or Table and showing data details using Jquery and Ajax

Introduction:

Now day’s , important issue with web applications is how quick a wed page is rendered  and how it is animated or  visualized

So for quick reply from server Ajax is the solutions and for some visualizations with server side response we mostly use jquery or javascript.
I this article, for exp

anding , collapsing and  adding details to gridview row we are going to use AJAX to make call to server and we will visualized it using jquery.

Aim

1. Getting details of product  by extracting details at the next to current row and before second    one.

2. Visualizing  the expanding of rows.

3. No server side postback.

4. Using GridView Control to bind data and simple data binding to table using scriptlet.

Using  Jquery Code

Expanding Row :

For expanding any row, we need to create an new row  with the serverside details  and then we will add it to the next of current row

Ajax JQuery Row Expand Collapse

var trindex=0;	//trindex hold row index created by jquery
$("tr").click(function() {
if ($(this).find("td:first").length > 0) { //check whether it is header or content row
//row index increment to assign new row id everytime
trindex++;
//create a row with td colspan 3 to show product description
var row= '><td class="currRow" colspan="3" ><
div id="did"><img id="imagepath" src=""
style="height: 81px; width: 104px" />  Description :<
span id="des">sd</span><p>Cost :<
span id="cost">sd</span></p></div></td></tr>';

//adding animation to row
var newRow = $("<tr id=tr"+ trindex + row).animate({
height: "140px",
opacity: 0.25,
}, 500);
//adding row to existing table
$(this).after(newRow);
Collapsing  Row :

At the same moment we expand any row, we collapse previous created row, so we need to remember the previous created rowIndex or it’s id.

Ajax JQuery Row Expand Collapse

$("#"+rowName).find('td').removeClass('currRow').addClass('hideRow');
$("#"+rowName).animate({
    height: "0px",
    opacity: 0.25,
    }, 1000, function() {
$("#"+rowName).remove();</pre>
<h5>Ajax Call to the server :</h5>
For getting the full details about our shortly highlighted product, we need to make a asynchronous call to
server using AJAX. We are passing some key values to server(product Id) to extract the resultset.
<pre>$.ajax({
       type: "POST",
       url: "WebService.asmx/GetDetails",   //webserviceName/methodName
       data: "{'name': '" + $(this).find("td span").text() + "'}",  //passing values to webservice(productid)
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function(msg) {
       //extrating response data to newly created row
       $("#tr"+trindex ).find("td #did p #cost").text(msg.d.id );
       $("#tr"+trindex ).find("td #did  #des").text(msg.d.order);
       $("#tr"+trindex ).find("td #did #imagepath").attr('src', msg.d.order);
//$("#myImage").attr("src", "path/to/newImage.jpg");
       },
       error: FailedMessage     //showing error message if failure
       });
Using The WebService.cs

Programmable application logic accessible via standard Web protocols.We are using webservice to extract data from database using jquery Ajax call.  CollectData class to hold extracted details from db.

public class CollectData
{
        public string cost { get; set; }
        public string imagePath { get; set; }
        public string description { get; set; }
}

Simple queries to the database via WebMethod

[WebMethod()]
    public CollectData GetDetails(string name)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].
        ConnectionString);
        SqlCommand cmd = new SqlCommand("Select cost, imagePath, description from Products where ProductId='" +
        name + "'",con);
        SqlDataReader data;
        CollectData c = new CollectData();
        try
        {
            con.Open();
            data=cmd.ExecuteReader();
            if (data.Read())
            {
                c.cost= data[0].ToString();
                c.imagePath = data[1].ToString();
                c.description = data[2].ToString();
                return c;
            }
            else
            {
                c.cost = "N/A";
                c.imagePath = "N/A";
                c.description = "N/A";
                return c;
            }
        }
        catch (Exception ex)
        {
            c.cost = "N/A";
            c.imagePath = "N/A";
            c.description = "N/A";
            return c;
        }

    }

Conclusion :

We have mixed up Jquery, Ajax, server Control(Gridview ) to get quick and visualized output. Result can be little bit change as per the browsers.

Uploaded on Codeproject

Download Demo Article

DataGrid Sorting and Paging Example – Part 2

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with Leave a comment on DataGrid Sorting and Paging Example – Part 2

For Part 1, visit This URL http://JitendraZaa.com/blog/?p=191

In this part, i will show that how to Sort the Datagrid Component of ASP.NET.

To sort Datagrid, we will need DataView and then assign Dataview as datasource to our Grid control.

We will need to change our code of Part 1.

Previously, we used DataSet as a Datasource. This time we will use DataTable and get the DataView from DataTable using below line.

DataView dv = dt.DefaultView; //Where dt id DataTable

So we have created a function, which will return the DataTable as shown below:

private DataTable GetTableFromDataBase()
{
SqlConnection con = null;
SqlDataAdapter adp = null;
DataTable dt = new DataTable();
try
{
con = new SqlConnection(conString);
con.Open();
adp = new SqlDataAdapter("Select * from Employee",con);
adp.Fill(dt);
return dt;
}
catch (CustomException ex)
{
ex.logException();
}finally{
con.Close();
}
return null;
}

we will need to create the function on Sortcommand of the DataGrid.

The format for sorting the grid is like:

SortExpression+”asc”

OR

SortExpression+”desc”

Below is the code snap used for the sorting:

protected void grdEmp_Sort(object source, DataGridSortCommandEventArgs e)
{
DataTable dt = GetTableFromDataBase();
DataView dv = dt.DefaultView;
string dir = string.Empty;
if (e.SortExpression.Length > 0)
{
if (Session["OldSortDir"] == null)
{
Session["OldSortDir"] = e.SortExpression;
}
else
{
string oldSortExp = Session["OldSortDir"].ToString();
if (oldSortExp == "asc")
{
dir = "desc";
Session["OldSortDir"] = "desc";
}
else
{
dir = "asc";
Session["OldSortDir"] = "asc";
}
}
dv.Sort = e.SortExpression+"  "+dir;
}
grdEmp.DataSource = dv;
grdEmp.DataBind();
}

The code for the Pagination is written below. Consider Page Size as 3.

protected void grdEmp_Paging(object source,DataGridPageChangedEventArgs p)
{
grdEmp.CurrentPageIndex = p.NewPageIndex;
BindTable();
}

Download Source code

DataGrid Example – Part 1

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 1 Comment on DataGrid Example – Part 1

For the basics of DataGrid please refer this post: http://JitendraZaa.com/blog/?p=188

In this example, i will explain the basics of DataGrid control like Theming, Databinding etc.

We will start our example with creating the SQL Express database of Employee which will contain the following fields : Id, FName, LName, Email.

Now create a stored procedure to insert the data into Table.

CREATE PROCEDURE dbo.AddEmployee
@FName varchar(50),
@LName varchar(50),
@Email varchar(50)
AS
INSERT INTO Employee (FName,LName,Email) values (@FName,@LName,@Email)

In ASPX page, write the code to input the Employee information.

First Name : <asp:TextBox ID="txtFName" runat="server"/><br />
Last Name :<asp:TextBox ID="txtLName" runat="server"/><br />
Email :<asp:TextBox ID="txtEmail"; runat="server"/><br />
<asp:Button ID="btnSubmit" Text="Add Record" runat="server" OnClick="btnSubmit_Click"/>

Go to the property of Employee.mdf and select connection string as shown in below image.

On the click event of the button write below function:

string conString = @"Data Source=.SQLEXPRESS;AttachDbFilename=""|DataDirectory|Employee.mdf"";Integrated Security=True;User Instance=True";
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = null;
SqlCommand cmd = null;
try {
con = new SqlConnection(conString);
     con.Open();
     cmd = new SqlCommand("AddEmployee", con);
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.AddWithValue("@FName", txtFName.Text);
     cmd.Parameters.AddWithValue("@LName", txtLName.Text);
     cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
     cmd.ExecuteNonQuery();
     showConfirmationMessage();
}
catch (CustomException ex) {
ex.logException();
}finally{
    con.Close();
}
}
 private void showConfirmationMessage()
{
      ClientScriptManager csMngr = Page.ClientScript;
      csMngr.RegisterStartupScript(Page.GetType(), "Success", "alert('Record Added succesfully');", true);
}

ASPX Code for data grid

<asp:DataGrid ID="grdEmp" runat="server">
<HeaderStyle CssClass="Header" />
<AlternatingItemStyle CssClass="AlternateItemStyle" />
</asp:DataGrid>

Write below code to bind the data into DataGrid.

private void bindData()
{
SqlConnection con = null;
SqlDataAdapter adp = null;
try
{
con = new SqlConnection(conString);
con.Open();
adp = new SqlDataAdapter("Select * from Employee",con);
DataSet ds = new DataSet();
adp.Fill(ds);
grdEmp.DataSource = ds;
grdEmp.DataBind();
}
catch (CustomException ex)
{
ex.logException();
}finally{
con.Close();
}
}

Final output:

Download Code

ASP.NET DataGrid basic questions

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 2 Comments on ASP.NET DataGrid basic questions
  1. What is datagrid? The DataGrid Web server control is a powerful tool for displaying information from a data source. It is easy to use; you can display editable data in a professional-looking grid by setting only a few properties. At the same time, the grid has a sophisticated object model that provides you with great flexibility in how you display the data.
  2. What’s the difference between the System.Web.UI.WebControls.DataGrid and System.Windows.Forms.DataGrid? The Web UI control does not inherently support master-detail data structures. As with other Web server controls, it does not support two-way data binding. If you want to update data, you must write code to do this yourself. You can only edit one row at a time. It does not inherently support sorting, although it raises events you can handle in order to sort the grid contents. You can bind the Web Forms DataGrid to any object that supports the IEnumerable interface. The Web Forms DataGrid control supports paging. It is easy to customize the appearance and layout of the Web Forms DataGrid control as compared to the Windows Forms one.
  3. How do you customize the column content inside the datagrid? If you want to customize the content of a column, make the column a template column. Template columns work like item templates in the DataList or Repeater control, except that you are defining the layout of a column rather than a row.
  4. How do you apply specific formatting to the data inside the cells? You cannot specify formatting for columns generated when the grid’s AutoGenerateColumns property is set to true, only for bound or template columns. To format, set the column’s DataFormatString property to a string-formatting expression suitable for the data type of the data you are formatting.
  5. How do you display an editable drop-down list? Displaying a drop-down list requires a template column in the grid. Typically, the ItemTemplate contains a control such as a data-bound Label control to show the current value of a field in the record. You then add a drop-down list to the EditItemTemplate. In Visual Studio, you can add a template column in the Property builder for the grid, and then use standard template editing to remove the default TextBox control from the EditItemTemplate and drag a DropDownList control into it instead. Alternatively, you can add the template column in HTML view. After you have created the template column with the drop-down list in it, there are two tasks. The first is to populate the list. The second is to preselect the appropriate item in the list “” for example, if a book’s genre is set to “fiction,” when the drop-down list displays, you often want “fiction” to be preselected.
  6. How do you check whether the row data has been changed? The definitive way to determine whether a row has been dirtied is to handle the changed event for the controls in a row. For example, if your grid row contains a TextBox control, you can respond to the control’s TextChanged event. Similarly, for check boxes, you can respond to a CheckedChanged event. In the handler for these events, you maintain a list of the rows to be updated. Generally, the best strategy is to track the primary keys of the affected rows. For example, you can maintain an ArrayList object that contains the primary keys of the rows to update.

You can find more questions on Datagrid at http://msdn.microsoft.com/en-us/library/Aa289519