Datagridview With CheckBox

September 11, 2009

/* To Create a DatagridView with checkbox */

<asp:TemplateField HeaderText=”Select”>

<HeaderTemplate>

<asp:CheckBox runat=”server” Text=”All”">All(this);” />

</HeaderTemplate>

<ItemTemplate>

<asp:CheckBoxchkSelect” runat=”server” />

</ItemTemplate>

</asp:TemplateField>

/* Javascript function  to select all check boxes */

<script language=”javascript” type=”text/javascript”>

function All(CheckBox)

{

TotalChkBx = parseInt(‘<%= this.GridView1.Rows.Count %>’);

var TargetBaseControl = document.getElementById(‘<%= this.GridView2.ClientID %>’);

var TargetChildControl = “chkSelect“;

var Inputs = TargetBaseControl.getElementsByTagName(“input”);

for(var iCount = 0; iCount < Inputs.length; ++iCount)

{

if(Inputs[iCount].type == ‘checkbox’ && Inputs[iCount].id.indexOf(TargetChildControl,0) >= 0)

Inputs[iCount].checked = CheckBox.checked;

}

}

</script>

In code Behind

/* To get which are the values are selected in checkbox */

protected void btnsub_Click(object sender, EventArgs e)

{

CheckBox cbk = new CheckBox();

GridViewRowCollection gv = GridView1.Rows;

//foreach (GridViewRowCollection gv in GridView1.Rows)

foreach (GridViewRow gr in gv)

{

cbk = (CheckBox)(gr.Cells[0].FindControl(“chkSelect”));

if (cbk.Checked == true)

{

//  Which is the value required from the Datagrid View gr.Cells[2].Text.Trim();

Response.Write(gr.Cells[2].Text);

System.Threading.Thread.Sleep(100);

}

}

}


To add Serial Number in DataGrid

August 28, 2009

<asp:templatecolumn headertext=”S.No” >
<itemtemplate>
<%# Container.ItemIndex+1 %>
</itemtemplate>
</asp:TemplateColumn>


Sending Request And Get Response with POST Method

February 3, 2009
Imports System.IO  
Imports System.Net  
Partial Class Default1  
    Inherits System.Web.UI.Page  
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load  
        Dim strURL As String = “”  
        Dim strPostData As String = “”  
        Dim strResult As String = “”  
        Dim wbrq As HttpWebRequest  
        Dim wbrs As HttpWebResponse  
        Dim sw As StreamWriter  
        Dim sr As StreamReader  
  
        ’ Set the URL to post to  
        strURL = “http://www.webcom.com/cgi-bin/form”  
        ’ Post some values to the page  
        strPostData = String.Format(“your_name={0}&userid={1}&form_name={2}”, “Mark Smith”, “webcom”, “tutortest”)  
  
        ’ Create the web request  
        wbrq = WebRequest.Create(strURL)  
        wbrq.Method = “POST”  
        ’ We don’t always need to set the Referer but in this case   
        ’ the page we are posting to will only issue a response if we do  
        wbrq.Referer = “http://www.webcom.com/cgi-bin/form”  
        wbrq.ContentLength = strPostData.Length  
        wbrq.ContentType = “application/x-www-form-urlencoded”  
  
        ’ Post the data  
        sw = New StreamWriter(wbrq.GetRequestStream)  
        sw.Write(strPostData)  
        sw.Close()  
  
        ’ Read the returned data   
        wbrs = wbrq.GetResponse  
        sr = New StreamReader(wbrs.GetResponseStream)  
        strResult = sr.ReadToEnd.Trim  
        sr.Close()  
  
        ’ Write the returned data out to the page  
        TextBox1.Text = strResult  
    End Sub  
End Class  

To Fix Grid Header in Asp.net

March 31, 2008

.frozenTop { top:expression(this.offsetParent.scrollTop-2);position:relative;z-index:30; }

write this style in style sheet and for Grid header style class assign this frozenTop.


How to convert given decimal value to Degrees?

March 31, 2008

