Skip to main content

Posts

Showing posts from February, 2008

GridView color change depending on inner value

rotected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // This line will get the reference to the underlying row DataRowView _row = (DataRowView)e.Row.DataItem; if (_row != null) { // get the field value which you want to compare and// convert to the corresponding data type// i assume the fieldName is of int typeint _field = Convert.ToInt32(_row.Row["fieldName"]); if (_field == 7) e.Row.BackColor = System.Drawing.Color.Green; else e.Row.BackColor = System.Drawing.Color.Red; } } }

How To Create Bound Column Dynamically (Data Grid)

Step 1: Add the GridView to your page. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:DataGrid ID="datagrid1" runat="server" AutoGenerateColumns="false" OnDataBinding="DataGrid1_DataBinding" OnItemCommand="DataGrid1_ItemCommand"> <Columns> </Columns> </asp:DataGrid> </div> <asp:Label ID="lblStatus" runat="server"&g…

Confirm GridView Deletes with the ModalPopupExtender

Step 1: Add the GridView to your page, placing it inside an UpdatePanel. <asp:UpdatePanelID="updatePanel"runat="server"UpdateMode="Conditional"><ContentTemplate><asp:LabelID="lblTitle"runat="server"Text="User List"BackColor="lightblue"Width="95%"/><asp:GridViewID="gvUsers"runat="server"AutoGenerateColumns="false"Width="95%"><AlternatingRowStyleBackColor="aliceBlue"/><HeaderStyleHorizontalAlign="Left"/><Columns><asp:BoundFieldDataField="ID"HeaderText="ID"/><asp:BoundFieldDataField="FirstName"HeaderText="FirstName"/><asp:BoundFieldDataField="LastName"HeaderText="LastName"/><asp:BoundFieldDataField="Address"HeaderText="Address"/></Columns></asp:GridView></ContentTemplate></asp:Update…

Creating a DataTable programmatically in ASP.NET

This article will show how to create a DataTable object at runtime and binding it to a DataGrid web controlThe various data bound controls available in ASP.NET allow you to bind themselves with objects that implements IList interface of System.Collections namespace. The famous DataList and DataGrid controls can be bound to more complex data sources like the DataSet and DataTable. Usually you fetch data from a database and fill these data containers from this data and then bind the DataGrid or DataList with these objects.Some times it becomes necessary that the data not come from a data base but comes from some other source, like from some where in your program you are reading the file system and want to display that data. In such scenarios you can populate the DataSet or more commonly a DataTable in your ASP.NET web page and then bind the web control with this data object.Here I’ve used a very simple method to dynamically create a DataTable and populated it in the function with some r…

Printing GridView from ASp.net

