Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

Monday, March 28, 2011

Export Gridview to PDF

we have seen how to export the data from gridview to Excel file, today this post will helps you to export the gridview data to PDF, if you want protect you data being edit/ cut/ delete then Export to PDF will be a better option for you.there is a open source project for iTextShart. you can download the dll from them and you can use it.

only you need to add this content on your page

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
Response.End();


Even you can format the text also,if you want to set the page with A4 or any other even you can also do the same.you can also specify the font size, style color all the basic things you can do with it.

you can download the code from the below link. you can try that it will helps you.

download Source

Friday, December 4, 2009

Format DateTime in Gridview.

Gridview is using mostly , now i have come up with some small but very important task on how to display Proper date time on Gridview , Basically we are defining standard date time option (date + time) , but some time we only want to display date in this case you can follow the below format.Format Date on Bound Column in Grid View

Suppose you want DOB in short date format without time , then you can simply use DataFormatString ="{0:d}" for Short Date
like this

<asp:BoundField DataField="DOB" HeaderText="DOB" DataFormatString = "{0:d}" />


if you are using above this setting then also it will not work ,coz by default the html encode is turned ON to prevent the Cross site Scripting attack , so for that you need to add one more property as HtmlEncode ="false".


<asp:BoundField DataField="DOB" HtmlEnclode="False" HeaderText="DOB" DataFormatString = "{0:d}" />

if You want Logn Date you can use - DataFormatString = "{0:D}"
if You want Logn Time you can use - DataFormatString = "{0:T}"

If you are using Template comlumn and you want to make your date string in short format then also you can use this suppose your item templates is

<ItemTemplate >
<asp:Label ID="DOB" runat="server" Text='<%# Bind("DOB") % >'> </asp:Label >
</ItemTemplate >


Then also you can use like this way:

<asp:Label ID="DOB" runat="server" Text='<%# Bind("DOB","{0:D}") % >'> </asp:Label >


Following table will show some date formating ways in Gridview column.



Format Pattern

Name

Example

d


Short date

11/8/2008

D

Long date

Sunday, August 11, 2008


t

Short time

3:32 PM

T

Long time

3:32:00 PM

f

Full date/time
(short time)

Sunday, August 11, 2008 3:32 PM

F

Full date/time
(long time)

Sunday, August 11, 2008 3:32:00 PM

g

General date/time
(short time)

8/11/2008 3:32 PM

G

General date/time
(long time)

8/11/2008 3:32:00 PM

m or M

Month day

August 11

r or R

RFC 1123


Sun, 11 Aug 2008 8:32:00 GMT

s

Sortable date/time

2008-08-11T15:32:00

u


Universable sortable date/time

2008-08-11 15:32:00z

U

Universable sortable date/time

Sunday, August 11, 2008 11:32:00 PM


y or Y

Year month

August, 2008


thanx you,

Wednesday, September 2, 2009

Highlight Gridview's Row on mouseHover

in Gridview we have seen most of the time we one we take move hover to any row , size of that row or background color or any animation get happen you can do that using css, or java script also.

here i have do that using java script

function gvHigh(tRow,showAct)
{
if (showAct)
{
tRow.style.backgroundColor = '#ff32ss';
}
else
{
tRow.style.backgroundColor = '#ffffff';
}
}

function urlloca(Url)
{
document.location.href = Url;
}



and Define onrowCreated function like this and put your code behind here


protected void gv1_onRowCreated(object sender, EventArgs e)
{
foreach (GridViewRow gvRow in gv1.Rows)
{
gvRow.Attributes["onmouseover"] = "highlight(this, true);";
gvRow.Attributes["onmouseout"] = "highlight(this, false);";
HttpResponse myHttpResponse = Response;
HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
gvRow.Attributes.AddAttributes(myHtmlTextWriter);
}

}



that's it it will help you.
thank you.

Wednesday, July 29, 2009

Move Seleted Records using Checkbox in GridView

Hi ,

here is nice tutorial or you can say very simple example on how you can
delete or move the records from the Gridview

Move/Delete content From GridView

hope u like it ,

Wednesday, July 22, 2009

Eliminate Duplicate records from the Grid View

Most of the time we need to delete duplicate entries from GridView, in this case we can delete it manually also or using onRowcreate also we can remove that .

Example
suppose Mr.Xyz has has more than 2 Account in Blogspot.com site and we want to show
in GridView Person and RelatedBlogs like this





and in this case we dont want to repeat Person name on each row.
- I have a data source

DataTable dtsource = new DataTable();

//Adding columns to datatable
dtsource.Columns.Add("Person");
dtsource.Columns.Add("Related Blog");