protected string convertToDegrees(decimal decValue)
{
//Method to convert to Decimal values to Degrees.
int Degree = 0, Mins = 0, Secs = 0;
decimal dec_Mins = 0.0M, dec_Secs = 0.0M;
string output = null;

Degree = (int)decValue;
dec_Mins = Math.Abs(decValue – Degree) * 60;
Mins = (int)dec_Mins;
dec_Secs = Math.Abs(dec_Mins – Mins) * 60;
dec_Secs = Math.Round(dec_Secs);
Secs = (int)dec_Secs;

//output = “<td>”+Degree+”</td><td>”+Mins+”</td><td>”+Secs+”</td>”;
output = Degree + “° &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;” + Mins + “‘ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;” + Secs + “\”";
return output;
/* The Logic Used is given below
# The whole units of degrees will remain the same (i.e. in 121.135° longitude, start with 121°).
# Multiply the decimal by 60 (i.e. .135 * 60 = 8.1).
# The whole number becomes the minutes (8′).
# Take the remaining decimal and multiply by 60. (i.e. .1 * 60 = 6).
# The resulting number becomes the seconds (6″). Seconds can remain as a decimal.
# Take your three sets of numbers and put them together, using the symbols for degrees (°), minutes (‘), and seconds (“) (i.e. 121°8′6″ longitude)
*/
}


How to Generate Excel File From Grid?

March 31, 2008

protected void BtnDownload_Click()

{

string filename = “[Dowload_Filename]“;  // Give the file name with which it has to download

Response.AddHeader(“content-disposition”,
string.Format(“attachment;filename={0}.xls”, filename);
Response.Charset = “”;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = “application/vnd.ms-excel”;

StringWriter stringWrite = new StringWriter();
//StreamWriter stringWrite = new StreamWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

[GridId].RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());

}

//This method must be included for download a file.

public override void VerifyRenderingInServerForm(Control control)
{

}


How to write functionality for a hyperlink bind in GridView?

March 31, 2008

//in columns of GridView any one is of type Hyperlink assume that in one Column
// When you click on that hyperlink a new window has to open to edit details of
// GridView row
protected void Button1_Click(object sender, EventArgs e)
{
[GridId].DataSource = [Datasource];
[GridId].DataBind();
}

int sno;
protected void [GridId]_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

e.Row.Cells[1].Text = Convert.ToString(++sno); // To Dispaly Serial number in first column

//script is the java script function called after clicking link button in Grid View.
//you can pass parameters to that java script function

script = “javascript:return OpenViewWindow(” + [column value]+ “,” + [column value] + “)”;
// Write OpenViewWindow function in .aspx page script as per requirement

// [HyerLink Control Name] is the name given to control when adding hyperlink control to columns of GridView
((LinkButton)e.Row.Cells[2].FindControl(“[HyerLink Control Name]“)).OnClientClick = script;
}
}
}


How to Download a File in asp.net?

March 31, 2008

in c#.net

string path = Server.MapPath(“~”).ToString() + @”[Filename]“;

if (File.Exists(path))
{
Response.AppendHeader(“content-disposition”,”attachment; filename=[FileName]“);
Response.ContentType = “application/x-msdownload”;
Response.TransmitFile(path);
}
else
{
string nofile = “<script language=javascript>alert(‘File Not available’);</script>”;
Page.RegisterStartupScript(“nofile”, nofile);
}


How to read Excel File in asp.net ?

March 31, 2008

//docpath is locaiton of Excel File from which we have to read Data

string con = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + docpath + “;”;
con = con + @”Extended Properties=”"Excel 8.0;IMEX=1″”";
OleDbConnection oc = new OleDbConnection(con);
oc.Open();
OleDbCommand com = new OleDbCommand(“select * from [Sheet1$]“, oc);

//Sheet1 is the name of sheet in excel file from which you want to read data

OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = com;
DataSet ds = new DataSet();
da.Fill(ds);
After this the data in excel will be stored in dataset ds. assign ds to any DataSource.