Browsing all articles in ASP.NET
Apr
6

Code Snippet : Exporting DataSet to Excel file in asp.net

Here is the code to export DataSet to Excel file.
Process:
Prepare a GridView or DataGrid from code behind file with the DataSet
and use the following code to export as a Excel(.xls) file.

private void Export(DataSet ds)
{
System.Web.UI.WebControls.DataGrid dg;
try
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=ExportFile.xls");
EnableViewState = true;
foreach (DataTable item in ds.Tables)
{
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
dg = new System.Web.UI.WebControls.DataGrid();
dg.ShowHeader = true;
dg.HeaderStyle.BackColor = System.Drawing.Color.Gray;
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.ForeColor = System.Drawing.Color.White;
dg.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
dg.HeaderStyle.Height = new Unit(30);
dg.HeaderStyle.VerticalAlign = VerticalAlign.Middle;
dg.ForeColor = System.Drawing.Color.Black;
dg.DataSource = item;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(item.TableName);
Response.Write(stringWrite.ToString());
}
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
}
}
Mar
8

Complete Lifecycle of an ASP.Net page and controls

Many people have blogged about the lifecycle of an ASP.Net Page or Master Page but every time I need to find the complete lifecycle of a control it’s not so easy. Today I wrote a couple of test pages to generate a reference.
The pages are very simple, I just overrode every method I could find and wrote to the trace. For completeness when the method called its base I wrapped it with “Start MethodName” and “End MethodName” (if you look at the trace outputs below you will see why). I did this for the Master Page (.master), Page (.aspx), User Control (.ascx) and Web Control (.cs), the page structre was simple:

Master Page
Page
User Control
Web Control

read more

Aug
5

How to Add a GridView Column of Radio Buttons

In ASPX File add the following lines of code…

<form id="form1" runat="server">
<div>
<asp:Button ID="btnLoad" runat="server" Text="Load Users" onclick="btnLoad_Click" />
<asp:GridView ID="gvUsers" runat="server" OnRowCreated="gvUsers_RowCreated">
<Columns>
<asp:TemplateField HeaderText="Method1">
<ItemTemplate>
<asp:Literal id="RadioButtonMarkup" runat="server"></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Method2">
<ItemTemplate>
<input name="MyRadioButton" type="radio" value='<%# Eval("Name") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:Button ID="bSubmit" runat="server" Text="Submit" onclick="bSubmit_Click" />
<br />
<asp:Label ID="lmsg" runat="server"></asp:Label>
</form>

In code behind file add the following code…

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnLoad_Click(object sender, EventArgs e)
{
using (ProjectDBDataContext db = new ProjectDBDataContext())
{
var roles = from r in db.MUserInfos select r;
gvUsers.DataSource = roles;
gvUsers.DataBind();
}
}
private int UsersSelectedIndex
{
get
{
if (string.IsNullOrEmpty(Request.Form["UsersGroup"]))
return -1;
else
return Convert.ToInt32(Request.Form["UsersGroup"]);
}
}
protected void gvUsers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Grab a reference to the Literal control
Literal output = (Literal)e.Row.FindControl("RadioButtonMarkup");
// Output the markup except for the "checked" attribute
output.Text = string.Format( "<input type=\"radio\" name=\"UsersGroup\" " + "id=\"RowSelector{0}\" value=\"{0}\"", e.Row.RowIndex);
// See if we need to add the "checked" attribute
if (UsersSelectedIndex == e.Row.RowIndex)
output.Text += " checked=\"checked\"";
// Add the closing tag
output.Text += " />";
}
}
protected void bSubmit_Click(object sender, EventArgs e)
{
int x = UsersSelectedIndex;
lmsg.Text = "method1: " +x.ToString() + "</br>";
string selectedValue = Request.Form["MyRadioButton"];
lmsg.Text += "method2: "  + selectedValue;
}
}

Aug
4

How to upload a file to ftp server with FileUpload control

private bool UploadToFTP(string ftpfilepath,HttpPostedFile fileToUpload)
{
try
{
string ftphost = "ftpaddress";
string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
Stream streamObj = fileToUpload.InputStream;
Byte[] buffer = new Byte[fileToUpload.ContentLength];
streamObj.Read(buffer, 0, buffer.Length);
streamObj.Close();
streamObj = null;
FtpWebRequest requestObj = FtpWebRequest.Create(ftpfullpath) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
requestObj.Credentials = new NetworkCredential("username", "password");
Stream requestStream = requestObj.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Flush();
requestStream.Close();
requestObj = null;
return true;
}
catch
{
return false;
}
}
Feb
23

To create directory on application server with ASP.NET server side code

Here is the code to creating the directory at application with ASP.NET

using System;
using System.Data;
using System.Configuration;
// We  need this namespace to create directory
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void  Page_Load(object sender, EventArgs e)
{
string NewDir = Server.MapPath("New  Folder");
// Call function for creating a directory
MakeDirectoryIfExists(NewDir);
}
private void  MakeDirectoryIfExists(string NewDirectory)
{
try
{
// Check if directory exists
if (!Directory.Exists(NewDirectory))
{
// Create the directory.
Directory.CreateDirectory(NewDirectory);
}
}
catch (IOException  _ex)
{
Response.Write(_ex.Message);
}
}
}
Feb
22

Gridview custom paging in asp.net 3.5 with SQL Server Sproc

GridView — Displays a set of data items in an HTML table. ASP.NET GridView control enables you to display, sort, page, select, and edit data.

Default gridview paging works best when you deal with limited pages. If there are more pages then, the performance suffers. In this case direct jump to desire page is a good alternative.

I have deal with a problem on GridView while working on user control (.ascx). I have a user control (.ascx) with GridView in it. I have used Stored Procedure to retrieve data. Bounding data to gridview display all the records and Default paging setting not work for me. Here Custom Paging helps me and only those database records that need to be displayed get retrieved. Using GridView Custom Paging solve the Issue for me.

Here, I am going to demonstrate a sample on GridView Custom Paging. I want to display records from two different tables depending on search pattern, let’s consider, I have student table contain sName, sAddress, ClassId and class table contain classId and ClassName. Now I want to display Name, Address and ClassName based on string pattern. Here I will get Ramdom Records based on search pattern. In this example we are going to use ASP.Net DropDownList along with ASP.Net GridView for Pagination to provide Jump To Page Number facility to the user.

read more

Follow us on Twitter! Follow us on Twitter!
FoxSparrow Tweets

Categories