//Adding records to the datatable
dtsource.Rows.Add("kiran", "kirank.blog.com");
dtsource.Rows.Add("kiran", "webdevlopmenthelp");
dtsource.Rows.Add("kiran", "www.kiran.com");
dtsource.Rows.Add("mark", "mark.blog.com");
dtsource.Rows.Add("mark", "asp-net.blogspot.com");


put the below code in codebehind


private void GenerateUniqueData(int cellno)
{
//Logic for unique names

//Step 1:

string initialnamevalue = grdUniqueNames.Rows[0].Cells[cellno].Text;

//Step 2:

for (int i = 1; i < grdUniqueNames.Rows.Count; i++)
{

if (grdUniqueNames.Rows[i].Cells[cellno].Text == initialnamevalue)
grdUniqueNames.Rows[i].Cells[cellno].Text = string.Empty;
else
initialnamevalue = grdUniqueNames.Rows[i].Cells[cellno].Text;
}
}



on GridView define property OnRowCreated="GenerateUniqueData" it will search the record via cell and set the Person name as a empty or person name

Monday, July 20, 2009

open new window in GridView using OnRowCreated

In GridView using "OnRowCreated" function we can add onClick function.

here is the sample code

html code


<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Click Me"></asp:Label>
</ItemTemplate>
</asp:TemplateField>


and CodeBehind is


protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l = (Label)e.Row.FindControl("Label1");
if (l != null)
{
string script = "window.open('Default.aspx');";
l.Attributes.Add("onclick", script);
}
}
}


run the Application and click "Click Me" it will open new window , indirectly we are adding
OnClick Event in That Row.

Tuesday, July 14, 2009

Pass multiple parameter using HyperLink field in GridView

While using Hyperlink field u can send multiple parameter in Gridview , and then u can retrive it using QueryString Parameter.

here in this Example when user will click on username then it will redirect to
http://xyz.com/ShowUser.aspx?id={0}&city={1} this page
and it will pass customer id and city .






<asp:SqlDataSource id="datasource1" runat="server" SelectCommand="SELECT CustomerID, CompanyName, City FROM Customers"
/>

<asp:GridView id="gridview1" DataSourceID="datasource1" runat="server"
AutoGenerateColumns="False">
<Columns>

<asp:BoundField DataField="CustomerID" HeaderText="BoundField" />

<asp:HyperLinkField
DataTextField="CustomerName"
DataNavigateUrlFields="CustomerID,City"
DataNavigateUrlFormatString=
"http://xyz.com/ShowUser.aspx?id={0}&city={1}" />

</Columns>
</asp:GridView>

Wednesday, July 8, 2009

Export Gridview to xls

Now you can Export content from GridView to Excel file

1. Create one Button "Export"

<asp:Button id="Export" Text="Export" onClick="Export_Click"> </asp:Button>

2. Add this on Export Event

protected void Export_Click(object sender, EventArgs e)
{
Response.AddHeader("content-disposition", "attachment;filename=ExportData.xls");
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter SWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmWr = new HtmlTextWriter(SWrite);
GridView1.RenderControl(htmWr);
Response.Write(SWrite.ToString());
Response.End();
}


that's it

Tuesday, July 7, 2009

Limiting Data from GridView

while Desinging GridView we want some special effets like (coloring , bold, Setting width , height )
and so many , you can do this by handling event like RowCreated and implementing event handler for it OnRowCreated.


<asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" />


And in your code behind you can add


protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Comments = (String)DataBinder.Eval(e.Row.DataItem, "Comment");
if (Comments != null)
{
if (Comments.Length > 30)
{
Comments = Comments.Substring(0, 40) + "...";
e.Row.ForeColor = System.Drawing.Color.red;

}
}
}
}


in that on "Comment" filed , i just simply minimize the string uptp 40 character and make it as a "RED" color.
like that you can add more feature as u want.

Monday, July 6, 2009

Using Parameters with the SqlDataSource Control

When using the SqlDataSource control, you can specify SQL queries and statements that use parameters. This helps make your data-binding scenarios more flexible by
reading and writing database information based on values




how to Specifying Parameters in Commands
When you use the SqlDataSource control, you can set the control's command properties to parameterized SQL statements or to the name of a stored procedure.
The SqlDataSource control adds the value of the ParameterPrefix property to the beginning of all parameter names. (The default prefix is "@".)


Using Parameters with the SqlClient Provider:
By default, the SqlDataSource control uses the System.Data.SqlClient data provider to work with SQL Server as the data source. The System.Data.SqlClient provider supports named parameters as placeholders, as shown in the following example:


SELECT * FROM Stud WHERE Rollno = @Rno
AND Name = @Name


The following example shows how to use parameters in an SQL command for a SqlDataSource control that uses the System.Data.SqlClient provider