<%@ Page Language="C#" %><%@ Import Namespace="System.Data" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><scriptrunat="server">private DataTable GetDataTable() { //create table DataTable dt = new DataTable("Product"); dt.Columns.Add("ProductID", Type.GetType("System.Int32")); dt.Columns.Add("ProductName", Type.GetType("System.String")); //create fields DataColumn[] pk = new DataColumn[1]; pk[0] = dt.Columns["ProductID"]; dt.PrimaryKey = pk; dt.Columns["ProductID"].AutoIncrement = true; dt.Columns["ProductID"].AutoIncrementSeed = 1; dt.Columns["ProductID"].ReadOnly = true; //fill rows DataRow dr; for (int x = 1; x <= 10; x++) { //make every other …

How To Open Modal PopUp Inside Gridview

<%@ Page Language="C#" %><%@ Import Namespace="System.Data"%><%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ccl" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><scriptrunat="server">protectedvoid Grd_SelectedIndexChanged(object sender, EventArgs e) { GridViewRow row = ((GridView)sender).SelectedRow; if (row == null) return; ModalPopupExtender extender = row.FindControl("extPerson") as ModalPopupExtender; if (extender != null) { extender.Show(); } } private DataSet CreateDS() { DataSet ds = new DataSet(); if (Session["ds"] == null) { DataTable dt = new DataTable("PersonData"); DataRow dr; dt.Columns.Ad…

How to locate control nested inside of another control

Finding controls within a Page's control hierarchy can be painful but if you know how the controls are nested you can use the lesser known "$" shortcut to find controls without having to write recursive code. The following example shows how to use the DefaultFocus property to set the focus on a textbox that is nested inside of a FormView control. Notice that the "$" is used to delimit the nesting: <form id="form1" DefaultFocus="formVw$txtName" runat="server"> <div> <asp:FormView ID="formVw" runat="server"> <ItemTemplate> Name: </ItemTemplate> </asp:FormView> </div> </form> This little trick can also be used on the server-side when calling FindControl(): TextBox tb = this.FindControl("form1$formVw$txtName") as TextBox; if (tb != null) { //Access TextBox control …

Adding Auto Suggest Box in the search Box

Adding Auto suggest box using Ajax(Microsoft ASP.NET Ajax extension) was very easy. You need a web service (returning the list of words), the autocompleteextender to show the panel and a text box. The webservice is required to return an array list.The code to use the autocompleteextender is very simple<ajaxtoolkit:autocompleteextenderrunat="server"id="AutoCompleteExtender1"enabled="true"minimumprefixlength="1"servicepath="~/SuggestionService.asmx"servicemethod="GetAllNames"targetcontrolid="txtSearch"/>Here MinimumPrefixLength is the number of words after which the the suggestion will be shown. Service path is the path to the web service and service method is the webmethod that will be used. The target control ID is the id of the textbox. That Is the syntax of the extender control. We also have to make a web service.I decided to keep the values in a array list .The web service is like thisSuggestionService.asmx…

Read Excel files from ASP.NET

Read Excel files from ASP.NET: This page provides a simple example of how to query an Excel spreadsheetfrom an ASP.NET page using either C# or VB.NET. Check it out!This code was written in response to a message posted on one ofCharles Carroll''s ASP.NET lists. You can ... This page provides a simple example of how to query an Excel spreadsheet from an ASP.NET page using either C# or VB.NET. Check it out! <%@ Page Language="C#" %><%@ Import Namespace="System.Data.OleDb" %><%@ Import Namespace="System.Data" %><%@ Import Namespace="System" %><scriptlanguage="C#"runat="server">protectedvoid Page_Load(Object Src, EventArgs E) { string strConn; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\exceltest.xls;" + "Extended Properties=Excel 8.0;"; //You must use the $ after the object you reference in the sp…

How To Add Columns (BoundColumn and HyperLinkColumn) to DataGrid Programmatically in C#

Sometimes we need to create column in DataGrid dynamically. By using the following code you can create BoundColumn and HyperLinkColumn to DataGrid Programmatically using C#. Adding BoundColumn and HyperLinkColumn to DataGrid publicvoid AddboundandHyperLinkColumn() { // First add a simple bound column BoundColumn nameColumn = new BoundColumn(); nameColumn.DataField = "ProductName"; nameColumn.DataFormatString = "{0}"; nameColumn.HeaderText = "Product"; // Now add the HyperLink column HyperLinkColumn linkColumn = new HyperLinkColumn(); linkColumn.DataTextField = "ProductName"; linkColumn.DataTextFormatString = "{0} Details"; linkColumn.DataNavigateUrlField = "ProductID"; linkColumn.DataNavigateUrlFormatString = "/MyApp/ProductDetails.aspx={0}"; linkColumn.HeaderText = "Details"; // Add the link in …

Using SqlBulkCopy to Import Excel Spreadsheet Data into SQL Server

Let's take an Excel Workbook with a worksheet, called Data, that contains 1000 rows of data broken into 2 columns, ID and Data. I want to copy this data into a SQL Server Database Table, called ExcelData, with the same schema. Just a little bit of code transfers the data from the Excel Spreadsheet into the SQL Server Database Table: // Connection String to Excel Workbookstring excelConnectionString = @"Provider=Microsoft .Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;"""; // Create Connection to Excel Workbookusing (OleDbConnection connection = new OleDbConnection(excelConnectionString)) { OleDbCommand command = new OleDbCommand ("Select ID,Data FROM [Data$]", connection); connection.Open(); // Create DbDataReader to Data Worksheetusing (DbDataReader dr = command.ExecuteReader()) { // SQL Server Connection Stringstring sqlConnectionString = "Data Source=.; Initial Catalog=Test;Integrated Security=True&q…

How To Copy Table Data Between SQL Servers at High Speeds - Through SqlBulkCopy

SqlBulkCopy is a new feature in ADO.NET 2.0 that gives you DTS-like speeds when you need to programmatically copy data from one database to another. Late last night I needed to harness SqlBulkCopy when for some unknown reason my beloved Red Gate Tools kept hanging when trying to transfer data from SQL Server 2000 to SQL Server 2005. Lucky for me my situation was simple. I had identical tables on both databases. I just needed to populate those empty tables on SQL Server 2005 with the data on SQL Server 2000. It took me about 20 minutes to write the code as SqlBulkCopy does the bulk of the work. Shown below is my slapped-together CopyData Class that accepts 2 connection strings, one for the source database and one for the destination database. A single method CopyTable is called with the name of the table whose data needs to be transferred from one database to another. /// /// CopyData /// public class CopyData { string _sourceConnectionString; string _destinationConnectionString; …

Nested DataList to show Master/Details relationship in ASP.NET 2.0

This will helpyou to nest grdiviews inside ASP.NET. There may be many ways to do this, but this is my way( May not be the best, let me know if you have any other 1. First drop a DataList to the page, also set its DataKeyNames to your primary key2. Add a new template column to this DataList3. Place another DataList this template column.<%@ Page Language="C#" %><%@ Import Namespace="System.Data" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><scriptrunat="server">private DataSet CreateDS() { DataSet ds = new DataSet(); if (Session["dsEvents"] == null) { DataTable dt = new DataTable("PersonData"); DataRow dr; dt.Columns.Add(new DataColumn("Person_ID", typeof(Int32))); dt.Columns.Add(new DataColumn("PersonName", typeof(string))); dt.Columns.A…

How To Convert Movie File To FLV Format using ffmpeg

protectedvoid convert_Click(object sender, EventArgs e) { Process ffmpeg; // creating processstring video; string mpg; video = Page.MapPath("FreeHugs.wmv"); // setting video input name with path mpg = Page.MapPath("") + "\\video.flv"; // thumb name with path ! ffmpeg = new Process(); ffmpeg.StartInfo.Arguments = " -i " + video + " -s 480*360 -deinterlace -ab 32 -r 15 -ar 22050 -ac 1 " + mpg; // arguments ! ffmpeg.StartInfo.FileName = Page.MapPath("ffmpeg.exe"); ffmpeg.Start(); // start ! ffmpeg.WaitForExit(); ffmpeg.Close(); } publicvoid ExtractImage() { Process ffmpeg; // creating processstring video; string thumb; video = Page.MapPath("video.flv"); // setting video input name with path thumb = Page.MapPath("") + "\\frame.jpg"; // thumb name with path ! ffmpeg = new Process()…