C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
DataClassesDataContext o=new DataClassesDataContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
fill();
}
void fill()
{
var m = from x in o.EMPs select x;
gv.DataSource = m;
gv.DataBind();
}
Here i have created three procedures from dml operation that procedure are
PROCEDURE FOR INSERT
ALTER PROCEDURE emp1
(
@NAME VARCHAR(50)
)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO EMP(NAME) VALUES(@NAME)
SET NOCOUNT OFF
END
PROCEDURE FOR UPDATE
CREATE PROCEDURE emp2
(
@ID INT,
@NAME VARCHAR(50)
)
PROCEDURE FOR DELETE
CREATE PROCEDURE emp3
(
@ID INT
)
AS
BEGIN
SET NOCOUNT ON
DELETE FROM EMP WHERE ID=@ID
SET NOCOUNT OFF
END
THEN MAPPING THE PROCEDURE GO TO SOLUTION DOUBLE CLICK ON THE Model.edmx, GO TO model window then right click on the table then select procedure mapping
AS
BEGIN
SET NOCOUNT ON
UPDATE EMP SET NAME=@NAME WHERE ID=@ID
SET NOCOUNT OFF
END
after that u go to solution and double click on model.edmx
then right click on model
select update model from database
then right click on model
select update model from database
after that rihght click on table select store procedure mapping
then select the procedure name from the drop down
right click on the model window select model brower
expand the procedure folder select then right click on procedure select add function import
then new window open after that click on ok button
then clikck on finish buttom
then module window clike this
then go to design view
after that u go to code view
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
#region
DatabaseModel.DatabaseEntities o = new DatabaseModel.DatabaseEntities();
int i;
string s;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
fill();
}
void fill()
{
var m = from x in o.EMPs select x;
gv.DataSource = m;
gv.DataBind();
}
protected void btn_Click(object sender, EventArgs e)
{
o.emp1(tb1.Text);
o.SaveChanges();
lb.Text = "One record saved.";
fill();
}
//protected void lbt_Click(object sender, EventArgs e)
//{
// LinkButton lk = (LinkButton)sender;
// GridViewRow gr = (GridViewRow)lk.NamingContainer;
after that u go to solution and double click on model.edmx
then right click on model
select update model from database
then clikck on finish buttom
then module window like this
then go to design view
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
then go to code view
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
#region
DatabaseModel.DatabaseEntities o = new DatabaseModel.DatabaseEntities();
int i;
string s;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
fill();
}
void fill()
{
var m = from x in o.EMPs select x;
gv.DataSource = m;
gv.DataBind();
}
protected void btn_Click(object sender, EventArgs e)
{
DatabaseModel.EMP p = new DatabaseModel.EMP();
p.ID = Convert.ToInt32(tb.Text);
p.NAME = tb1.Text;
o.AddToEMPs(p);
o.SaveChanges();
lb.Text = "One record saved.";
fill();
}
//protected void lbt_Click(object sender, EventArgs e)
//{
// LinkButton lk = (LinkButton)sender;
// GridViewRow gr = (GridViewRow)lk.NamingContainer;
I have one table and view that is define below:
CREATE TABLE [B]
(
[ID] [int] ,
[NAME] [varchar](50) ,
[SAL] [decimal](18, 2) ,
[TA] [decimal](18, 2)
)
create view [v] as select id,name,sal from B
TRIGGER:
create trigger tr0 on v instead of insert,delete
as
begin
insert into b select id,name,sal,(sal*.1) from inserted
delete from b where id=(select id from deleted)
end
TRIGGER:
alter trigger tr00 on v instead of update
as
begin
if update(name) or update(sal)
update b set name=(select name from inserted),sal=(select sal from inserted),ta=((select sal from inserted)*.1) where id=(select id from deleted)
end
1. CHARINDEX string function takes 2 arguments. 1st argument specifies the character whose index is to be retrieved and 2nd argument takes as a string from which character index is carried out.
Example:
Select CHARINDEX ('S','MICROSOFT SQL SERVER 2000')
Result: 6
2. LEFT string function takes 2 arguments. 1st argument takes as a string value and 2nd argument as integer value as length parameter. It returns first characters of specified length starting from the left side of the string entered as 1st argument.
Example:
Select LEFT ('MICROSOFT SQL SERVER 2000',4)
Result: MICR
3. RIGHT string function takes 2 arguments. 1st argument takes as a string value and 2nd argument as integer value as length parameter. It returns last characters of specified length starting from the right side of the string entered as 1st argument.
Example:
Select RIGHT ('MICROSOFT SQL SERVER 2000',4)
Result: 2000
4. LEN string function takes 1 argument as string value and returns the length of entered string.
Example:
Select LEN ('MICROSOFT SQL SERVER 2000')
Result: 25
5. REPLACE string function takes 3 arguments.
1st argument as string value.
2nd argument is a part of string entered as 1st argument which is to be replaced.
3rd argument as a new string value that is to be placed at the place of 2nd argument.
Example:
Select REPLACE ('MICROSOFT SQL SERVER 2000','MICROSOFT','MS')
Result: MS SQL SERVER 2000
6. STUFF string function takes 4 arguments. It is used to replace specified length of characters with provided pattern.
1st argument as string value.
2nd argument as integer value specifying the starting point of characters to be replaced.
3rd arguments as integer value specifying the length of characters.
4th argument as string value specifying the new pattern of characters.
Example:
Select STUFF ('MICROSOFT SQL SERVER 2000', 11, 3,'S.Q.L.')
Result: MICROSFT S.Q.L. SERVER 2000
7. SUBSTRING string function returns the sub string of specified length starting from the entered start position. It takes 3 arguments.
1st argument as string value.
2nd argument as integer specifying the start position.
3rd argument as integer specifying the length
11. LTRIM function returns the string by removing all the blank spaces at left side. It also takes 1 argument as string value.
Example:
select LTRIM (‘ ASP ’)
Result: ASP-----
blanks at the right side not removed.
12. RTRIM function returns the string by removing all the blank spaces at left side. It also takes 1 argument as string value.
Example:
select RTRIM (‘ ASP ’)
Result: -----ASP
blanks at the left side not removed.
13. PATINDEX function returns the position of first occurrence of specified pattern in the provided string. It takes 2 arguments.
1st argument as string value specifying the pattern to match
2nd argument as string value specifying the string to compare.
14. STR function returns character data converted from numeric data. It takes 3 arguments.
1st argument as float data
2nd argument as integer value specifying the length of the string including decimal that is to be retrieved.
3rd argument as integer specifying the number of places to the right of the decimal point.
Example:
select STR(140.15, 6, 1)
Result: 140.2
15. ASCII function returns the ASCII code value from the leftmost character specified character expression. It takes 1 argument as string/character expression.
Example:
select ASCII('A')
Result: 65
16. NCHAR(expression)
Returns a Unicode String with the specified integer code, as defined by the Unicode standard.
Arguments
expression: An Int32.
Return Value
A Unicode String.
Example NCHAR(65)
Result: A
17. QUOTENAME('char_string' [, 'quote_char'])
Returns a Unicode String with the delimiters added to make the input string a valid SQL Server 2005 delimited identifier.
Arguments
char_string: A Unicode String.
quote_char: A one-character string to use as the delimiter are "({[<"". Can be a single quotation mark ( ' ), a left or right bracket ( [ ] ), or a double quotation mark ( " ). If quote_char is not specified, brackets are used.
Return Value
A Unicode String.
Example
select QUOTENAME('siv','"')
Result "siv"
18. REPLICATE(char_expression, int_expression)
Repeats a character expression for a specified number of times.
Arguments
char_expression: A Unicode or ASCII String type.
int_expression: Int64 (not supported in SQL Server 2000) or Int32.
Return Value
A Unicode or ASCII String type.
Example
select REPLICATE('siv ', 2)
Result
siv siv
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
#region
static OleDbConnection cn = null;
static OleDbConnection cn1 = null;
OleDbCommand cm = null;
OleDbDataAdapter da = null;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
int i,j,k;
string s, ss = "varchar(50)";
string[] st1;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
cn1 = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("swash.accdb") + ";Persist Security Info=False;");
if (!IsPostBack)
{
cn1.Open();
//fill1();
}
}
protected void btn_Click(object sender, EventArgs e)
{
try
{
string s = null;
if (fu.HasFile)
{
string[] st = fu.PostedFile.ContentType.ToString().Split('/');
if (st[0] == "application")
{
st1 = fu.FileName.ToString().Split('.');
s = "test" + "." + st1[1].ToString();
fu.SaveAs(Server.MapPath("~/upload/" + s));
string t = Server.MapPath("~/upload/" + s);
if (st1[1].ToString().Trim() == "xlsx".Trim())
cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + t + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"");
else
cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + t + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"");
fill();
ViewState["dt"] = st1[0].ToString();
}
else
ClientScript.RegisterStartupScript(GetType(), "x", "");
create trigger tr123 on G for insert,delete
as
begin
insert into G1 select id,name,getdate(),'INSERT' FROM inserted
insert into G1 select id,name,getdate(),'DELETE' FROM deleted
end
create trigger tr456 on G after update
as
begin
if update(name)
begin
insert into G1 select id,name,getdate(),'NEW' FROM inserted
insert into G1 select id,name,getdate(),'OLD' FROM deleted
end
end
create procedure pp456
AS
create table #tb
(
ID INT,
NAME VARCHAR(50),
SAL MONEY,
TA MONEY,
ROW INT
)
DECLARE @id int,@name varchar(50),@sal money,@c cursor
BEGIN
set nocount on
set @c=cursor for select ID,NAME,SAL FROM B
open @c
fetch next from @c into @id,@name,@sal
while @@fetch_status=0
begin
insert into #tb values(@id,@name,@sal,(@sal*.1),@@CURSOR_ROWS)
fetch next from @c into @id,@name,@sal
end
CLOSE @C
DEALLOCATE @C
select * from #tb
drop table #tb
set nocount off
END EXECUTE OF THE PROCEDURE
exec pp456
create procedure pp123
(
@ID INT,
@NAME varchar(50),
@MARK INT
)
AS
BEGIN
set nocount on
if @MARK=1
INSERT INTO emp VALUES(@ID,@NAME)
ELSE IF @MARK=2
UPDATE emp SET NAME=@NAME WHERE ID=@ID
ELSE IF @MARK=3
DELETE FROM emp WHERE ID=@ID
ELSE IF @MARK=4
SELECT * FROM emp
set nocount off
END EXECUTE OF THE PROCEDURE
exec pp123(1,'siv')
If a function return a table then that function is called table value function
create function fxemp1(@sd datetime,@ed datetime)returns @tb table(cdate datetime,weekdate varchar(50))
as
begin
declare @s varchar(50)
while (@ed>=@sd)
begin
if(datepart(dw,@sd))=1
set @s='S'
else if(datepart(dw,@sd))=2
set @s='M'
else if(datepart(dw,@sd))=3
set @s='T'
else if(datepart(dw,@sd))=4
set @s='W'
else if(datepart(dw,@sd))=5
set @s='Th'
else if(datepart(dw,@sd))=6
set @s='F'
else if(datepart(dw,@sd))=7
set @s='St'
set @s=convert(varchar(2),day(@sd))+' '+@s
insert into @tb values(@sd,@s)
set @sd=dateadd(day,1,@sd)
end
return
end execute the function
select * from dbo.fxemp1('2012-jan-1','2012-jan-31')
If a function return a value then that function is called scalar value function
create function fxemp(@cdate datetime)returns varchar(50)
as
begin
return replace(convert(varchar(50),@cdate,106),' ','-')
end
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List x = new List()
{
new emp{ EID=1, NAME="siv", MGR=0, SALARY=5000,DID=1},
new emp{ EID=2, NAME="sankar", MGR=1, SALARY=4000,DID=2},
new emp{ EID=3, NAME="mahadev", MGR=2, SALARY=3000,DID=3},
new emp{ EID=4, NAME="ram", MGR=1, SALARY=2000,DID=5}
};
List y = new List()
{
new dept{ DID=1, DNAME="A"},
new dept{ DID=2, DNAME="B"},
new dept{ DID=3, DNAME="C"},
new dept{ DID=4, DNAME="D"}
};
List z = new List()
{
new salgrade{ LOWSAL=1, HISAL=1000, RANK=1},
new salgrade{ LOWSAL=1001, HISAL=2000, RANK=2},
new salgrade{ LOWSAL=2001, HISAL=3000, RANK=3},
new salgrade{ LOWSAL=3001, HISAL=4000, RANK=4},
new salgrade{ LOWSAL=4001, HISAL=5000, RANK=5}
};
var m = from a in x select a;
var m = from a in x where a.SALARY>=3000 select a;
var m = from a in x where a.SALARY==4000 && a.NAME=="sankar" select a;
var m = from a in x where a.SALARY>=4000 || a.NAME=="sankar" select a;
var m = from a in x where a.NAME!="sankar" select a;
var m = from a in x orderby a.SALARY ascending select a;
var m = from a in x group a by a.DID into b where b.Count() > 1 select new {b.Key,n=b.Count() };
var m = from a in x where a.SALARY < x.Max(b => b.SALARY) select a;
var m = from a in x where a.SALARY > x.Min(b => b.SALARY) select a;
var m = from a in x select new {a.EID,a.NAME,Sumsallary=x.Sum(b=>b.SALARY) };
var m=from a in x
from b in y
where a.DID == b.DID
select new {a.EID,a.NAME,b.DID,b.DNAME};
var m=from a in x
from b in y
from c in z
where a.DID == b.DID && (a.SALARY >= c.LOWSAL && a.SALARY <= c.HISAL)
select new {a.EID,a.NAME,a.SALARY,b.DNAME,c.RANK};
var m = from a in x
from b in y
where 1==1
select new { a.EID, a.NAME, b.DNAME };
var m=from a in x
from b in y
from c in z
where a.DID == b.DID && (a.SALARY >= c.LOWSAL && a.SALARY <= c.HISAL)
select new {a.EID,a.NAME,a.SALARY,b.DNAME,c.RANK};
var m =from a in x
join b in y on a.DID equals b.DID into c
from b in c.DefaultIfEmpty()
select new {a.EID,a.NAME,DNAME=(b==null?null:b.DNAME)};
var m=from a in y
join b in x
on a.DID equals b.DID
into c
from b in c.DefaultIfEmpty()
where b == null
select a;
var m=from a in x
join b in x
on a.MGR equals b.EID
select new { mark = a.NAME + " is working under " + b.NAME };
gv.DataSource = m;
gv.DataBind();
}
class emp
{
public int EID
{
get;
set;
}
public string NAME
{
get;
set;
}
public int MGR
{
get;
set;
}
public decimal SALARY
{
get;
set;
}
public int DID
{
get;
set;
}
}
class dept
{
public int DID
{
get;
set;
}
public string DNAME
{
get;
set;
}
}
class salgrade
{
public decimal LOWSAL
{
get;
set;
}
public decimal HISAL
{
get;
set;
}
public int RANK
{
get;
set;
}
}
}
select len('siv')
select upper('siv')
select lower('SIV')
select day(getdate())
select month(getdate())
select year(getdate())
select DATEADD(DAY,1,GETDATE())
select DATEDIFF(DAY,GETDATE(),DATEADD(DAY,1,GETDATE()))
select DATEPART(DW,GETDATE())
select DATEADD(mi,1,GETDATE())
select convert(varchar(50),getdate(),103)
select replace(convert(varchar(50),getdate(),106),' ','-')
select charindex('%','siv%sankar')
select ltrim(' ram')
select rtrim('ram ')
select substring('ram',1,2)
select isnull(mgr,'0') from emp
select * from emp
select * from emp where name='x'
select * from emp where name='x' and eid=2
select * from emp where name='x' or eid=2
select * from emp where name!='x'
select * from emp where name like 'A%'
select * from emp where name like '_i%'
select top 2 * from emp
select * from emp order by sal desc
select distinct sal from emp
select newid(),* from emp
select row_number() over(order by sal desc) RANK,* from emp
select did,count(*) from emp group by did
select did,count(*) from emp group by did having count(*)>1
select *,MARK=case when did=10 then 'siv' when did=20 then 'sankar' else 'mahadev' end from emp
INSERT INTO F SELECT 4,'d' union select 5,'e' union select 6,'f'
select * from emp join dept on emp.did=dept.did
select * from emp left join dept on emp.did=dept.did
select * from emp right join dept on emp.did=dept.did
select * from emp full join dept on emp.did=dept.did
select * from emp cross join dept
select dname from emp join dept on emp.did=dept.did
select dname from emp right join dept on emp.did=dept.did where eid is null
select isnull(m.name,'')+' is working under '+isnull(t.name,'') from emp m join emp t on m.mgr=t.eid
select isnull(m.name,'')+' is working under '+isnull(t.name,'') from emp m gight join emp t on m.mgr=t.eid where m.name is null
select isnull(m.name,'')+' is working under '+isnull(t.name,'') from emp m left join emp t on m.mgr=t.eid where t.name is null
select * from emp where mgr=(select eid from emp where name='x')
select max(sal) from emp where sal<(select max(sal) from emp where sal<(select max(sal) from emp))
update f set name=(select name from ff where id=f.id) where id!=2
Saturday, 7 January 2012Source Code of the Free ASP.NET QuickTimePlayer Control
Playing QuickTime movies from an ASP.NET Web form can be a little tricky. At first it may not seem difficult, but there are a lot of little details to worry about — such as browser differences, ActiveX activation, and the list of acceptable parameters. The QuickTimePlayer control detailed here (and shown in Figure 1) takes care of all those issues, reducing the task to drag-and-drop simplicity.
Figure 1: The QuickTimePlayer control eliminates the chores involved with playing QuickTime movies.
How to Use It
The QuickTimePlayer.dll can be added to your Visual Studio toolbox via right-click just like any other control (see end of article for download details). When that task is done, it can be dragged from the toolbox onto any ASP.NET Web form, where a definition similar to this will be rendered to the ASPX:
The source code for this article is available for download here.
If you dont have QuickTimePlayer control you can download it from following url:
Since this is a continuation of my previous example then I'm jus going to use the same layout and extend it a bit by adding some buttons on the form and a label control for displaying some message. Aside from that I have also moved the form fields inside a Panel control for validation purposes and removed the ReadOnly attribute for each TextBox. Here's the updated mark-up below:
--Select--
First Name:
Last Name:
Contact Number:
STEP 3: Editing and Updating the Form
Add the following method below in the UserManager class:
public void UpdateUser(UserDetail userDetail) {
var user = (from o in dre.SysUsers
where o.SysUserID == userDetail.SysUserID
select o).First();
user.FirstName = userDetail.FirstName;
user.LastName = userDetail.LastName;
user.ContactNumber = userDetail.ContactNumber;
dre.SaveChanges();
}
The UpdateUser() is a method that handles the updating of data. This method take the UserDetail as the parameter. If you can still remember in my previous example particularly in STEP 2, the UserDatail is a class that holds some properties such as the SysUserID, FirstName, LastName and ContactNumber.
The first line within the method is we queried the SysUser object based on the userID using LINQ syntax and assigned the result into a variable user. The FirstOrDefault function is an eager function which returns the first element of a sequence that satisfies a specified condition. Once the LINQ FirstOrDefault function is invoked then EF will autmatically issue a parameterize SQL query to the database in which the SQL Server can understand and then bring back the result to the Entity Model.
After querying the data we then assign a new value to each field and then call SaveChanges() method to update the database with the changes.
Now let's go to the code behind part of the webform and perform the update by calling the method UpdateUser() from the UserManager class. Here are the code blocks below:
The ToggleButton() method is a method that returns a boolean type which is responsible for toggling the visibility of each buttons in the form during Edit,Update,cancel and Delete mode.
The UpdateUserDetail() is a method that takes UserDetail as the parameter. This method is the one who calls the UpdateUser() method from the UserManager class.
At btnUpdate_Click event we create an instance of the UserDetail class and assign the values from the form to the corresponsing fields. After that we call the method UpdateUserDetail() and pass the UserDetail object as the parameter.
Here's the output below when running it on the browser:
On initial load:
After selecting an item from the DropDownList
On Edit Mode (after clicking the edit button)
After Update
STEP 4: Deleting data from the Form
Now lets implement the deletion part of the program. In the UserManager class add this method below:
public void DeleteUser(int userID) {
var user = (from o in dre.SysUsers
where o.SysUserID == userID
select o).First();
dre.DeleteObject(user);
dre.SaveChanges();
}
Just like the UpdateUser() method. We query the SysUser object based on the SysUserID and then assign the result in the variable user. After that we call the DeleteObject() to perform delete and then call the SaveChanges() method to reflect the changes to the database.
Here's the code in the code behind for the deletion:
//Perform the Delete
UserManager userMgr = new UserManager();
userMgr.DeleteUser(Convert.ToInt32(ddlUser.SelectedItem.Value));
//Re-bind the DropDownList
ddlUser.Items.Clear();
BindUserNames();
//Clear the form fields
tbFirstName.Text = string.Empty;
tbLastName.Text = string.Empty;
tbContactNumber.Text = string.Empty;
lblMessage.Text = "Delete Successful!";
}
else {
lblMessage.Text = "Please select name from the list first.";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
}
Since we don’t want users to delete the information right away, we need to prompt them a confirmation message if they wish to continue the deletion or not. To do this we could simply hook up the javascript confirm function in the delete button. Take a look at the highlighted code below:
Here's the output below when running the page and perform the delete:
This article will help you to create a simple WPF application to bind data in datagrid using SQL Server Compact 3.5 sp1 as data source. In this article, I would like to show the simple way of data binding to datagrid in WPF.
In this article, I have used Visual Studio 2010 to demonstrate the example. Below find the steps to create new WPF project.
Create New WPF Project
Step 1: Click Start All Program à Microsoft Visual Studio 2010 à Microsoft Visual Studio 2010
Step 2: Click “New Project”
Step 3: Under “Visual C#” à Windows à WPF Application
Give application name for your new WPF applications, mention the location and solution name.
Start Designing and Programming using WPF
Designing windows or web application is quite easy and interesting also. Let’s start designing our first application using WPF.
WPF will generate XAML tags similar to HTML. Here I have used the below mentioned tools for design:
Datagrid1
Databinding to “Datagrid1” in WPF is simple, in this example, I have used ADO.NET for binding.
<
/datagridtextcolumn>
We can bind the data to datagrid by assigning it to datagrid’s “ItemsSource” and mention the data path which will connect to database to get the data. This is an add on feature in WPF.
App.config is a configuration file which will have the setting and other stuff for an application. Here, I have used this to store the database connectionstring and it is as follows:
Here, I have used SQL Server Compact 3.5 sp1 as my data source so we have to give the exact path of the database file where it is stored. (Note: You need to give exact path of the database file to make this code work).
Whenever we add, delete, update datagrid has to be changed accordingly, so I created a public method named “BindGrid()”.
public void BindGrid()
{
SqlCeConnection _Conn = new SqlCeConnection(_ConnectionString);
// Open the Database Connection
_Conn.Open();
SqlCeDataAdapter _Adapter = new SqlCeDataAdapter("Select * from Details", _Conn);
DataSet _Bind = new DataSet();
_Adapter.Fill(_Bind, "MyDataBinding");
dataGrid1.DataContext = _Bind;
// Close the Database Connection
_Conn.Close();
}
In the above, I have shown a very simple way to get the SQL connection string which will connect to database and used dataset to bind the data to datagrid. The below code will add new record using the values from the textbox.
Add New Record
To add new record on database, I had used simple insert query and it will be populated in the datagrid. The below will do the trick:
To confirm that a record has been added, I have a messagebox with the message “One Record Inserted” and once you click “Ok”, you should see the added record to be listed in datagrid (refer to the below image).
To update the existing data, just double click on the record on the datagrid and the values will be edited, will be listed in their respective textboxes as shown in the below image:
The below code will perform editing the datagrid value:
DataRowView _DataView = dataGrid1.CurrentCell.Item as DataRowView;
Here I have used “DataRowView” to read the currentcell of the datagrid and fetch each cell value and have assigned it to a textbox.
You can’t change the first name as we are using its value as primary key in the database, so you can change on the other available fields. In this example, I have changed the last name to “Sellamuthu”.
code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlServerCe;
using System.Configuration;
using System.Data;
namespace ShibashishWpfApp
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
string _ConnectionString = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
string Query;
SqlCeDataAdapter da;
SqlCeConnection con;
DataSet ds;
SqlCeCommand cmd;
private void Add_Btn_Click(object sender, RoutedEventArgs e)
{
insertData();
clearData();
}
public void common()
{
con = new SqlCeConnection(_ConnectionString);
con.Open();
code:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication2
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
#region
ArrayList al = new ArrayList();
Database1Entities o = new Database1Entities();
int i,j;
string s,ss;
#endregion
private void Window_Loaded(object sender, RoutedEventArgs e)
{
view();
al.Add("--------Select--------");
al.Add("What is ur name?");
al.Add("What is ur vabority movie?");
al.Add("What is ur vabority game?");
al.Add("What is ur vabority place?");
for (i = 0; i < al.Count; i++)
comboBox1.Items.Add(al[i].ToString());
comboBox1.SelectedIndex = 0;
listBox1.Items.Add("Cricket");
listBox1.Items.Add("Hockey");
listBox1.Items.Add("Football");
listBox1.Items.Add("Baseball");
}
void view()
{
var m = from x in o.EMP1 select new {x.EID,x.NAME,x.ADDRESS,x.SEX,x.DOB,x.HOBBY,x.INTEREST,x.QUESTION,x.PASSWORD};
dataGrid1.ItemsSource = m;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
s=string.Empty;
ss=string.Empty;
if (radioButton1.IsChecked==true)
s = radioButton1.Content.ToString();
else
s = radioButton2.Content.ToString();
if (checkBox1.IsChecked==true)
ss =ss+ checkBox1.Content.ToString()+" ";
if(checkBox2.IsChecked==true)
ss = ss + checkBox2.Content.ToString() + " ";
if (checkBox3.IsChecked == true)
ss = ss + checkBox3.Content.ToString() + " ";
if (checkBox4.IsChecked == true)
ss = ss + checkBox4.Content.ToString() + " ";
o.EMP2(textBox1.Text, textBox2.Text, s, Convert.ToDateTime(datePicker1.SelectedDate), ss, listBox1.SelectedItem.ToString(), comboBox1.SelectedItem.ToString(), passwordBox1.Password.ToString());
o.SaveChanges();
view();
}
}
}
To get started then lets go ahead and fire up Visual Studio 2008 and create a new WebSite by selecting File > New WebSite.
STEP 2: Adding a DBML file
Since we are going to use L2S then we need to add .dbml file. To do this, just right click on the application root and select Add New Item. On the template select LINQ to SQL Classes file. See below screen shot:
Now rename your dbml file the way you want it and then click OK. Note that I’m using the Northwind database for this demo and on that case I renamed the dbml file to Northwind to make it friendlier.
Now open up server explorer in Visual Studio and browse the database that you wan’t to work on (in this case the Northwind database). Just for the purpose of this example I’m going to use the Customers table from the northwind database and drag it to the Northwind.dbml design surface. See the screen shot below:
That’s simple! Isn’t it?
What happens there is that by time you drag a table in the design surface, L2S will automatically generates the Business object for you within the DataContext and let you query against it.The DataContext is the main gateway by which you retrieve objects from the database and resubmit changes. You use it in the same way that you would use an ADO.NET Connection. In fact, the DataContext is initialized with a connection or connection string you supply. The purpose of the DataContext is to translate your requests for objects into SQL queries made against the database and then assemble objects out of the results. The DataContext enables language-integrated query by implementing the same operator pattern as the standard query operators such as Where and Select
STEP 3: Setting up the GUI
Now let’s go ahead and create our form for data entry. For the simplicity of this demo, I just set up the form like below: