Sometimes in .net application we need to have a copy of a dll which is available in GAC. But when we view the GAC through C:\Windows\assembly folder or Runà assembly it will show like this
Using this we cannot copy the dll. Only uninstall option is available.
To view the available dll using the naked eye follow the steps
Dot net have a dll file Shfusion.dll which is a Assembly Cache Viewer (Shfusion.dll) is a Windows shell extension that allows you to view and manipulate the contents of the global assembly cache using Windows Explorer. Shfusion.dll is located in the <Windows Folder>\Microsoft.NET\Framework\vx.x.xxxx folder, where x.x.xxxx is the version and build number of the .NET Framework you are using.
uninstall the dll using the following command in the run dialog box.
This error message is mostly comes up, when you try to access a file which is opened by another process. You may open an image file in one of your form in a picturebox with using ImageFromFile or something. I mostly use memorystream to open an image. After read it in byte[] write it into a stream and close it.
You can check whether a file is being used or not with a simple function.
An enumerator is a read-only, forward-only cursor over a sequence of values. An enumerator is an object that either:
Implements IEnumerator or IEnumerator
Has a method named MoveNext for iterating the sequence, and a property called Current for getting the current element in the sequence
The foreach statement iterates over an enumerable object. An enumerable object is the logical representation of a sequence, and is not itself a cursor, but an object that produces cursors over itself. An enumerable object either:
Implements IEnumerable or IEnumerable
Has a method named GetEnumerator that returns an enumerator
Iterators
An iterator is a method, property, or indexer that contains one or more yield statements. An iterator must return one of the following four interfaces (otherwise, the compiler will generate an error):
Iterators that return an enumerator interface tend to be used less often. They're useful when writing a custom collection class: typically, you name the iterator GetEnumerator and have your class implement IEnumerable.
Iterators that return an enumerable interface are more common—and simpler to use because you don't have to write a collection class. The compiler, behind the scenes, writes a private class implementing IEnumerable (as well as IEnumerator).
foreach statement is a consumer of an enumerator, an iterator is a producer of an enumerator. In this example, we use an iterator to return a sequence of Fibonacci numbers (where each number is the sum of the previous two):
Whereas a return statement expresses "Here's the value you asked me to return from this method," a yield return statement expresses "Here's the next element you asked me to yield from this enumerator." On each yield statement, control is returned to the caller, but the callee's state is maintained so that the method can continue executing as soon as the caller enumerates the next element. The lifetime of this state is bound to the enumerator, such that the state can be released when the caller has finished enumerating.
Edit the Global web.config (placed at %Windows Install Folder%Microsoft.NET\Frame
work\v2.0.50727\CONFIG).
add the new full folder path in the Compilation section of the configuration file.
<compilation tempDirectory="E:\New Location\" debug="false">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GoogleMap.aspx.cs" Inherits="GoogleMap" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="Server"><metahttp-equiv="content-type"content="text/html; charset=utf-8"/><title>Google Maps JavaScript API Example</title><scriptsrc="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAjQ5pL86XOoQ41VopETg1BxRfqogRWDFFWKC2bFG72235ZrnYERRoUjFELdorAiLMorc8KixeuNcskQ"type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[function load() {
if (GBrowserIsCompatible()) {
var lat = document.getElementById("lat").value;
var lon = document.getElementById("lon").value;
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(lat,lon), 13);
}
}
//]]></script></head><bodyonload="load()"onunload="GUnload()"><formid="form1"runat="server"><div><divid="map"style="width: 500px; height: 300px"></div></div></form></body></html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
publicpartialclass GoogleMap : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{ string lat = "37.4419";
string lon = "-122.1419";
Page.ClientScript.RegisterHiddenField("lat", lat);
Page.ClientScript.RegisterHiddenField("lon", lon);
}
}
In this post i will show how to create custom control and also how to add design time support .
When inheriting from the WebControl class, you must override the Render method to provide the desired output. The following is a code sample of LogoControl that contains
a property for the LogoUrl and the CompanyName:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.Design;
using System.Drawing;
using System.ComponentModel;
namespace CustomControl
{
[Designer("CustomControl.LogoControlDesigner, CustomControl")]
[ToolboxData(@"<{0}:LogoControl runat=""server"" CompanyName="" "" LogoUrl="" "" />")]
publicclass LogoControl : WebControl
{
public LogoControl()
{
}
publicstring LogoUrl
{
get { return _logoUrl; }
set { _logoUrl = value; }
}
privatestring _logoUrl;
publicstring CompanyName
{
get { return _companyName; }
set { _companyName = value; }
}
privatestring _companyName;
protectedoverridevoid Render(HtmlTextWriter writer)
{
writer.WriteFullBeginTag("div");
writer.Write(@"<img src=""{0}"" /><br />", LogoUrl);
writer.Write(CompanyName + "<br />");
writer.WriteEndTag("div");
}
}
}
The ToolboxBitmapAttribute class is located in the System.Drawing namespace in the System.Drawing.dll assembly. The following code snippet shows the ToolboxBitmap being set to a .bmp file that is configured to be an embedded resource. (When you use the ToolBoxBitmapAttribute, the Attribute suffix is optional.)
You can also change the namespace prefix that is assigned by the Web page designer by assigning the TagPrefixAttribute to the assembly that contains your custom control. The following snippet shows the namespace prefix being changed to “mcl” for the controls in the Customcontrol project
[assembly: TagPrefix("LogoControl", "mcl")]
Now we add custom designer for our that is used to render the control
when in design mode by adding a reference to the System.Design.dll assembly and creating a class that inherits from the ControlDesigner class. This can be beneficial when the normal rendering of the control may not be visible due to code that needs to run to populate specific properties. For example, you may want to provide a custom designer for the LogoControl that provides a default rendering when the LogoUrl property
has not been set, as shown in the following code sample:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.Design;
using System.Drawing;
using System.ComponentModel;
namespace CustomControl
{
class LogoControlDesigner : System.Web.UI.Design.ControlDesigner
{
private LogoControl _logoControl;
publicoverridestring GetDesignTimeHtml()
{
if (_logoControl.LogoUrl.Trim().Length == 0)
{
return"<div id=\'mcl1\' "
+
"style=\'background-color:red;border-width:2px;\' >"
+
"<center>LogoControl</center><br />"
+
"<center>Please set LogoUrl property.</center><br />"
+ "</div>";
}
else
{
returnbase.GetDesignTimeHtml();
}
}
publicoverridevoid Initialize(IComponent component)
{
_logoControl = (LogoControl)component;
base.Initialize(component);
return;
}
}
}
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
publicpartialclass CalInsideGridView : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetCustomMadeDataTable();
GridView1.DataBind();
}
}
public DataTable GetCustomMadeDataTable()
{
//Create a new DataTable object
System.Data.DataTable objDataTable = new System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("ISBN", typeof(string));
objDataTable.Columns.Add("Title", typeof(string));
objDataTable.Columns.Add("Publisher", typeof(string));
objDataTable.Columns.Add("Year", typeof(string));
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["ISBN"];
objDataTable.PrimaryKey = dcPk;
objDataTable.Columns["ISBN"].AutoIncrement = true;
objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 1; i <= 10; i++)
{
dr = objDataTable.NewRow();
dr[1] = "Title" + i.ToString();
dr[2] = "Publisher" + i.ToString();
dr[3] = "12/12/200" + i.ToString();
objDataTable.Rows.Add(dr);
}
Session["strTemp"] = objDataTable;
return objDataTable;
}
protectedvoid Cal1_SelectionChanged(object sender, EventArgs e)
{
Calendar cal = (Calendar)sender;
TextBox text1 = (TextBox)((GridViewRow)cal.Parent.Parent).FindControl("text1");
text1.Text = cal.SelectedDate.ToShortDateString();
}
}
The connectionStrings element can be encrypted by running the Visual Studio 2005 Command Prompt, executing the following command, and specifying the full path to your Web site folder:
aspnet_regiis -pef "connectionStrings" "C:\...\EncryptWebSite"
Note that the –pef switch requires you to pass the physical Web site path, which is the last parameter. Be sure to verify the path to your Web.config file. The encrypted Web.config file will look like the following:
Many people think that the Calendar control is only used as a date picker control, but the Calendar control can also be used to display a schedule. The trick to using the Calendar control to display scheduled items and special days is to make the control
large enough to display text in each day, and then add Label controls (or other controls) to the Cell object’s Controls collection in the DayRender event handler.
The following example shows how a Calendar control can be used as a schedule display
showing special days. In this example, a Web page was created and a Calendar control was added to the page. The following code was added to the code-behind page to show how the Calendar control’s properties can be set programmatically and the Calendar control events can be used.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;
publicpartialclass ExportToExcel : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BuildUserList();
}
}
privatevoid BuildUserList()
{
IList<User> users = new List<User>();
users.Add(new User("Xyz", "Coder"));
users.Add(new User("Abc", "Writer"));
users.Add(new User("Charles", "Poet"));
// assign users to GridView
GridView1.DataSource = users;
GridView1.DataBind();
}
publicclass User
{
/// <summary>/// ctor/// </summary>/// <param name="name"></param>/// <param name="description"></param>public User(string name, string description)
{
_name = name;
_description = description;
_id = Guid.NewGuid().ToString();
}
privatestring _id;
publicstring Id
{
get { return _id; }
set { _id = value; }
}
privatestring _name;
publicstring Name
{
get { return _name; }
set { _name = value; }
}
privatestring _description;
publicstring Description
{
get { return _description; }
set { _description = value; }
}
}
protectedvoid Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than// comment out the line below// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new System.IO.StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
publicoverridevoid VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the//specified ASP.NET server control at run time.//for more details check out this link//http://msdn.microsoft.com/en-us/library/system.web.ui.page.verifyrenderinginserverform.aspx
GridView grid = control as GridView;
if (grid != null && grid.ID == "GridView1")
return;
elsebase.VerifyRenderingInServerForm(control);
}
}
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
publicpartialclass RadioListImage : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
string[] strImages = System.IO.Directory.GetFiles(Server.MapPath("~/img"));
foreach (string strImage in strImages)
{
this.rdoI.Items.Add(new ListItem(String.Format("<img src='{0}'>", strImage.ToString()), strImage.ToString()));
}
}
}
In .net 1.1, the GridCommandEventArgs used to give access to the row that triggered the command.
In .net 2.0, it isn't as obvious as that. Fritz posted an excellent discussion on the matter, and i'm just posting his 2-line solution here for reference.
If your button is a ButtonField, then you can access the index of the item via e.CommandArgument. This may be enough information to do whatever you need.
If your button is a LinkButton in a TemplateField, you have to add the CommandArgument as an attribute to the LinkButton: CommandArgument='<%# Eval("id") %>'
Then in the code behind for RowCommand, you can use the following syntax:
I wanted to install my web application assembly into the GAC, but this is made more complicated by the multitude of assemblies produced by VS when i publish the web site. On the newsgroups, i found some talk of a tool called Merge_Aspnet.exe but i couldn't find it anywhere. Eventually i found it as a download on MSDN, it is bundled as part of the Web Deployment Projects. You install it, and then right-click your project in VS and you should see a new menu item "Add Web Deployment Project". I am baffled as to why they didn't just add a new project type in the list of projects under "Deployment". There is a link to "Search online templates" so i think it should really be available there. but it looks like MS did a hack just to add in a new item to the project context menu. but it works... so i'll stop complaining.
This postshows 2 common tasks with the ASP.NET GridView: Binding a List (generic) of objects as DataSource and on clicking a row, getting the values of the selected row by a javascript function. In the example a List with User-objects is displayed. On clicking a row containing the data of a User-object, the Id of the object is used to get the address of the user by an Ajax-call and display it in a details-field.
Binding objects to a GridView in ASP.NET is a well supported feature. You need to add the objects you like to bind to a Collection like an IList<> and assign the list as datasource to the GridView. The mechanism of binding works by reading out the properties of the bound objects. Each property of your object maps to a column in the GridView.
So binding and displaying your data isn't very hard. A little more tricky is the procedure to refer to your data in a client-script. There are some use-cases where you need this, for example when you want to get some detail-information that correspond to the selected row, but don't want to reload the page for that. In our sample-project we get the address of the selected user by executing a Webservice-call and display the information in a DIV-element.
Binding the List
First we define a User and Address-object for binding to a GridView:(in App_Code Folder)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>/// User/// </summary>publicclass User
{
/// <summary>/// ctor/// </summary>/// <param name="name"></param>/// <param name="description"></param>public User(string name, string description)
{
_name = name;
_description = description;
_id = Guid.NewGuid().ToString();
}
privatestring _id;
publicstring Id
{
get { return _id; }
set { _id = value; }
}
privatestring _name;
publicstring Name
{
get { return _name; }
set { _name = value; }
}
privatestring _description;
publicstring Description
{
get { return _description; }
set { _description = value; }
}
}
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>/// Summary description for Address/// </summary>publicclass Address
{
public Address(string street, string location, string zipCode)
{
_street = street;
_location = location;
_zipCode = zipCode;
}
privatestring _street;
publicstring Street
{
get { return _street; }
set { _street = value; }
}
privatestring _location;
publicstring Location
{
get { return _location; }
set { _location = value; }
}
privatestring _zipCode;
publicstring ZipCode
{
get { return _zipCode; }
set { _zipCode = value; }
}
publicoverridestring ToString()
{
string result = "";
result += "Street: " + _street + "<BR/>";
result += "Location: " + _location + "<BR/>";
result += "ZipCode: " + _zipCode + "<BR/>";
return result;
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageMethods.aspx.cs" Inherits="_Default" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headid="Head1"runat="server"><title>GridView, javascript and Webservice</title><scripttype="text/javascript">/** * a user has been clicked * @param userId id of the user * Now we defined that whenever a DataRow is clicked, * the javascript-function CallMyWebService is called. * And here is the function in the head of the aspx-page: */function CallMyWebService( userId)
{
PageMethods.GetAddressForUser(userId, OnRequestComplete);
}
function OnRequestComplete(result)
{
document.getElementById('addressBox').innerHTML = result;
}
</script></head><bodystyle="font-family: Tahoma"><formid="frmMain"runat="server"><asp:ScriptManagerID="ScriptManger1"runat="Server"EnablePageMethods="true"></asp:ScriptManager><div><h1>
GridView, javascript and Ajax</h1><spanstyle="font-size: 10pt"><strong>Users:</strong></span><br/><asp:GridViewID="GridView1"runat="server"BackColor="LightGoldenrodYellow"BorderColor="Tan"BorderWidth="1px"CellPadding="2"Font-Names="Tahoma"ForeColor="Black"GridLines="None"Width="300px"OnRowDataBound="GridView1_RowDataBound"AutoGenerateColumns="False"><FooterStyleBackColor="Tan"/><SelectedRowStyleBackColor="DarkSlateBlue"ForeColor="GhostWhite"/><PagerStyleBackColor="PaleGoldenrod"ForeColor="DarkSlateBlue"HorizontalAlign="Center"/><HeaderStyleBackColor="Tan"Font-Bold="True"/><AlternatingRowStyleBackColor="PaleGoldenrod"/><Columns><asp:BoundFieldDataField="Id"Visible="False"/><asp:BoundFieldDataField="Name"HeaderText="Name"><HeaderStyleHorizontalAlign="Left"/></asp:BoundField><asp:BoundFieldDataField="Description"HeaderText="Description"><HeaderStyleHorizontalAlign="Left"/></asp:BoundField></Columns></asp:GridView><br/><spanstyle="font-size: 10pt"><strong>User's address:</strong></span><br/><divstyle="width: 300px; height: 80px; background-color: Beige"><divstyle="margin: 5px 5px 5px 5px"id="addressBox"></div></div></div></form></body></html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
publicpartialclass _Default : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BuildUserList();
}
}
privatevoid BuildUserList()
{
IList<User> users = new List<User>();
users.Add(new User("Xyz", "Coder"));
users.Add(new User("Abc", "Writer"));
users.Add(new User("Charles", "Poet"));
// assign users to GridView
GridView1.DataSource = users;
GridView1.DataBind();
// Store some sampledata
Dictionary<string, Address> addresses = new Dictionary<string, Address>();
addresses.Add(users[0].Id, new Address("Teststreet", "Stuttgart", "83840"));
addresses.Add(users[1].Id, new Address("India", "Delhi", "23455"));
addresses.Add(users[2].Id, new Address("Abc", "Bangalore", "34566"));
Session["Addresses"] = addresses;
}
protectedvoid GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
User selUser = e.Row.DataItem as User;
e.Row.Attributes.Add("onclick", "CallMyWebService('" + selUser.Id + "')");
}
}
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
publicstaticstring GetAddressForUser(string userId)
{
Dictionary<string, Address> addresses = HttpContext.Current.Session["Addresses"] as Dictionary<string, Address>;
Address address = addresses[userId];
return address.ToString();
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewCustomEvent.aspx.cs"
Inherits="GridViewCustomEvent" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title>Untitled Page</title></head><body><formid="form1"runat="server"><div><table><tr><tdstyle="height: 194px"><h3>
Using Event Delegates in the controls nested within a GridView</h3><p>
In this sample I use event delegates to process an event triggered by a child control
within a gridview</p><table><tr><tdrunat="server"id="tdDG3"></td><tdrunat="server"id="tdStatus"width="400"></td></tr><tr><tdcolspan="2">
Column Number
<asp:TextBoxID="txtColNo"runat="server"Text="1"MaxLength="1"Width="20"></asp:TextBox><asp:RegularExpressionValidatorID="valRegExp"runat="server"ErrorMessage="Invalid Column Number"ControlToValidate="txtColNo"ValidationExpression="[1-2]"Display="Dynamic"></asp:RegularExpressionValidator><asp:ButtonID="btnHideDisplay"Text="Toggle the visiblity of the specified column"runat="server"OnClick="ChangeVisibility"></asp:Button></td></tr></table></td></tr></table></div></form></body></html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
publicpartialclass GridViewCustomEvent : System.Web.UI.Page
{
protected CustomControls.CustomGridView dg;
privatevoid Page_Load(object sender, System.EventArgs e)
{
dg = new CustomControls.CustomGridView();
dg.AutoGenerateColumns = false;
dg.CssClass = "GridStyle2";
dg.HeaderStyle.CssClass = "DataGrid1HeaderStyle";
dg.DataSource = CreateDS().Tables["PersonData"];
dg.DataBind();
dg.Columns[0].ItemStyle.CssClass = "Col1Item";
dg.Columns[2].ItemStyle.CssClass = "Col3Item";
dg.Columns[3].ItemStyle.CssClass = "Col2Item";
tdDG3.Controls.Add(dg);
dg.chkBoxChanged += new CustomControls.CheckBoxChangedEventHandler(this.CheckBox_Clicked);
dg.ddlIndexChanged += new CustomControls.ddlIndexChangedEventHandler(this.ddlIndex_Changed);
}
protectedvoid ChangeVisibility(object sender, EventArgs e)
{
if (txtColNo.Text != "1" && txtColNo.Text != "2")
{
tdStatus.InnerHtml = "Invalid Column Number";
}
else
{
int iIndex = Convert.ToInt16(txtColNo.Text);
dg.Columns[iIndex].Visible = !dg.Columns[iIndex].Visible;
}
}
privatevoid CheckBox_Clicked(object sender, CustomControls.CustomGV_Event_Args e)
{
if (((CheckBox)sender).Checked)
{
e.dgrow.Cells[e.SelectedCell].BackColor = System.Drawing.Color.Gainsboro;
tdStatus.InnerHtml += "<br>You selected row " + e.dgrow.RowIndex + " and column " + e.SelectedCell;
}
else
{
e.dgrow.Cells[e.SelectedCell].BackColor = System.Drawing.Color.Ivory;
tdStatus.InnerHtml += "<br><font color=red>You unselected row " + e.dgrow.RowIndex + " and column " + e.SelectedCell + "</font>";
}
}
privatevoid ddlIndex_Changed(object sender, CustomControls.CustomGV_Event_Args e)
{
tdStatus.InnerHtml += "<br>You selected " + ((DropDownList)sender).SelectedValue + " at row " + e.dgrow.RowIndex + " and column " + e.SelectedCell;
}
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.Add(new DataColumn("Company", typeof(string)));
for (int i = 1; i < 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Person " + i;
dr[2] = "Company " + i;
dt.Rows.Add(dr);
}
DataColumn parentCol;
parentCol = dt.Columns["Person_ID"];
ds.Tables.Add(dt);
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = dt.Columns["Person_Id"];
dt.PrimaryKey = PrimaryKeyColumns;
dt = new DataTable("Orders");
dt.Columns.Add(new DataColumn("PrimaryKey", typeof(Int32)));
dt.Columns.Add(new DataColumn("ForeignKey", typeof(Int32)));
dt.Columns.Add(new DataColumn("Order", typeof(string)));
for (int i = 1; i < 60; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = 1 + i % 9;
dr[2] = "Order # " + i;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
DataColumn childCol;
childCol = dt.Columns["ForeignKey"];
DataRelation relation1;
relation1 = new DataRelation("CustomersOrders", parentCol, childCol);
// Add the relation to the DataSet.
ds.Relations.Add(relation1);
Session["dsEvents"] = ds;
}
else
{
ds = (DataSet)Session["dsEvents"];
}
return ds;
}
}
namespace CustomControls
{
publicdelegatevoid CheckBoxChangedEventHandler(object sender, CustomGV_Event_Args e);
publicdelegatevoid ddlIndexChangedEventHandler(object sender, CustomGV_Event_Args e);
publicenum GVListItemType
{
Item = 0,
AlternatingItem = 1,
EditItem = 2,
DropDownListItem = 3,
CheckBoxListItem = 4,
Footer = 6,
Header = 7
}
publicclass GridViewTemplate : ITemplate
{
GVListItemType templateType;
string columnName;
public GridViewTemplate(GVListItemType type, string colname)
{
templateType = type;
columnName = colname;
}
publicvoid InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case GVListItemType.Header:
Literal lc = new Literal();
lc.Text = "<B>" + columnName + "</B>";
container.Controls.Add(lc);
break;
case GVListItemType.CheckBoxListItem:
CheckBox chkBox = new CheckBox();
container.Controls.Add(chkBox);
chkBox.DataBinding += new EventHandler(chkbox_DataBinding);
Label lbl = new Label();
container.Controls.Add(lbl);
lbl.DataBinding += new EventHandler(label_DataBinding);
break;
case GVListItemType.DropDownListItem:
DropDownList ddl = new DropDownList();
container.Controls.Add(ddl);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBinding += new EventHandler(ddl_DataBinding);
ddl.AutoPostBack = true;
break;
}
}
privatevoid ddl_DataBinding(object sender, System.EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow container;
container = ddl.NamingContainer as GridViewRow;
ddl.DataSource = ((DataRowView)container.DataItem).CreateChildView("CustomersOrders");
ddl.SelectedIndexChanged += new EventHandler(((CustomGridView)ddl.NamingContainer.NamingContainer).DropDownList_Command);
}
privatevoid chkbox_DataBinding(object sender, System.EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow container;
container = chk.NamingContainer as GridViewRow;
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(((CustomGridView)chk.NamingContainer.NamingContainer).CheckBox_Command);
}
privatevoid label_DataBinding(object sender, System.EventArgs e)
{
Label lbl = (Label)sender;
GridViewRow container;
container = lbl.NamingContainer as GridViewRow;
lbl.Text = DataBinder.Eval(container.DataItem, columnName) asstring;
}
}
publicclass CustomGV_Event_Args : EventArgs
{
private GridViewRow dataViewItem;
privateint selectedCell;
publicint SelectedCell
{
get
{
return selectedCell;
}
}
public GridViewRow dgrow
{
get
{
return dataViewItem;
}
}
public CustomGV_Event_Args(object sender)
{
string uniqueID = null;
if (sender is CheckBox)
{
dataViewItem = ((CheckBox)sender).NamingContainer as GridViewRow;
uniqueID = ((CheckBox)sender).UniqueID;
}
elseif (sender is DropDownList)
{
dataViewItem = ((DropDownList)sender).NamingContainer as GridViewRow;
uniqueID = ((DropDownList)sender).UniqueID;
}
for (int i = 0; i < dataViewItem.Cells.Count; i++)
{
if (dataViewItem.Cells[i].Controls.Count > 0)
{
if (dataViewItem.Cells[i].Controls[0].UniqueID == uniqueID) selectedCell = i;
}
}
}
}
[ToolboxData("<{0}:CustomGridView runat=server></{0}:CustomGridView>")]
publicclass CustomGridView : System.Web.UI.WebControls.GridView
{
private BoundField bc;
private TemplateField tc;
publicevent CheckBoxChangedEventHandler chkBoxChanged;
publicevent ddlIndexChangedEventHandler ddlIndexChanged;
protectedoverridevoid CreateChildControls()
{
bc = new BoundField();
bc.DataField = "Person_ID";
bc.HeaderText = "Person_ID";
this.Columns.Add(bc);
tc = new TemplateField();
tc.HeaderTemplate = new GridViewTemplate(GVListItemType.Header, "PersonName");
tc.ItemTemplate = new GridViewTemplate(GVListItemType.CheckBoxListItem, "PersonName");
this.Columns.Add(tc);
tc = new TemplateField();
tc.HeaderTemplate = new GridViewTemplate(GVListItemType.Header, "Company");
tc.ItemTemplate = new GridViewTemplate(GVListItemType.CheckBoxListItem, "Company");
this.Columns.Add(tc);
tc = new TemplateField();
tc.HeaderTemplate = new GridViewTemplate(GVListItemType.Header, "Orders");
tc.ItemTemplate = new GridViewTemplate(GVListItemType.DropDownListItem, "Order");
this.Columns.Add(tc);
}
publicvoid CheckBox_Command(Object sender, EventArgs e)
{
CustomGV_Event_Args ea = new CustomGV_Event_Args(sender);
if (chkBoxChanged != null)
{
chkBoxChanged(sender, ea);
}
}
publicvoid DropDownList_Command(Object sender, EventArgs e)
{
CustomGV_Event_Args ea = new CustomGV_Event_Args(sender);
if (ddlIndexChanged != null)
{
ddlIndexChanged(sender, ea);
}
}
}
}