[C# code]

<asp:sqlDataSource ID="StudInfo"
SelectCommand="SELECT Marks,Rollno,ID FROM Stud WHERE Rollno = @Rno"
ConnectionString="<%$ ConnectionStrings:Stud %>" RunAt="server">
<SelectParameters>
<asp:Parameter Name="Rno" Type="Int32" DefaultValue="0" />
</SelectParameters>

//Suppose for insert query
<InsertParameters>
<asp:Parameter Name="abc" Type="String" />
<asp:Parameter Name="xyz" Type="String" />
</InsertParameters>

// for update
<UpdateParameters>
<asp:Parameter Name="abc" Type="String" />
</UpdateParameters>

//you can also use Seesion Parameter

<SelectParameters>
<asp:SessionParameter
Name="Rollno"
SessionField="Rno"
DefaultValue="1" />
</SelectParameters>

// also pass via querystring
<SelectParameters>

<asp:QueryStringParameter Name="Rollno" QueryStringField="rno" Type="int" />

</SelectParameters>


like this u can access Parameters with the SqlDataSource Control
also refer This Article

Saturday, June 20, 2009

ways of using hyperlink control in data controls.

Here are some different ways of using hyperlink control in data controls.

What is a Hyperlink control:
A hyperlink control is used to navigate from the client to another page.Here is a example for a hyperlink control

<asp:HyperLink ID="hyp1" runat="server" Text="test" ></asp:HyperLink>


In data controls like datagrid and gridview we have hyperlink column and hyperlink field.
We will have a gridview containing hyperlinkfield as shown below where DataNavigateUrlFields and DataNavigateUrlFormatString are used to get
Fields from datasource and construct the url for navigation to next page.In the datagrid hyperlink column we have the same fields and you can follow the same procedure.


<asp:GridView ID="gdview" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:HyperLinkField HeaderText="Category" DataTextField="CategoryName" DataNavigateUrlFields="CategoryID" DataNavigateUrlFormatString="~/page.aspx?id={0}" />
</Columns>
</asp:GridView>

in code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}

public void BindGrid()
{
SqlConnection conn = new SqlConnection("Data Source='localhost';Initial Catalog='Northwind';Persist Security Info=False ");
SqlDataAdapter da = new SqlDataAdapter("", conn);
da.SelectCommand = new SqlCommand("select * from emp", conn);
DataSet ds = new DataSet();
da.Fill(ds, "data");
gdview.DataSource = ds.Tables[0].DefaultView;
gdview.DataBind();

}


Using Mutliple dataitems
If you want to send mutliple items to next page you have to do like this



<asp:GridView ID="gdview" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:HyperLinkField HeaderText="Category" DataTextField="CategoryName" DataNavigateUrlFields="CategoryID,CategoryName" DataNavigateUrlFormatString="~/page.aspx?id={0}&name={1}" />
</Columns>
</asp:GridView>



In runtime
Inorder to access the hyperlinkfield in code behind we have to follow the below
Procedure

In design view:



<asp:GridView ID="gdview" runat="server" AutoGenerateColumns="False" OnRowDataBound="gdview_RowDataBound" >
<Columns>
<asp:HyperLinkField HeaderText="Category" DataTextField="CategoryName" runat="server" />
</Columns>
</asp:GridView>



In code behind:

protected void gdview_RowDataBound(object sender, GridViewRowEventArgs e)
{
HyperLinkField hyp = (HyperLinkField)gdview.Columns[0];
string[] items = new string[2];
items[0] = "CategoryName";
items[1] = "CategoryID";
hyp.DataNavigateUrlFields = items;
hyp.DataNavigateUrlFormatString ="~/page.aspx?id={0}&name={1}";
}



Using Hyperlink control

In the case of repeater and datalist we don’t have hyperlink column.In that scenario we have to use hyperlink control in itemtemplate.

.


In design view:
<asp:Repeater ID="rp1" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<asp:HyperLink ID="hyp1" runat="server" Text='<%#Eval("CategoryName")%>' NavigateUrl='<%#"page.aspx?id=" + DataBinder.Eval(Container.DataItem," CategoryID") + "&name=" + DataBinder.Eval(Container.DataItem,"CategoryName")%>' ></asp:HyperLink>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>



in code behind:


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindRep();
}
}

public void BindRep()
{
SqlConnection conn = new SqlConnection("Data Source='localhost';Initial Catalog='Northwind';Integrated Security=SSPI;Persist Security Info=False ");
SqlDataAdapter da = new SqlDataAdapter("", conn);
da.SelectCommand = new SqlCommand("select CategoryName,CategoryID from Categories", conn);
DataSet ds = new DataSet();
da.Fill(ds, "data");
rp1.DataSource = ds.Tables[0].DefaultView;
rp1.DataBind();
}


Here in this example we have passed multiple data items to page.aspx.In the same way you can create hyperlink control in datalist.