Monday, March 12, 2012

How to copy single row in datagrid

Hi to all,

I would like to copy data (whole single row at once) from web-based datagrid to off line Excel spreadsheet. I am using Vb.net and Access database.

Please help me!

Regards

Harsh

Here is an example that uses the Northwind database as an example. It creates a CSV file that Excel can open directly, so there is no need to start interfacing with the COM Excel DLL. If your text contains commas, you can use another seperator such as vbTab. Hope this helps

<%@.PageLanguage="VB" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<scriptrunat="server">

ProtectedSub Gridview1_RowCommand(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.GridViewCommandEventArgs)

If e.CommandName ="Export"Then

' Create an instance of StreamWriter to write text to a file.

Using swAs System.IO.StreamWriter =New System.IO.StreamWriter(MapPath("App_Data/TestFile.csv"))

Dim rAs GridViewRow = Gridview1.Rows(CInt(e.CommandArgument))

Dim csvLineAsString =String.Empty

For indexAsInteger = 0To r.Cells.Count - 1

If csvLine =""Then

csvLine = r.Cells(index).Text

Else

csvLine +="," + r.Cells(index).Text

EndIf

Next

sw.WriteLine(csvLine)

sw.Close()

EndUsing

EndIf

EndSub

</script>

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

<formid="form1"runat="server">

<asp:GridViewID="Gridview1"runat="server"AutoGenerateColumns="False"DataKeyNames="CustomerID"

DataSourceID="SqlDataSource1"OnRowCommand="Gridview1_RowCommand">

<Columns>

<asp:TemplateFieldHeaderText="Click link to Export">

<ItemTemplate>

<asp:LinkButtonID="LinkButton1"runat="server"CommandName="Export"CommandArgument='<%# Container.DataItemIndex %>'>Export</asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

<asp:BoundFieldDataField="CustomerID"HeaderText="CustomerID"ReadOnly="True"SortExpression="CustomerID"/>

<asp:BoundFieldDataField="CompanyName"HeaderText="CompanyName"SortExpression="CompanyName"/>

<asp:BoundFieldDataField="PostalCode"HeaderText="PostalCode"SortExpression="PostalCode"/>

<asp:BoundFieldDataField="Phone"HeaderText="Phone"SortExpression="Phone"/>

</Columns>

</asp:GridView>

<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

SelectCommand="SELECT [CustomerID], [CompanyName], [PostalCode], [Phone] FROM [Customers]">

</asp:SqlDataSource>

</form>

</body>

</html>


Thanks sbyard for the code. I appreciate you. I will try this code and hope it will help me.

Regards

Harsh

Labels: , , , , , , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home