Select a Row in A Gridview by Clicking Anywhere on it

Add a GridView, Bind values in Gridview.

C#:

protected void GridView_CustomerDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes[“onmouseover”] = “this.style.cursor=’hand';this.style.textDecoration=’underline';”;
e.Row.Attributes[“onmouseout”] = “this.style.textDecoration=’none';”;

e.Row.Attributes[“onclick”] = ClientScript.GetPostBackClientHyperlink(this.GridView_CustomerDetails, “Select$” + e.Row.RowIndex);
}

}
catch (Exception)
{

throw;
}
}

 

 

Source:

http://www.geekzilla.co.uk/view9FC28EE6-ACB0-4F51-BFE4-38B0B10134D5.htm

http://www.aspmessageboard.com/showthread.php?t=230982

Maintain Scroll Position after Asynchronous Postback

Do you want to maintain the scroll position of a GridView, Div, Panel,  or whatever that is inside of an UpdatePanel after
an asynchronous  postback?  Normally, if the updatepanel posts back, the item will scroll  back to the top because it has
been reloaded.  What you need to do is  “remember” where the item was scrolled to and jump back to there after  the postback.
Place the following script after the ScriptManager  on your page.  And since the _endRequest event of the  PageRequestManager
happens before the page is rendered, you’ll never  even see your item move!

<script type=”text/javascript”>
var xPos, yPos;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
xPos = $get(‘scrollDiv’).scrollLeft;
yPos = $get(‘scrollDiv’).scrollTop;
}
function EndRequestHandler(sender, args) {
$get(‘scrollDiv’).scrollLeft = xPos;
$get(‘scrollDiv’).scrollTop = yPos;
}
</script>

While using Master Page

$get(‘scrollDiv’)
to
$get(‘<%= scrollDiv.ClientID %>’)

Reset to TOP

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
<script type=”text/javascript”>
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(scrollToTop);

function scrollToTop()
{
window.scrollTo(0,0);
}
</script>

Source:

http://weblogs.asp.net/andrewfrederick/archive/2008/03/04/maintain-scroll-position-after-asynchronous-postback.aspx

http://basgun.wordpress.com/2008/06/09/maintain-scroll-position-updatepanel-postback/

GridView Events

GridView PageIndexChanging Event:

protected void GridView_Roles_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

try

{

GridView_ContactType.PageIndex = e.NewPageIndex;

BindGrid();

}

catch (Exception ex)

{

}

}

GridView SelectedIndexChanged Event:

protected void GridView_ContactType_SelectedIndexChanged(object sender, EventArgs e)

{

try

{

ViewState[“TypeID”] = GridView_ContactType.SelectedRow.Cells[0].Text;

txt_Type.Text = GridView_ContactType.SelectedRow.Cells[1].Text;

txt_Description.Text = GridView_ContactType.SelectedRow.Cells[2].Text;

}

catch (Exception)

{

}

}

RowEditing Event:

protected void GridView_RowEditing(object sender, GridViewEditEventArgs e)

{

lbl_ForwardStatus.Text = GridView.Rows[e.NewEditIndex].Cells[2].Text.Trim();

}

RowDeleting Event:

protected void GridView_RequestDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

lbl_Reject.Text = GridView_RequestDetails.Rows[e.RowIndex].Cells[2].Text.Trim();

}


To Hide Columns in GridView:

GridView RowCreated Event:

protected void GridView_ContactType_RowCreated(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.Header)

{

e.Row.Cells[0].CssClass=”hiddencol”;

e.Row.Cells[3].CssClass=”hiddencol”;

e.Row.Cells[4].CssClass=”hiddencol”;

}
else if(e.Row.RowType==DataControlRowType.DataRow)
{

e.Row.Cells[0].CssClass=”hiddencol”;

e.Row.Cells[3].CssClass=”hiddencol”;

e.Row.Cells[4].CssClass=”hiddencol”;

}

}

Enable/Disable Command Button on condition in GridView

RowDataBound Event:

protected void GridView_RequestDetails_RowDataBound(object sender, GridViewRowEventArgs e)

{

try

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

foreach (DataControlFieldCell cell in e.Row.Cells)

{

// check all cells in one row

foreach (Control control in cell.Controls)

{

if (e.Row.Cells[9].Text.Trim() == “Declined” || e.Row.Cells[9].Text.Trim() == “Closed”)

{

Button button = control as Button;

if (button != null && button.CommandName == “Delete”)

{

button.Enabled = false;

}

else if (button != null && button.CommandName == “Edit”)

{

button.Enabled = false;

}

}

}

}

}

}

catch (Exception)

{

throw;

}

}

Change color of  GridView Row on mouseover:

protected void GridView_RequestDetails_RowDataBound(object sender, GridViewRowEventArgs e)

