Pages

Showing posts with label Gridview. Show all posts
Showing posts with label Gridview. Show all posts

Wednesday, August 21, 2013

Highlight gridview row on mouse over in asp net web page

In ASP.Net, programmers heavily use the gridview control for data display. Adding some effects in gridview will change the look and feel and make it more interactive for users. One such of effects is highlighting the gridview row on mouse over. With this short background let's go for the design markup of the example gridview.

<asp:GridView ID="gridSample" runat="server" OnRowCreated="gridSample_RowCreated"
        AutoGenerateColumns="false">
        <Columns>           
            <asp:BoundField HeaderText="Name" DataField="Name" />
            <asp:BoundField HeaderText="Technology" DataField="Technology" />
            <asp:BoundField HeaderText="Experience" DataField="Experience" />
        </Columns>
 </asp:GridView>

Now we have gridview, so let’s create the style for highlight the row on mouse over.

<style type="text/css">
   /*for gridview row hover, select etc*/
   .OnOut
    {
       background-color: white;
cursor:default;

    }
       
    .OnOver
     {
       background-color: #cccccc;
cursor:pointer;

     }
</style>


Now write some line of codes on gridview row created event handler of design markup. 

protected void gridSample_RowCreated(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
        e.Row.Attributes.Add("onmouseover", "this.className='OnOver'");
        e.Row.Attributes.Add("onmouseout", "this.className='OnOut'");
    }
}

In the above code, we have specified the CSS class to adapt by the gridview row on mouse over. At the same time, we need to assign another CSS class on mouse out so that the gridview will be highlighted only on mouse over and on mouse out the effect will be void.

Happy coding!!

Nested Gridview with Expand/Collapse Functionality

Here in this example, I am going to show you how to create Nested Gridview with Expand and Collapse Functionality.
 
I have used java script to add the expandable and collapsible functionality in nested gridview by displaying plus and minus image. I have used Subjects and SubjectUnits tables to populate the nested gridviews.  

Drag and drop the Gridview control from toolbox and add two template fields with in <Columns> tag one as first column and one as last column of gridview. Now add SQLDataSource  from toolbox and configure it. The HTML source will be look like as shown below-
<asp:GridView ID="grdParent" runat="server" DataKeyNames="SubId"
            AutoGenerateColumns="False" onrowdatabound="grdParent_RowDataBound"
            DataSourceID="SqlDataSource1" GridLines="None"
            Width="500px" BorderStyle="Solid" BorderWidth="1px">
            <Columns>
            <asp:TemplateField>
            <ItemTemplate>
                        <a href="javascript:collapseExpand('SubId_<%# Eval("SubId") %>');">
                            <img id="imageSubId_<%# Eval("SubId") %>" alt="Click to show/hide orders"
                                border="0" src="Images/bullet_toggle_plus.jpg" /></a>
                    </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="SubId" HeaderText="Subject Id" />
            <asp:BoundField DataField="SubCode" HeaderText="Subject Code" />
            <asp:BoundField DataField="SubName" HeaderText="Subject Name" />
            <asp:TemplateField>
            <ItemTemplate>
            <tr>
            <td colspan="100%">
            <div id="SubId_<%# Eval("SubId") %>" style="display: none; position: relative; left: 25px;">
            <asp:GridView ID="grdChild" runat="server" AutoGenerateColumns="False"DataKeyNames="UnitId" Width="90%">           
            <Columns>
            <asp:BoundField DataField="UnitName" HeaderText="Unit Name" />
            <asp:BoundField DataField="UnitDescription" HeaderText="Description" />
            <asp:BoundField DataField="UnitSessionNumber" HeaderText="No. of Session" />
            </Columns>
            </asp:GridView>
            </div>
            </td>
            </tr>
            </ItemTemplate>
            </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT * FROM [Subjects]"></asp:SqlDataSource>

Add the following JavaScript code in head section of page.

<script type="text/javascript">
   function collapseExpand(obj) {
      var gvObject = document.getElementById(obj);
      var imageID = document.getElementById('image' + obj);

if (gvObject.style.display == "none") {
                gvObject.style.display = "inline";
                imageID.src = "Images/bullet_toggle_minus.jpg";
       }
       else {
                gvObject.style.display = "none";
                imageID.src = "Images/bullet_toggle_plus.jpg";
        }
   }
</script>

Now, Write the following code on RowDataBound event of parent gridview to bind the child gridviewwith data.

protected void grdParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
  try
  {
    if(e.Row.RowType==DataControlRowType.DataRow)
    {
       string strSubId = DataBinder.Eval(e.Row.DataItem, "SubId").ToString();
       GridView grdChild = (GridView)e.Row.FindControl("grdChild");
       SqlDataSource grdChildDataSource = new SqlDataSource();
       grdChildDataSource.ConnectionString =ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
       grdChildDataSource.SelectCommand = "select * from SubUnits where SubId='" + strSubId + "'";
        grdChild.DataSource = grdChildDataSource;
         grdChild.DataBind();
     }
   }
   catch (Exception ex)
   {
   }
}

Build the application and run it to test the functionality.
Happy coding!!

Upload and Read the Excel file using C#

This example will show you how to Upload the excel file and then read the excel file data using C# and display it on Gridview.

Drag and drop the FileUpload control and Button control from toolbox. Also drag and drop theGridview  control for display the excel file data. ASPX page will look as following.


<div>
 <asp:FileUpload ID="fileupload" runat="server" />
  <asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click"
    Text="Upload" />
 <asp:GridView ID="grdExcelData" runat="server">
 </asp:GridView>
</div>

Now write the following code on Click event of Button control.

protected void btnUpload_Click(object sender, EventArgs e)
{
  try
  {
     string connectionString = "";
     if (fileupload.HasFile)
     {
        string fileName = Path.GetFileName(fileupload.PostedFile.FileName);
        string fileExtension = Path.GetExtension(fileupload.PostedFile.FileName);
        string fileLocation = Server.MapPath("~/App_Data/" + fileName);
        fileupload.SaveAs(fileLocation);
        //Check whether file extension is xls or xslx
        if (fileExtension == ".xls")
        {
          connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation +";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
        }
        else if (fileExtension == ".xlsx")
        {
           connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation +";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
        }

        //Create OleDB Connection and OleDb Command
        OleDbConnection con = new OleDbConnection(connectionString);
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = con;
        OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
        DataTable dtExcelRecords = new DataTable();
        con.Open();
        DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
        cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
        dAdapter.SelectCommand = cmd;
        dAdapter.Fill(dtExcelRecords);
        con.Close();
        grdExcelData.DataSource = dtExcelRecords;
        grdExcelData.DataBind();
   }
 }
 catch (Exception ex)
 {
 }
}


Build and run the application.

Friday, August 16, 2013

Move Selected Gridview Rows to Another Gridview in Asp.net

To implement this first we need to write the code in aspx page like this 

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Tranfer selected gridview rows to another gridview in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true"OnCheckedChanged="chkSelect_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<br />
<b>Second Gridview Data</b>
<asp:GridView ID="gvTranferRows" AutoGenerateColumns="false" CellPadding="5" runat="server"EmptyDataText="No Records Found">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>

Now add following namespaces in codebehind

using System;
using System.Data;
using System.Web.UI.WebControls;

After that add following code in code behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
BindSecondGrid();
}
}
protected void BindGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
DataRow dtrow = dt.NewRow();    // Create New Row
dtrow["UserId"] = 1;            //Bind Data to Columns
dtrow["UserName"] = "Nayab";
dtrow["Education"] = "MCA";
dtrow["Location"] = "Nellore";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();               // Create New Row
dtrow["UserId"] = 2;               //Bind Data to Columns
dtrow["UserName"] = "Mahesh";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Guntur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();              // Create New Row
dtrow["UserId"] = 3;              //Bind Data to Columns
dtrow["UserName"] = "Vijay";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
protected void chkSelect_CheckChanged(object sender, EventArgs e)
{
GetSelectedRows();
BindSecondGrid();
}
protected void BindSecondGrid()
{
DataTable dt = (DataTable)ViewState["GetRecords"];
gvTranferRows.DataSource = dt;
gvTranferRows.DataBind();
}
private void GetSelectedRows()
{
DataTable dt;
if (ViewState["GetRecords"] != null)
dt = (DataTable)ViewState["GetRecords"];
else
dt = CreateTable();
for (int i = 0; i < gvDetails.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvDetails.Rows[i].Cells[0].FindControl("chkSelect");
if (chk.Checked)
{
dt = AddGridRow(gvDetails.Rows[i], dt);
}
else
{
dt = RemoveRow(gvDetails.Rows[i], dt);
}
}
ViewState["GetRecords"] = dt;
}
private DataTable CreateTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId");
dt.Columns.Add("UserName");
dt.Columns.Add("Education");
dt.Columns.Add("Location");
dt.AcceptChanges();
return dt;
}
private DataTable AddGridRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("UserId = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
int rowscount = dt.Rows.Count - 1;
dt.Rows[rowscount]["UserId"] = gvRow.Cells[1].Text;
dt.Rows[rowscount]["UserName"] = gvRow.Cells[2].Text;
dt.Rows[rowscount]["Education"] = gvRow.Cells[3].Text;
dt.Rows[rowscount]["Location"] = gvRow.Cells[4].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("UserId = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}