/// <summary>
/// Handle grid Employee row command
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void grdEmployee_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Details")
{
GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int index = row.RowIndex;
int EmployeeID = Convert.ToInt32(grdEmployee.DataKeys[index].Value);
}
}
Here “e.CommandSource” is the Clicked LinkButton and NamingContainer is its Parent Control. So that will be the GridViewRow. Here we can easily find the DataKey. Here in my Example EmployeeID is the DataKey
<asp:GridView ID="grdEmployee" runat="server"
EmptyDataText="No Employee Available."
Width="100%" AllowPaging="True"
PageSize="10" OnRowDeleting="grdEmployee_RowDeleting" OnPageIndexChanging="grdEmployee_PageIndexChanging"
DataKeyNames="EmployeeID"
OnRowCommand="grdEmployee_OnRowCommand">
<Columns>
<asp:BoundField HeaderText="Employee Code" DataField="EmployeeCode">
</asp:BoundField>
<asp:BoundField HeaderText="Employee Name" DataField="EmployeeName">
</asp:BoundField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="lbtnDelete" runat="server" CausesValidation="false" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" CausesValidation="false" CommandName="Details" Text="View Details"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Dot net Sample codes, C#.net, ASP.net, VB.NET, Dot net Tips, Data grid, Grid View, Dot net Framework, SQL Server
Monday, December 6, 2010
Friday, December 3, 2010
Difference between RadioButtonList and RadioButton
Difference between RadioButtonList and RadioButton
1. RadioButtonList
RadioButtonList is a single control with a list of RadioButtons.
This is derived from ListControl class. So this will work similar to other list controls like ListBox, DropDownList and CheckBoxList.
For giving a caption for buttons you can use the Text property. You cannot insert a text in between two buttons.
Using the “SelectedIndexChanged” event you will get the selected buttons value (“RadioButtonList1.SelectedValue”).
It is easy to bind this to a DataSource.
private void Bind()
{
RadioButtonList1.DataSource = dsEmployees;
RadioButtonList1.DataTextField = "EmployeeName";
RadioButtonList1.DataValueField = "EmployeeID";
RadioButtonList1.DataBind();
}
If you are using HTML
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
RepeatDirection="Horizontal"
onselectedindexchanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem Text="Male" Value="1" ></asp:ListItem>
<asp:ListItem Text="Female" Value="2" ></asp:ListItem>
</asp:RadioButtonList>
2. RadioButton
“”RadioButton” is a single control, it is derived from “CheckBox” Class. You have to set the GroupName property to identify a group. Also the event handler for the event “CheckedChanged” will help us to do some job. Another one thing is you have to write separate handlers for each radio button.
For e.g.:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Gender"
AutoPostBack="true" oncheckedchanged="RadioButton1_CheckedChanged" Text="Male" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Gender"
AutoPostBack="true" oncheckedchanged="RadioButton2_CheckedChanged" Text="Female" />
1. RadioButtonList
RadioButtonList is a single control with a list of RadioButtons.
This is derived from ListControl class. So this will work similar to other list controls like ListBox, DropDownList and CheckBoxList.
For giving a caption for buttons you can use the Text property. You cannot insert a text in between two buttons.
Using the “SelectedIndexChanged” event you will get the selected buttons value (“RadioButtonList1.SelectedValue”).
It is easy to bind this to a DataSource.
private void Bind()
{
RadioButtonList1.DataSource = dsEmployees;
RadioButtonList1.DataTextField = "EmployeeName";
RadioButtonList1.DataValueField = "EmployeeID";
RadioButtonList1.DataBind();
}
If you are using HTML
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
RepeatDirection="Horizontal"
onselectedindexchanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem Text="Male" Value="1" ></asp:ListItem>
<asp:ListItem Text="Female" Value="2" ></asp:ListItem>
</asp:RadioButtonList>
2. RadioButton
“”RadioButton” is a single control, it is derived from “CheckBox” Class. You have to set the GroupName property to identify a group. Also the event handler for the event “CheckedChanged” will help us to do some job. Another one thing is you have to write separate handlers for each radio button.
For e.g.:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Gender"
AutoPostBack="true" oncheckedchanged="RadioButton1_CheckedChanged" Text="Male" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Gender"
AutoPostBack="true" oncheckedchanged="RadioButton2_CheckedChanged" Text="Female" />
Friday, October 29, 2010
Format Excel file using XSLT, XslCompiledTransform
See the sample code for creating an Excel file formatted with the help of XSLT file.
------------------------------------------------------------------------------------
private void button1_Click(object sender, EventArgs e)
{
ExportToExcel(GetDataSet(), "Employees.xslt", "c:\\Employees.xls");
}
Method to create a dataset for writing to excel
---------------------------------------------------------
private DataSet GetDataSet()
{
DataSet ds = new DataSet();
DataTable dtEmployees = new DataTable("Employees");
DataColumn colEmpID = new DataColumn("EmpID");
DataColumn colEmpName = new DataColumn("EmpName");
DataColumn colAge = new DataColumn("Age");
DataColumn colLocation = new DataColumn("Location");
DataColumn colDesignation = new DataColumn("Designation");
dtEmployees.Columns.AddRange(new DataColumn[] { colEmpID, colEmpName, colAge, colLocation, colDesignation });
DataRow dr = dtEmployees.NewRow();
dr[colEmpID] = "E001";
dr[colEmpName] = "George";
dr[colAge] = "45";
dr[colLocation] = "USA";
dr[colDesignation] = "PM";
dtEmployees.Rows.Add(dr);
dr = dtEmployees.NewRow();
dr[colEmpID] = "E002";
dr[colEmpName] = "James";
dr[colAge] = "30";
dr[colLocation] = "INDIA";
dr[colDesignation] = "TL";
dtEmployees.Rows.Add(dr);
dr = dtEmployees.NewRow();
dr[colEmpID] = "E002";
dr[colEmpName] = "Mary";
dr[colAge] = "35";
dr[colLocation] = "UK";
dr[colDesignation] = "Developer";
dtEmployees.Rows.Add(dr);
ds.Tables.Add(dtEmployees);
return ds;
}
Method to create a XSLT formatted excel file
---------------------------------------------------------
public bool ExportToExcel(DataSet ds, string xsltPath, string pathToSave)
{
try
{
XmlDataDocument xmlDoc = new XmlDataDocument();
xmlDoc.LoadXml(ds.GetXml());
XslCompiledTransform xsl = new XslCompiledTransform();
xsl.Load(xsltPath);
StreamWriter strWriter = new StreamWriter(pathToSave);
xsl.Transform(xmlDoc, null, strWriter);
strWriter.Flush();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
Save the below mentioned XSLT in a file with name "Employees.xslt" in "C" drive to run the sample
---------------------------------------------------------
<xsl:stylesheet version="1.0"
xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:my-scripts"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:ms="urn:schemas-microsoft-com:xslt"
>
<xsl:template match="NewDataSet">
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Styles>
<Style ss:ID="s21">
<Font ss:FontName="Arial" ss:Size="10" ss:Bold="1"/>
<Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/>
</Style>
<Style ss:ID="s22">
<Font ss:FontName="MS Sans Serif" ss:Size="10"/>
<Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/>
</Style>
<Style ss:ID="s25">
<Font ss:Color="Red" ss:FontName="MS Sans Serif" ss:Size="10"/>
<Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/>
</Style>
</Styles>
<Worksheet>
<xsl:attribute name="ss:Name">Employees List</xsl:attribute>
<Table>
<Column ss:Width="50"/>
<Column ss:Width="50"/>
<Column ss:Width="30"/>
<Column ss:Width="90"/>
<xsl:apply-templates select="NewDataSet"/>
<Row>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Name</Data>
</Cell>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Employee ID</Data>
</Cell>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Age</Data>
</Cell>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Location</Data>
</Cell>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Designation</Data>
</Cell>
</Row>
<xsl:for-each select="Employees">
<Row>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="EmpID"/>
</Data>
</Cell>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="EmpName"/>
</Data>
</Cell>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="Age"/>
</Data>
</Cell>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="Location"/>
</Data>
</Cell>
<xsl:choose>
<xsl:when test="Designation='PM'">
<Cell ss:StyleID="s25">
<Data ss:Type="String">
<xsl:value-of select="Designation"/>
</Data>
</Cell>
</xsl:when>
<xsl:otherwise>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="Designation"/>
</Data>
</Cell>
</xsl:otherwise>
</xsl:choose>
</Row>
</xsl:for-each>
</Table>
</Worksheet>
</Workbook>
</xsl:template>
</xsl:stylesheet>
------------------------------------------------------------------------------------
private void button1_Click(object sender, EventArgs e)
{
ExportToExcel(GetDataSet(), "Employees.xslt", "c:\\Employees.xls");
}
Method to create a dataset for writing to excel
---------------------------------------------------------
private DataSet GetDataSet()
{
DataSet ds = new DataSet();
DataTable dtEmployees = new DataTable("Employees");
DataColumn colEmpID = new DataColumn("EmpID");
DataColumn colEmpName = new DataColumn("EmpName");
DataColumn colAge = new DataColumn("Age");
DataColumn colLocation = new DataColumn("Location");
DataColumn colDesignation = new DataColumn("Designation");
dtEmployees.Columns.AddRange(new DataColumn[] { colEmpID, colEmpName, colAge, colLocation, colDesignation });
DataRow dr = dtEmployees.NewRow();
dr[colEmpID] = "E001";
dr[colEmpName] = "George";
dr[colAge] = "45";
dr[colLocation] = "USA";
dr[colDesignation] = "PM";
dtEmployees.Rows.Add(dr);
dr = dtEmployees.NewRow();
dr[colEmpID] = "E002";
dr[colEmpName] = "James";
dr[colAge] = "30";
dr[colLocation] = "INDIA";
dr[colDesignation] = "TL";
dtEmployees.Rows.Add(dr);
dr = dtEmployees.NewRow();
dr[colEmpID] = "E002";
dr[colEmpName] = "Mary";
dr[colAge] = "35";
dr[colLocation] = "UK";
dr[colDesignation] = "Developer";
dtEmployees.Rows.Add(dr);
ds.Tables.Add(dtEmployees);
return ds;
}
Method to create a XSLT formatted excel file
---------------------------------------------------------
public bool ExportToExcel(DataSet ds, string xsltPath, string pathToSave)
{
try
{
XmlDataDocument xmlDoc = new XmlDataDocument();
xmlDoc.LoadXml(ds.GetXml());
XslCompiledTransform xsl = new XslCompiledTransform();
xsl.Load(xsltPath);
StreamWriter strWriter = new StreamWriter(pathToSave);
xsl.Transform(xmlDoc, null, strWriter);
strWriter.Flush();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
Save the below mentioned XSLT in a file with name "Employees.xslt" in "C" drive to run the sample
---------------------------------------------------------
<xsl:stylesheet version="1.0"
xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:my-scripts"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:ms="urn:schemas-microsoft-com:xslt"
>
<xsl:template match="NewDataSet">
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Styles>
<Style ss:ID="s21">
<Font ss:FontName="Arial" ss:Size="10" ss:Bold="1"/>
<Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/>
</Style>
<Style ss:ID="s22">
<Font ss:FontName="MS Sans Serif" ss:Size="10"/>
<Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/>
</Style>
<Style ss:ID="s25">
<Font ss:Color="Red" ss:FontName="MS Sans Serif" ss:Size="10"/>
<Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/>
</Style>
</Styles>
<Worksheet>
<xsl:attribute name="ss:Name">Employees List</xsl:attribute>
<Table>
<Column ss:Width="50"/>
<Column ss:Width="50"/>
<Column ss:Width="30"/>
<Column ss:Width="90"/>
<xsl:apply-templates select="NewDataSet"/>
<Row>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Name</Data>
</Cell>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Employee ID</Data>
</Cell>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Age</Data>
</Cell>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Location</Data>
</Cell>
<Cell ss:StyleID="s21">
<Data ss:Type="String">Designation</Data>
</Cell>
</Row>
<xsl:for-each select="Employees">
<Row>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="EmpID"/>
</Data>
</Cell>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="EmpName"/>
</Data>
</Cell>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="Age"/>
</Data>
</Cell>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="Location"/>
</Data>
</Cell>
<xsl:choose>
<xsl:when test="Designation='PM'">
<Cell ss:StyleID="s25">
<Data ss:Type="String">
<xsl:value-of select="Designation"/>
</Data>
</Cell>
</xsl:when>
<xsl:otherwise>
<Cell ss:StyleID="s22">
<Data ss:Type="String">
<xsl:value-of select="Designation"/>
</Data>
</Cell>
</xsl:otherwise>
</xsl:choose>
</Row>
</xsl:for-each>
</Table>
</Worksheet>
</Workbook>
</xsl:template>
</xsl:stylesheet>
Wednesday, October 13, 2010
Disable Save/Open Button in ASP.NET Download Dialog box
Code Behind
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=sample.xls");
Response.Write("Hello World");
Response.End();
}
HTML Page
To disable Save button, write this meta tag
<head runat="server">
<meta name="DownloadOptions" content="nosave" />
</head>
To disable Open button, write this meta tag
<head runat="server">
<meta name="DownloadOptions" content="noopen" />
</head>
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=sample.xls");
Response.Write("Hello World");
Response.End();
}
HTML Page
To disable Save button, write this meta tag
<head runat="server">
<meta name="DownloadOptions" content="nosave" />
</head>
To disable Open button, write this meta tag
<head runat="server">
<meta name="DownloadOptions" content="noopen" />
</head>
Friday, October 8, 2010
DataKey from a GridView RowCommand Event
Method to get DataKey from a GridView RowCommand Event
protected void grdEmployees_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int index = row.RowIndex;
int employeeID = Convert.ToInt32(grdEmployees.DataKeys[index].Value);
}
}
For this eg: There should be GridView Control with a TemplateField and that should contain a Linkbutton with CommandName="Select"
protected void grdEmployees_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int index = row.RowIndex;
int employeeID = Convert.ToInt32(grdEmployees.DataKeys[index].Value);
}
}
For this eg: There should be GridView Control with a TemplateField and that should contain a Linkbutton with CommandName="Select"
SQL Query to Get SP and Text from DB
SELECT sysobjects.name, syscomments.text
FROM sysobjects JOIN syscomments ON
sysobjects.id = syscomments.id
WHERE xtype='P'
FROM sysobjects JOIN syscomments ON
sysobjects.id = syscomments.id
WHERE xtype='P'
Write to Event Viewer
/// <summary>
/// Method to write Errors to Event viewer
/// </summary>
/// <param name="message">message</param>
static void WriteToEventViewer(string message)
{
string sSource = "Sample";
string sLog = "MyApplication";
if (!EventLog.SourceExists(sSource))
{
EventLog.CreateEventSource(sSource, sLog);
}
EventLog.WriteEntry(sSource, message,
EventLogEntryType.Error);
}
for more information refer this
http://msdn.microsoft.com/en-us/library/xzwc042w.aspx
/// Method to write Errors to Event viewer
/// </summary>
/// <param name="message">message</param>
static void WriteToEventViewer(string message)
{
string sSource = "Sample";
string sLog = "MyApplication";
if (!EventLog.SourceExists(sSource))
{
EventLog.CreateEventSource(sSource, sLog);
}
EventLog.WriteEntry(sSource, message,
EventLogEntryType.Error);
}
for more information refer this
http://msdn.microsoft.com/en-us/library/xzwc042w.aspx
Get Client Machine IP Address
/// <summary>
/// Method to get Client IP number
/// </summary>
/// <returns>IP Address</returns>
private string GetIPNumber()
{
return Request.UserHostAddress;
}
/// Method to get Client IP number
/// </summary>
/// <returns>IP Address</returns>
private string GetIPNumber()
{
return Request.UserHostAddress;
}
Friday, July 9, 2010
Dynamic SQL Query Building
Create SQL Table
CREATE TABLE [dbo].[Employee](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Address] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Phone] [varchar](15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Pin] [int] NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Insert Data in to Employee Table
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Sabu','Cochin','9876543210',682030)
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Arun','TVM','9876543210',789456)
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Rahul','BGLR','1472583690',456782)
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Ann','DELHI','1234566985',256314)
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Vipin','Cochin','5852369641',682020)
Procedure for searching for Employees
---------------------------------------------------
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
CREATE PROCEDURE pr_SearchEmployee
-- Add the parameters for the stored procedure here
@EmployeeName varchar(20)
,@EmployeeAddress nvarchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE @searchQuery varchar(300)
SET @searchQuery = 'SELECT [ID]
,[Name]
,[Address]
,[Phone]
,[Pin]
FROM Employee WHERE '
IF len(@EmployeeName) > 0
BEGIN
SET @searchQuery = @searchQuery + '[Name] LIKE ' + char(39) + '%' + @EmployeeName + '%' + char(39)
END
ELSE IF len(@EmployeeAddress) > 0
BEGIN
SET @searchQuery = @searchQuery + '[Address] LIKE ' + char(39) + '%' + @EmployeeAddress + '%' + char(39)
END
EXEC (@searchQuery)
END
---------------------------------------------------------------------------
Execute Procedure
EXEC pr_SearchEmployee '','Cochin'
CREATE TABLE [dbo].[Employee](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Address] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Phone] [varchar](15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Pin] [int] NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Insert Data in to Employee Table
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Sabu','Cochin','9876543210',682030)
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Arun','TVM','9876543210',789456)
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Rahul','BGLR','1472583690',456782)
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Ann','DELHI','1234566985',256314)
INSERT INTO Employee([Name],[Address],[Phone],[Pin])VALUES('Vipin','Cochin','5852369641',682020)
Procedure for searching for Employees
---------------------------------------------------
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
CREATE PROCEDURE pr_SearchEmployee
-- Add the parameters for the stored procedure here
@EmployeeName varchar(20)
,@EmployeeAddress nvarchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE @searchQuery varchar(300)
SET @searchQuery = 'SELECT [ID]
,[Name]
,[Address]
,[Phone]
,[Pin]
FROM Employee WHERE '
IF len(@EmployeeName) > 0
BEGIN
SET @searchQuery = @searchQuery + '[Name] LIKE ' + char(39) + '%' + @EmployeeName + '%' + char(39)
END
ELSE IF len(@EmployeeAddress) > 0
BEGIN
SET @searchQuery = @searchQuery + '[Address] LIKE ' + char(39) + '%' + @EmployeeAddress + '%' + char(39)
END
EXEC (@searchQuery)
END
---------------------------------------------------------------------------
Execute Procedure
EXEC pr_SearchEmployee '','Cochin'
Wednesday, June 2, 2010
Embed Windows Mediaplayer in a Web Page
<HTML>
<HEAD>
<TITLE>Embed Media player</TITLE>
</HEAD>
<BODY>
<OBJECT id="media1" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" type="application/x-oleobject" width="300" height="300">
<PARAM NAME="URL" VALUE="intro.wmv">
<PARAM NAME="ENABLED" VALUE="True">
<PARAM NAME="AUTOSTART" VALUE="False">
<PARAM name="PLAYCOUNT" value="2">
<PARAM name="VOLUME" value="50">
<PARAM NAME="MUTE" VALUE="False">
<PARAM NAME="FULLSCREEN" VALUE="FALSE">
<PARAM name="UIMODE" value="full">
</OBJECT>
</BODY>
</HTML>
<HEAD>
<TITLE>Embed Media player</TITLE>
</HEAD>
<BODY>
<OBJECT id="media1" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" type="application/x-oleobject" width="300" height="300">
<PARAM NAME="URL" VALUE="intro.wmv">
<PARAM NAME="ENABLED" VALUE="True">
<PARAM NAME="AUTOSTART" VALUE="False">
<PARAM name="PLAYCOUNT" value="2">
<PARAM name="VOLUME" value="50">
<PARAM NAME="MUTE" VALUE="False">
<PARAM NAME="FULLSCREEN" VALUE="FALSE">
<PARAM name="UIMODE" value="full">
</OBJECT>
</BODY>
</HTML>
Monday, February 22, 2010
Anonymous Methods Vs Named Methods
create a console application in c#.net and copy this
namespace ConsoleApplication1
{
class Program
{
//Declaring a delegate
delegate void Display(String text);
static void Main(string[] args)
{
//Anonymous method
Display d = delegate(String s)
{
Console.WriteLine(s + "Anonymous method");
};
//Calling anonymous method
d("I am calling ");
d = new Display(Program.Foo);
//Calling named method
d("I am calling ");
Console.ReadLine();
}
/// Named method
public static void Foo(String text)
{
Console.WriteLine(text + "Named Method.");
}
}
}
You cannot use a "ref" or "out" variable inside an anonymous method.
If you are using a variable that is declared outside the anonymous method is called "outer" or "captured" variables of the anonymous method.
eg:-
string outside = "I am captured";
//Anonymous method
Display d = delegate(String s)
{
Console.WriteLine(s + "Anonymous method " + outside);
};
namespace ConsoleApplication1
{
class Program
{
//Declaring a delegate
delegate void Display(String text);
static void Main(string[] args)
{
//Anonymous method
Display d = delegate(String s)
{
Console.WriteLine(s + "Anonymous method");
};
//Calling anonymous method
d("I am calling ");
d = new Display(Program.Foo);
//Calling named method
d("I am calling ");
Console.ReadLine();
}
/// Named method
public static void Foo(String text)
{
Console.WriteLine(text + "Named Method.");
}
}
}
You cannot use a "ref" or "out" variable inside an anonymous method.
If you are using a variable that is declared outside the anonymous method is called "outer" or "captured" variables of the anonymous method.
eg:-
string outside = "I am captured";
//Anonymous method
Display d = delegate(String s)
{
Console.WriteLine(s + "Anonymous method " + outside);
};
Labels:
Anonymous,
Anonymous Method,
Named,
Named Method
Sunday, February 21, 2010
Conditional Loop In XSLT
XML
--------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="test.xslt" ?>
<Root>
<Title>Looping function example</Title>
<Limit>10</Limit>
</Root>
XSLT
----------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/">
<html>
<head>
<title> <xsl:value-of select="Root/Title" /> </title>
</head>
<body>
<!--CALLING FUNCTION -->
<h3><xsl:value-of select="Root/Title" /></h3>
<xsl:call-template name="LoopingFunc">
<xsl:with-param name="limit" select="Root/Limit" />
</xsl:call-template>
</body>
</html>
</xsl:template>
<!--LOOPING FUNCTION -->
<xsl:template name="LoopingFunc">
<xsl:param name="limit"/>
<xsl:if test="$limit > 0">
<h5>
<xsl:value-of select="$limit"/>
</h5>
<xsl:call-template name="LoopingFunc">
<xsl:with-param name="limit" select="$limit - 1" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Out put
----------------
Looping function example
10
9
8
7
6
5
4
3
2
1
--------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="test.xslt" ?>
<Root>
<Title>Looping function example</Title>
<Limit>10</Limit>
</Root>
XSLT
----------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/">
<html>
<head>
<title> <xsl:value-of select="Root/Title" /> </title>
</head>
<body>
<!--CALLING FUNCTION -->
<h3><xsl:value-of select="Root/Title" /></h3>
<xsl:call-template name="LoopingFunc">
<xsl:with-param name="limit" select="Root/Limit" />
</xsl:call-template>
</body>
</html>
</xsl:template>
<!--LOOPING FUNCTION -->
<xsl:template name="LoopingFunc">
<xsl:param name="limit"/>
<xsl:if test="$limit > 0">
<h5>
<xsl:value-of select="$limit"/>
</h5>
<xsl:call-template name="LoopingFunc">
<xsl:with-param name="limit" select="$limit - 1" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Out put
----------------
Looping function example
10
9
8
7
6
5
4
3
2
1
Labels:
Iteration in XSLT,
XSLT,
XSLT Conditional Looping
Thursday, February 18, 2010
Enable and Disable a Control by Binding to another Control
You can Set the Enable Property of a control by binding that control to another control.
How to Achieve this?
See this code snippet.This is a Windows Application Project with C# language.
To test this code you should have a TextBox named "txtName" and a CheckBox named "chk".
In the form load event write this
txtName.DataBindings.Add("Enabled", chk, "Checked");Execute code and check and uncheck CheckBox. So that you can find the TextBox's property changing.
Serialize Objects using BinaryFormatter
Serialization is the process of converting an object to a format that can be transfer through a network or can be save to a location(file or DB).
The serialized data contains the object's informations like Version,Culture,PublicKeyToken,Type etc.
Deserialization is the reverse process of serialization, that is reconstructing the object from the serialized state to its original state.
Here is an eg:
A class "Employee" and its collection class "Employees". I marked these classes as Serializable with the [Serializable] attribute.
and also i am using BinaryFormatter to Serialize and Deserialize this object.
private void button1_Click
(object sender, EventArgs e)
{
Employees emps = new Employees();
emps.Add(new Employee("1", "Sabu"));
emps.Add(new Employee("2", "Litson"));
String pth = @"E:\Test.dat";
Serialize(emps, pth);
Deserialize(pth);
}
public void Serialize(Employees emps, String filename)
{
System.IO.Stream ms = File.OpenWrite(filename);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(ms, emps);
ms.Flush();
ms.Close();
ms.Dispose();
formatter = null;
}
public void Deserialize(String filename)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
object obj = formatter.Deserialize(File.Open(filename, FileMode.Open));
Employees emps = (Employees)obj;
MessageBox.Show(emps[1].Name);
}
//Classes
[Serializable]
public class Employee
{
public Employee(String id, String name)
{
_ID = id;
_Name = name;
}
private String _ID = String.Empty;
private String _Name = String.Empty;
public String ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}
public String Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
}
[Serializable]
public class Employees:CollectionBase
{
//Constructor
public Employees()
{
}
//Add function
public void Add(T objT)
{
this.List.Add(objT);
}
//Indexer
public T this[int i]
{
get
{
return (T) this.List[i];
}
set
{
this.List.Add(value);
}
}
}
The serialized data contains the object's informations like Version,Culture,PublicKeyToken,Type etc.
Deserialization is the reverse process of serialization, that is reconstructing the object from the serialized state to its original state.
Here is an eg:
A class "Employee" and its collection class "Employees". I marked these classes as Serializable with the [Serializable] attribute.
and also i am using BinaryFormatter to Serialize and Deserialize this object.
private void button1_Click
(object sender, EventArgs e)
{
Employees emps = new Employees();
emps.Add(new Employee("1", "Sabu"));
emps.Add(new Employee("2", "Litson"));
String pth = @"E:\Test.dat";
Serialize(emps, pth);
Deserialize(pth);
}
public void Serialize(Employees emps, String filename)
{
System.IO.Stream ms = File.OpenWrite(filename);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(ms, emps);
ms.Flush();
ms.Close();
ms.Dispose();
formatter = null;
}
public void Deserialize(String filename)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
object obj = formatter.Deserialize(File.Open(filename, FileMode.Open));
Employees emps = (Employees)obj;
MessageBox.Show(emps[1].Name);
}
//Classes
[Serializable]
public class Employee
{
public Employee(String id, String name)
{
_ID = id;
_Name = name;
}
private String _ID = String.Empty;
private String _Name = String.Empty;
public String ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}
public String Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
}
[Serializable]
public class Employees:CollectionBase
{
//Constructor
public Employees()
{
}
//Add function
public void Add(T objT)
{
this.List.Add(objT);
}
//Indexer
public T this[int i]
{
get
{
return (T) this.List[i];
}
set
{
this.List.Add(value);
}
}
}
Labels:
BinaryFormatter,
Serialization,
Serialize Objects
Serialize Objects using XmlSerializer class
--------------------------------------
Serialization is the process of converting an object to a format that can be transfer through a network or can be save to a location(file or DB).
The serialized data contains the object's informations like Version,Culture,PublicKeyToken,Type etc.
Deserialization is the reverse process of serialization, that is reconstructing the object from the serialized state to its original state.
Here is an eg:
A class "Employee" and its collection class "Employees". I marked these classes as Serializable with the [Serializable] attribute.
and also i am using XmlSerializer class to Serialize and Deserialize this object.
private void button1_Click
(object sender, EventArgs e)
{
Employees
emps.Add(new Employee("1", "Sabu"));
emps.Add(new Employee("2", "Litson"));
String pth = @"E:\Test.xml";
XmlSerialize(emps, pth);
XmlDeserialize(pth);
}
public void XmlSerialize(Employees
{
System.IO.Stream ms = File.OpenWrite(filename);
System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(emps.GetType());
xmlSer.Serialize(ms, emps);
ms.Flush();
ms.Close();
ms.Dispose();
xmlSer = null;
}
public void XmlDeserialize(String filename)
{
System.Xml.Serialization.XmlSerializer xmlSer =
new System.Xml.Serialization.XmlSerializer(typeof(Employees
FileStream fs = new FileStream(filename, FileMode.Open);
object obj = xmlSer.Deserialize(fs);
Employees
MessageBox.Show(emps[1].Name);
}
//Classes
[Serializable]
public class Employee
{
public Employee(String id, String name)
{
_ID = id;
_Name = name;
}
private String _ID = String.Empty;
private String _Name = String.Empty;
public String ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}
public String Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
}
[Serializable]
public class Employees
{
//Constructor
public Employees()
{
}
//Add function
public void Add(T objT)
{
this.List.Add(objT);
}
//Indexer
public T this[int i]
{
get
{
return (T) this.List[i];
}
set
{
this.List.Add(value);
}
}
}
DataGridView - Dynamically Seting up column styles
#region Person Class
public class Person
{
private String _code = String.Empty;
private String _name = String.Empty;
private String _address = String.Empty;
private String _faxNo = String.Empty;
private String _contactPerson = String.Empty;
public int ID
{
get { return _id; }
set { _id = value; }
}
public String Code
{
get
{
return _code;
}
set
{
_code = value;
}
}
public String Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public String Address
{
get { return _address; }
set { _address = value; }
}
public String FaxNo
{
get { return _faxNo; }
set { _faxNo = value; }
}
public String ContactPerson
{
get { return _contactPerson; }
set { _contactPerson = value; }
}
public void Fill(DataRow drPerson)
{
if (drPerson != null)
{
this.Code =
drPerson["code"].ToString();
this.Name =
drPerson["name"].ToString();
this.Address =
drPerson["address"].ToString();
this.FaxNo =
drPerson["faxno"].ToString();
this.ContactPerson =
drPerson["contactperson"].ToString();
}
}
public List GetAllPersons()
{
List persons = new List();
DataTable dtPerson = new DataTable();
using (SqlConnection conn = DataHelper.GetConnection())
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
String getQuery = "SELECT id,code,name,address," +
"faxno,contactperson FROM person ORDER BY name";
comm.CommandText = getQuery;
comm.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
daConst.SelectCommand = comm;
try
{
connConst.Open();
daConst.Fill(dtPerson);
if (dtPerson.Rows.Count < 1)
{
foreach (DataRow drPerson in dtPerson.Rows)
{
Person objPerson = new Person();
objPerson.Fill(drPerson);
persons.Add(objClient);
}
}
}
catch (Exception ex)
{ throw ex; }
finally
{ comm.Dispose(); }
}
}
return persons;
}
}
#endregion
#region "Form Events"
private void FormView_Load(object sender, EventArgs e)
{
SetupGrid();
dgvPersons.DataSource = Person.GetAllPersons();
}
#region SetupGrid
///
/// SetupGrid
///
private void SetupGrid()
{
DataGridViewTextBoxColumn colCode = new DataGridViewTextBoxColumn();
colCode.HeaderText = "Code";
colCode.DataPropertyName = "Code";
colCode.Width = 50;
DataGridViewTextBoxColumn colName = new DataGridViewTextBoxColumn();
colName.HeaderText = "Name";
colName.DataPropertyName = "Name";
colName.Width = 250;
DataGridViewTextBoxColumn colAddressDet = new DataGridViewTextBoxColumn();
colAddressDet.HeaderText = "Address";
colAddressDet.DataPropertyName = "Address";
colAddressDet.Width = 300;
DataGridViewTextBoxColumn colFaxNo = new DataGridViewTextBoxColumn();
colFaxNo.HeaderText = "FaxNo";
colFaxNo.DataPropertyName = "FaxNo";
colFaxNo.Width = 50;
DataGridViewTextBoxColumn colContactPerson = new DataGridViewTextBoxColumn();
colContactPerson.HeaderText = "ContactPerson";
colContactPerson.DataPropertyName = "ContactPerson";
colContactPerson.Width = 100;
DataGridViewButtonColumn colEdit = new DataGridViewButtonColumn();
colEdit.HeaderText = "Edit";
colEdit.FlatStyle = FlatStyle.Flat;
colEdit.UseColumnTextForButtonValue = true;
colEdit.Text = "Edit";
colEdit.Width = 50;
DataGridViewButtonColumn colDelete = new DataGridViewButtonColumn();
colDelete.HeaderText = "Delete";
colDelete.FlatStyle = FlatStyle.Flat;
colDelete.UseColumnTextForButtonValue = true;
colDelete.Text = "Delete";
colDelete.Width = 60;
dgvClients.Columns.AddRange(new DataGridViewColumn[]
{ colCode, colName, colAddressDet, colFaxNo,
colContactPerson, colEdit, colDelete });
}
#endregion
#endregion
public class Person
{
private String _code = String.Empty;
private String _name = String.Empty;
private String _address = String.Empty;
private String _faxNo = String.Empty;
private String _contactPerson = String.Empty;
public int ID
{
get { return _id; }
set { _id = value; }
}
public String Code
{
get
{
return _code;
}
set
{
_code = value;
}
}
public String Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public String Address
{
get { return _address; }
set { _address = value; }
}
public String FaxNo
{
get { return _faxNo; }
set { _faxNo = value; }
}
public String ContactPerson
{
get { return _contactPerson; }
set { _contactPerson = value; }
}
public void Fill(DataRow drPerson)
{
if (drPerson != null)
{
this.Code =
drPerson["code"].ToString();
this.Name =
drPerson["name"].ToString();
this.Address =
drPerson["address"].ToString();
this.FaxNo =
drPerson["faxno"].ToString();
this.ContactPerson =
drPerson["contactperson"].ToString();
}
}
public List GetAllPersons()
{
List persons = new List();
DataTable dtPerson = new DataTable();
using (SqlConnection conn = DataHelper.GetConnection())
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
String getQuery = "SELECT id,code,name,address," +
"faxno,contactperson FROM person ORDER BY name";
comm.CommandText = getQuery;
comm.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
daConst.SelectCommand = comm;
try
{
connConst.Open();
daConst.Fill(dtPerson);
if (dtPerson.Rows.Count < 1)
{
foreach (DataRow drPerson in dtPerson.Rows)
{
Person objPerson = new Person();
objPerson.Fill(drPerson);
persons.Add(objClient);
}
}
}
catch (Exception ex)
{ throw ex; }
finally
{ comm.Dispose(); }
}
}
return persons;
}
}
#endregion
#region "Form Events"
private void FormView_Load(object sender, EventArgs e)
{
SetupGrid();
dgvPersons.DataSource = Person.GetAllPersons();
}
#region SetupGrid
///
/// SetupGrid
///
private void SetupGrid()
{
DataGridViewTextBoxColumn colCode = new DataGridViewTextBoxColumn();
colCode.HeaderText = "Code";
colCode.DataPropertyName = "Code";
colCode.Width = 50;
DataGridViewTextBoxColumn colName = new DataGridViewTextBoxColumn();
colName.HeaderText = "Name";
colName.DataPropertyName = "Name";
colName.Width = 250;
DataGridViewTextBoxColumn colAddressDet = new DataGridViewTextBoxColumn();
colAddressDet.HeaderText = "Address";
colAddressDet.DataPropertyName = "Address";
colAddressDet.Width = 300;
DataGridViewTextBoxColumn colFaxNo = new DataGridViewTextBoxColumn();
colFaxNo.HeaderText = "FaxNo";
colFaxNo.DataPropertyName = "FaxNo";
colFaxNo.Width = 50;
DataGridViewTextBoxColumn colContactPerson = new DataGridViewTextBoxColumn();
colContactPerson.HeaderText = "ContactPerson";
colContactPerson.DataPropertyName = "ContactPerson";
colContactPerson.Width = 100;
DataGridViewButtonColumn colEdit = new DataGridViewButtonColumn();
colEdit.HeaderText = "Edit";
colEdit.FlatStyle = FlatStyle.Flat;
colEdit.UseColumnTextForButtonValue = true;
colEdit.Text = "Edit";
colEdit.Width = 50;
DataGridViewButtonColumn colDelete = new DataGridViewButtonColumn();
colDelete.HeaderText = "Delete";
colDelete.FlatStyle = FlatStyle.Flat;
colDelete.UseColumnTextForButtonValue = true;
colDelete.Text = "Delete";
colDelete.Width = 60;
dgvClients.Columns.AddRange(new DataGridViewColumn[]
{ colCode, colName, colAddressDet, colFaxNo,
colContactPerson, colEdit, colDelete });
}
#endregion
#endregion
Difference between Arraylist and Generic List
//Arraylist - Arraylist accept values as object
//So i can give any type of data in to that.
//Here in this eg: an arraylist object accepting
//values like String,int,decimal, char and a custom object
Employee emp = new Employee("2", "Litson");
ArrayList arr = new ArrayList();
arr.Add("Sabu");
arr.Add(234);
arr.Add(45.236);
arr.Add(emp);
arr.Add('s');
//This process is known as boxing
//To get inserted vales from arraylist we have to specify the index.
//So it will return that values as object.
//we have to cast that value from object to its original type.
String name = (String)arr[0];
int num = (int)arr[1];
decimal dec = (decimal)arr[2];
Employee em = (Employee)arr[3];
char c = (char)arr[4];
//This process that is converting from object to its original type is known as unboxing
//------------------------------------------------------------------------------------
//Generic List
//List<>
//Main advantage of Generic List is we can specify the type of data we are going to insert in to
//List. So that we can avoid boxing and unboxing
//Eg:
List<string> strLst = new List<string>();
strLst.Add("Sabu");//Here List accepting values as String only
strLst.Add("Litson");
strLst.Add("Sabu");
strLst.Add("Sabu");
List<int> intLst = new List<int>();
intLst.Add(12);//Here List accepting values as int only
intLst.Add(14);
intLst.Add(89);
intLst.Add(34);
List<decimal> decLst = new List<decimal>();
decLst.Add(2.5M);//Here List accepting values as deciaml only
decLst.Add(14.4587m);
decLst.Add(89.258m);
decLst.Add(34.159m);
List<Employee> empLst = new List<Employee>();
empLst.Add(new Employee("1", "Sabu"));//Here List accepting Employee Objects only
empLst.Add(new Employee("2", "Mahesh"));
empLst.Add(new Employee("3", "Sajith"));
empLst.Add(new Employee("4", "Binu"));
//To get values from Generic List
String nme = strLst[0]; //No need of casting
int nm = intLst[0];
Decimal decVal = decLst[0];
Employee empVal = empLst[0];
//So i can give any type of data in to that.
//Here in this eg: an arraylist object accepting
//values like String,int,decimal, char and a custom object
Employee emp = new Employee("2", "Litson");
ArrayList arr = new ArrayList();
arr.Add("Sabu");
arr.Add(234);
arr.Add(45.236);
arr.Add(emp);
arr.Add('s');
//This process is known as boxing
//To get inserted vales from arraylist we have to specify the index.
//So it will return that values as object.
//we have to cast that value from object to its original type.
String name = (String)arr[0];
int num = (int)arr[1];
decimal dec = (decimal)arr[2];
Employee em = (Employee)arr[3];
char c = (char)arr[4];
//This process that is converting from object to its original type is known as unboxing
//------------------------------------------------------------------------------------
//Generic List
//List<>
//Main advantage of Generic List is we can specify the type of data we are going to insert in to
//List. So that we can avoid boxing and unboxing
//Eg:
List<string> strLst = new List<string>();
strLst.Add("Sabu");//Here List accepting values as String only
strLst.Add("Litson");
strLst.Add("Sabu");
strLst.Add("Sabu");
List<int> intLst = new List<int>();
intLst.Add(12);//Here List accepting values as int only
intLst.Add(14);
intLst.Add(89);
intLst.Add(34);
List<decimal> decLst = new List<decimal>();
decLst.Add(2.5M);//Here List accepting values as deciaml only
decLst.Add(14.4587m);
decLst.Add(89.258m);
decLst.Add(34.159m);
List<Employee> empLst = new List<Employee>();
empLst.Add(new Employee("1", "Sabu"));//Here List accepting Employee Objects only
empLst.Add(new Employee("2", "Mahesh"));
empLst.Add(new Employee("3", "Sajith"));
empLst.Add(new Employee("4", "Binu"));
//To get values from Generic List
String nme = strLst[0]; //No need of casting
int nm = intLst[0];
Decimal decVal = decLst[0];
Employee empVal = empLst[0];
Linq to SQL Update Method
//Creating Employee DataContext object
EmployeeDBDataContext db = new EmployeeDBDataContext();
//Selecting an employee to update his name and address
emp = db.Employees.Single(e => e.EmpID == 1);
emp.Name = "Sabu";
emp.Address = "Cochin";
//Submitting changes
db.SubmitChanges();
EmployeeDBDataContext db = new EmployeeDBDataContext();
//Selecting an employee to update his name and address
emp = db.Employees.Single(e => e.EmpID == 1);
emp.Name = "Sabu";
emp.Address = "Cochin";
//Submitting changes
db.SubmitChanges();
Labels:
DataContext Class Update,
LINQ,
LINQ TO SQL UPDATE
Subscribe to:
Posts (Atom)