{

if(e.Row.RowType == DataControlRowType.DataRow)
{
if(e.Row.RowState == DataControlRowState.Alternate)
{
e.Row.Attributes.Add(“onmouseover”, “this.style.backgroundColor=’#8803AE';this.style.color=’#FFFFFF';”);
e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=’#FFFFFF';this.style.color=’#8803AE';”);
}

else
{
e.Row.Attributes.Add(“onmouseover”, “this.style.backgroundColor=’#8803AE';this.style.color=’#FFFFFF';”);
e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=’#FFFFFF';this.style.color=’#8803AE';”);
}

}

}

Confirm Button While Deleting in GridView:

protected void GridView_ContactType_RowDataBound(object sender, GridViewRowEventArgs e)

{

try

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

// loop all data rows

foreach (DataControlFieldCell cell in e.Row.Cells)

{

// check all cells in one row

foreach (Control control in cell.Controls)

{

// Must use LinkButton here instead of ImageButton

// if you are having Links (not images) as the command button.

//ImageButton button = control as ImageButton;

Button button = control as Button;

if (button != null && button.CommandName == “Delete”)

// Add delete confirmation

button.OnClientClick = “if (!confirm(‘Are you sure you want to delete this Record?’)) return;”;

}

}

}

}

catch (Exception)

{

throw;

}

}

Export DataSet To Excel C# & VB.Net

aspx.cs

protected void btn_Excel_Click(object sender, EventArgs e)
{
try
{
if (txt_Code.Text != “” )
{
Ds = new DataSet();
Ds.Clear();

BL.EmpCode = txt_Code.Text;

Ds = DL.FillCondition(BL);
Obj.ExportToExcel(Ds, “EmployeeReport-Code:” + txt_Code.Text);
}
else
{
lbl_status.Text = “Enter Date”;
lbl_status.CssClass = “lblStatusException”;
lbl_status.Visible = true;
}
}
catch (Exception)
{
lbl_status.Text = “Error in Excel generation”;
lbl_status.CssClass = “lblStatusException”;
lbl_status.Visible = true;
}
}

.cs

public void ExportToExcel(DataSet DsExcel, String XLname)
{
try
{
DataTable dt = DsExcel.Tables[0];
//DataTable dt = DsExcel;

string attachment = “attachment; filename=” + XLname + “.xls”;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader(“content-disposition”, attachment);
HttpContext.Current.Response.ContentType = “application/vnd.ms-excel”;
string tab = “”;
foreach (DataColumn dc in dt.Columns)
{
HttpContext.Current.Response.Write(tab + dc.ColumnName);
tab = “\t”;
}
HttpContext.Current.Response.Write(“\n”);
int i;
foreach (DataRow dr in dt.Rows)
{
tab = “”;
for (i = 0; i < dt.Columns.Count; i++)
{
HttpContext.Current.Response.Write(tab + dr[i].ToString());
tab = “\t”;
}
HttpContext.Current.Response.Write(“\n”);
}
HttpContext.Current.Response.End();

}
catch (Exception)
{
throw;
}
}

Export CurrentPage of Gridview into Excel

 

protected void btn_ExcelExport_Click(object sender, EventArgs e)
{
try
{
obj.ExportToExcel(Grid_Report, “Bills_Report_” + DateTime.Now.ToString(“dd/MM/yyyy”));
Response.End();
}
catch (Exception ex)
{
lbl_Status.Visible = true;
lbl_Status.ForeColor = Color.Red;
lbl_Status.Text = “Exception occured: ” + ex.Message.ToString();
}
}

public override void VerifyRenderingInServerForm(Control control)
{

}

If the Grid is in UpdatePanel, add Trigger to the Exporting Button

<Triggers>
<asp:PostBackTrigger ControlID=”btn_ExcelExport” />
</Triggers>

public void ExportToExcel(GridView gv, string XLname)
{
try
{
//HttpContext.Current.Response.Write(fileName);

HttpContext.Current.Response.ContentType = “application/excel”;

HttpContext.Current.Response.AppendHeader(“Content-Disposition”, “attachment; filename=” + XLname + “”);

System.IO.StringWriter sw = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter hsw = new System.Web.UI.HtmlTextWriter(sw);

gv.RenderControl(hsw);

HttpContext.Current.Response.Write(sw.ToString());
}
catch (Exception)
{
throw;
}
}

===========================

FileName:  Logics.cs

/// <summary>
///
/// </summary>
/// <param name=”fileName”></param>
/// <param name=”gv”></param>
public static void ExportToExcelCurrentPage(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
“content-disposition”, string.Format(“attachment; filename={0}”, fileName));
HttpContext.Current.Response.ContentType = “application/ms-excel”;

using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
//  Create a form to contain the grid
Table table = new Table();

//  add the header row to the table
if (gv.HeaderRow != null)
{
Logics.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}

//  add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
Logics.PrepareControlForExport(row);
table.Rows.Add(row);
}

//  add the footer row to the table
if (gv.FooterRow != null)
{
Logics.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}

//  render the table into the htmlwriter
table.RenderControl(htw);

//  render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}

/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name=”control”></param>

private static void PrepareControlForExport(Control control)

{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? “True” : “False”));
}

if (current.HasControls())
{
Logics.PrepareControlForExport(current);
}
}
}

VB.net

Public Sub ExportDataSetToExcel(ByVal dt As DataTable, ByVal filename As String)
Dim response As HttpResponse = HttpContext.Current.Response
‘ first let’s clean up the response.object
response.Clear()
response.Charset = “”
‘ set the response mime type for excel
response.ContentType = “application/vnd.ms-excel”
response.AddHeader(“Content-Disposition”, “attachment;filename=””” & filename & “”””)
‘ create a string writer
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
‘ instantiate a datagrid
Dim dg As New GridView()
dg.AllowPaging = False
dg.DataSource = dt
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
response.[End]()
End Using
End Using
End Sub

Follow

Get every new post delivered to your Inbox.