//Take one Grid View and Bind all Column and take column inside templatefiels inside ItemTemplate and EditItemTemplate ALSO FOR Generate text box for updation
I have remove starting tag from the Html Tag because blog can't take Html field like Starting tag .....
asp:Label ID="lblId" runat="server" Visible="false" Text='%# Bind("Id") %>'>/asp:Label>
//Web.config file
add name="Master" connectionString ="Data Source=.;user id=; password=; database=Master; "/>
//aspx.cs
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master"].ConnectionString);
SqlDataAdapter adp;
DataSet ds; SqlCommand cmd;
void fillgridview()
{
adp = new SqlDataAdapter("Select a.id,a.Name,a.Age,a.RollNo,b.Subject from student a join subject b on a.subjectid=b.subjectid", con);
ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
else { }
ds.Dispose();
adp = null;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgridview();
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
con.Open();
cmd = new SqlCommand("delete from student where id= " + lbnlid.Text + " ", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
fillgridview();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
con.Open();
cmd = new SqlCommand("update student set Name= '"+txtName.Text +"' where id= "+lbnlid.Text+" ", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
fillgridview();
}
Saturday, March 27, 2010
Disable Browser back Button in asp.net
//Make one .js file
function goNewWin()
{
window.open("default2.aspx",'TheNewpop','toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1');
self.close()
}
//Call that function and give the page name there which page you don't want browser back button....
function goNewWin()
{
window.open("default2.aspx",'TheNewpop','toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1');
self.close()
}
//Call that function and give the page name there which page you don't want browser back button....
Gridview sorting,paging
//Take one Grid View and Bind all the column through
//hdnSort is a Hidden field take one hidden field also.
asp:TemplateField
ItemTemplate and give the sort expression also and paging and sorting also true the property of GridView...
//Web.config file
add name="Master1" connectionString ="Data Source=.;user id=; password=; database=Master; "/>
//in aspx.cs
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master1"].ConnectionString);
private void bindData(string sorting)
{
DataSet ds;
SqlDataAdapter da;
string sql = null;
ds = new DataSet();
da = new SqlDataAdapter();
try
{
con.Open();
}
catch (Exception ex)
{
}
sql = "Select student_id,last_name,first_name,Score from Student order by " + sorting;
da.SelectCommand = new SqlCommand(sql, con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
if (ds.Tables.Count == 0)
{
//lblMessage.Text = "No record found";
}
}
ds = null;
da = null;
try { con.Close(); }
catch (Exception ex) { }
}
//call Bind Method where you bind the Gridview perform all operation
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindData("student_id");
}
}
//for sorting
private string ConvertSortDirectiontoSql(SortDirection sort)
{
string newSortDirection = string.Empty;
switch (sort)
{
case SortDirection.Ascending:
newSortDirection = "Asc";
hdnSort.Value = "Asc";
break;
case SortDirection.Descending:
newSortDirection = "Desc";
hdnSort.Value = "Desc";
break;
}
return newSortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//hdnSort is a Hidden field take one hidden field also.
if (hdnSort.Value.Length == 0 || hdnSort.Value == "Desc")
e.SortDirection = SortDirection.Ascending;
else
e.SortDirection = SortDirection.Descending;
string sorting = e.SortExpression + " " + ConvertSortDirectiontoSql(e.SortDirection);
if (hdnSort.Value.Length == 0)
hdnSort.Value = "Desc";
bindData(sorting);
}
//for paging
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindData("student_id desc");
}
//hdnSort is a Hidden field take one hidden field also.
asp:TemplateField
ItemTemplate and give the sort expression also and paging and sorting also true the property of GridView...
//Web.config file
add name="Master1" connectionString ="Data Source=.;user id=; password=; database=Master; "/>
//in aspx.cs
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master1"].ConnectionString);
private void bindData(string sorting)
{
DataSet ds;
SqlDataAdapter da;
string sql = null;
ds = new DataSet();
da = new SqlDataAdapter();
try
{
con.Open();
}
catch (Exception ex)
{
}
sql = "Select student_id,last_name,first_name,Score from Student order by " + sorting;
da.SelectCommand = new SqlCommand(sql, con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
if (ds.Tables.Count == 0)
{
//lblMessage.Text = "No record found";
}
}
ds = null;
da = null;
try { con.Close(); }
catch (Exception ex) { }
}
//call Bind Method where you bind the Gridview perform all operation
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindData("student_id");
}
}
//for sorting
private string ConvertSortDirectiontoSql(SortDirection sort)
{
string newSortDirection = string.Empty;
switch (sort)
{
case SortDirection.Ascending:
newSortDirection = "Asc";
hdnSort.Value = "Asc";
break;
case SortDirection.Descending:
newSortDirection = "Desc";
hdnSort.Value = "Desc";
break;
}
return newSortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//hdnSort is a Hidden field take one hidden field also.
if (hdnSort.Value.Length == 0 || hdnSort.Value == "Desc")
e.SortDirection = SortDirection.Ascending;
else
e.SortDirection = SortDirection.Descending;
string sorting = e.SortExpression + " " + ConvertSortDirectiontoSql(e.SortDirection);
if (hdnSort.Value.Length == 0)
hdnSort.Value = "Desc";
bindData(sorting);
}
//for paging
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindData("student_id desc");
}
Fill GridView
//Web.Config File Connection String
add name="Master1" connectionString ="Data Source=.;user id=; password=; database=Master; "/>
//aspx.cs
//Bind Function and call that function where you want..
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master1"].ConnectionString);
private void bindData()
{
DataSet ds;
SqlDataAdapter da;
string sql = null;
ds = new DataSet();
da = new SqlDataAdapter();
try
{
con.Open();
}
catch (Exception ex)
{
}
sql = "Select student_id,last_name,first_name,Score from Student ;
da.SelectCommand = new SqlCommand(sql, con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
if (ds.Tables.Count == 0)
{
//lblMessage.Text = "No record found";
}
}
ds = null;
da = null;
try { con.Close(); }
catch (Exception ex) { }
}
add name="Master1" connectionString ="Data Source=.;user id=; password=; database=Master; "/>
//aspx.cs
//Bind Function and call that function where you want..
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Master1"].ConnectionString);
private void bindData()
{
DataSet ds;
SqlDataAdapter da;
string sql = null;
ds = new DataSet();
da = new SqlDataAdapter();
try
{
con.Open();
}
catch (Exception ex)
{
}
sql = "Select student_id,last_name,first_name,Score from Student ;
da.SelectCommand = new SqlCommand(sql, con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
if (ds.Tables.Count == 0)
{
//lblMessage.Text = "No record found";
}
}
ds = null;
da = null;
try { con.Close(); }
catch (Exception ex) { }
}
Disable Mouse Right click over the .aspx page
//jscript.js file
var BM = 2; // button middle
var BR = 3; // button right
function mouseDown(e)
{
try { if (event.button==BM||event.button==BR) {return false;} }
catch (e) { if (e.which == BR) {return false;} }
}
document.oncontextmenu = function() { return false; }
document.onmousedown = mouseDown;
//page source code(Add .js file in page automatically handle the right click)
script src="JScript.js" type="text/javascript" language="javascript" />
var BM = 2; // button middle
var BR = 3; // button right
function mouseDown(e)
{
try { if (event.button==BM||event.button==BR) {return false;} }
catch (e) { if (e.which == BR) {return false;} }
}
document.oncontextmenu = function() { return false; }
document.onmousedown = mouseDown;
//page source code(Add .js file in page automatically handle the right click)
script src="JScript.js" type="text/javascript" language="javascript" />
Friday, March 26, 2010
What are cursors? Explain different types of cursors and Disadvantage of cursor?
Cursors allow row-by-row processing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one roundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Further, there are restrictions on the SELECT statements that can be used with some types of cursors. Most of the times, set based operations can be used instead of cursors. Here is an example: If you have to give a flat hike to your employees using the following criteria: Salary between 30000 and 40000 — 5000 hike Salary between 40000 and 55000 — 7000 hike Salary between 55000 and 65000 — 9000 hike. In this situation many developers tend to use a cursor, determine each employee’s salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:
UPDATE tbl_emp SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000 WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000 END
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one roundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Further, there are restrictions on the SELECT statements that can be used with some types of cursors. Most of the times, set based operations can be used instead of cursors. Here is an example: If you have to give a flat hike to your employees using the following criteria: Salary between 30000 and 40000 — 5000 hike Salary between 40000 and 55000 — 7000 hike Salary between 55000 and 65000 — 9000 hike. In this situation many developers tend to use a cursor, determine each employee’s salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:
UPDATE tbl_emp SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000 WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000 END
What are the steps you will take to improve performance of a poor performing query?
Some general issues that you could talk about would be: No indexes, excess recompilations of stored procedures, procedures and triggers , poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables.
What are constraints? Explain different types of constraints
...Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults. Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY.
What’s the difference between DELETE TABLE and TRUNCATE TABLE commands?
.....DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won’t log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back. TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE. The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log. TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
Index in sql server
//Important thing to note: By default a clustered index gets created on the primary key
and where are unique creates a nonclustered index by default
CREATE clusteredINDEX myIndex ON myTable(myColumn)
and where are unique creates a nonclustered index by default
CREATE clusteredINDEX myIndex ON myTable(myColumn)
Labels:
Index in sql server
Define candidate key, alternate key, composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key.
//link for Composite key understand
http://weblogs.sqlteam.com/jeffs/archive/2007/08/23/composite_primary_keys.aspx
//link for Composite key understand
http://weblogs.sqlteam.com/jeffs/archive/2007/08/23/composite_primary_keys.aspx
Labels:
alternate key,
composite key.,
Define candidate key
What’s the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.
Thursday, March 25, 2010
Access view state value in another page
//Find out the view state value in another page but you can find only Init and page load event and only redirect on another page Server.Transfer than you can get the value otherwise it will give error to you...
//first page
take one text box with name of textbox1.text and fill the value of text box.....
//second page init and load event
Page Poster = this.PreviousPage;
TextBox txtNewTest = (TextBox)Poster.FindControl("TextBox1");
string sDisplay = txtNewTest.Text;
Response.Write(sDisplay);
//first page
take one text box with name of textbox1.text and fill the value of text box.....
//second page init and load event
Page Poster = this.PreviousPage;
TextBox txtNewTest = (TextBox)Poster.FindControl("TextBox1");
string sDisplay = txtNewTest.Text;
Response.Write(sDisplay);
Wednesday, March 24, 2010
Update Statement for converting male to female and female to male
Update tablename set gender=(case, when gender='Male' then 'Female' else 'Male' end)
Monday, March 22, 2010
Instead of Trigger for Update
//Instead of triger will fired when user ant to update in emp table
create trigger tri_update on Emp
for update
as
begin
if update(ID)
begin
print'not update here'
rollback transaction
end
end
create trigger tri_update on Emp
for update
as
begin
if update(ID)
begin
print'not update here'
rollback transaction
end
end
Labels:
Instead of Trigger for Update
Sunday, March 21, 2010
Randam Number Concatenate two string with insert the data in table
Create a table it has two column one is int type and another is varchar
string randomnumber()
{
SqlDataAdapter adp = new SqlDataAdapter("Select max(empid) as empid from emp1 ", con);
DataSet ds = new DataSet();
adp.Fill(ds);
string i="";
if (ds.Tables[0].Rows.Count > 0)
{
i = ds.Tables[0].Rows[0]["empid"].ToString();
}
if (i == "")
{
i = "0";
}
//i=i.Remove(0, 3);
i = (int.Parse(i) + 1).ToString();
if (i.Length == 2)
{
i = "OCG0" + i;
}
else if (i.Length == 1)
{
i = "OCG00" + i;
}
else if (i.Length > 2)
{
i = "OCG" + i;
}
return i;
}
int randomnumber1()
{
SqlDataAdapter adp = new SqlDataAdapter("Select max(empid) as empid from emp1 ", con);
DataSet ds = new DataSet();
adp.Fill(ds);
int i = 0;
if (ds.Tables[0].Rows.Count > 0)
{
i = Convert.ToInt32( ds.Tables[0].Rows[0]["empid"].ToString());
}
if (i.ToString() == "")
{
i = 0;
}
i = i + 1;
return i;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void btns_Click(object sender, EventArgs e)
{
SqlCommand com = new SqlCommand();
ListBox1.Items.Add(randomnumber().ToString());
con.Open();
com.CommandText = "insert into emp1 (empid,EMPCODE) values ("+randomnumber1()+" ,'" + randomnumber().ToString() +"')";
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
string randomnumber()
{
SqlDataAdapter adp = new SqlDataAdapter("Select max(empid) as empid from emp1 ", con);
DataSet ds = new DataSet();
adp.Fill(ds);
string i="";
if (ds.Tables[0].Rows.Count > 0)
{
i = ds.Tables[0].Rows[0]["empid"].ToString();
}
if (i == "")
{
i = "0";
}
//i=i.Remove(0, 3);
i = (int.Parse(i) + 1).ToString();
if (i.Length == 2)
{
i = "OCG0" + i;
}
else if (i.Length == 1)
{
i = "OCG00" + i;
}
else if (i.Length > 2)
{
i = "OCG" + i;
}
return i;
}
int randomnumber1()
{
SqlDataAdapter adp = new SqlDataAdapter("Select max(empid) as empid from emp1 ", con);
DataSet ds = new DataSet();
adp.Fill(ds);
int i = 0;
if (ds.Tables[0].Rows.Count > 0)
{
i = Convert.ToInt32( ds.Tables[0].Rows[0]["empid"].ToString());
}
if (i.ToString() == "")
{
i = 0;
}
i = i + 1;
return i;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void btns_Click(object sender, EventArgs e)
{
SqlCommand com = new SqlCommand();
ListBox1.Items.Add(randomnumber().ToString());
con.Open();
com.CommandText = "insert into emp1 (empid,EMPCODE) values ("+randomnumber1()+" ,'" + randomnumber().ToString() +"')";
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
Friday, March 19, 2010
Store image in DataBase and Display in Gridview and picture box
//Cretate table in sql server "storeimage"
Create table storeimage(
name varchar(100),
pics image)
//code in .Net
byte[] ReadFile(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
SqlConnection con = new SqlConnection("Data source=.;Database=master;user id=;password=; integrated security=sspi;");
SqlCommand cmd;
private void Form1_Load(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("SElect * from storeimage", con);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
byte[] imageData;
imageData = ReadFile(textBox1.Text);
cmd = new SqlCommand("Insert into storeimage(name,pics) values('s' ,@OriginalPath)", con);
cmd.Parameters.Add(new SqlParameter("@OriginalPath", (object)imageData));
cmd.ExecuteNonQuery();
con.Close();
}
private void btnbrowse_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >0)
{
object a = dataGridView1.Rows[e.RowIndex].Cells["Pics"].GetType();
if (a.ToString() != "System.DBNull")
{
byte[] imageData = (byte[])dataGridView1 .Rows[e.RowIndex].Cells["pics"].Value;
imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["pics"].Value;
Image newImage;
using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
{
ms.Write(imageData, 0, imageData.Length);
newImage = Image.FromStream(ms, true);
}
//set picture
pictureBox1.Image = newImage;
}
}
}
Create table storeimage(
name varchar(100),
pics image)
//code in .Net
byte[] ReadFile(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
SqlConnection con = new SqlConnection("Data source=.;Database=master;user id=;password=; integrated security=sspi;");
SqlCommand cmd;
private void Form1_Load(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("SElect * from storeimage", con);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
byte[] imageData;
imageData = ReadFile(textBox1.Text);
cmd = new SqlCommand("Insert into storeimage(name,pics) values('s' ,@OriginalPath)", con);
cmd.Parameters.Add(new SqlParameter("@OriginalPath", (object)imageData));
cmd.ExecuteNonQuery();
con.Close();
}
private void btnbrowse_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >0)
{
object a = dataGridView1.Rows[e.RowIndex].Cells["Pics"].GetType();
if (a.ToString() != "System.DBNull")
{
byte[] imageData = (byte[])dataGridView1 .Rows[e.RowIndex].Cells["pics"].Value;
imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["pics"].Value;
Image newImage;
using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
{
ms.Write(imageData, 0, imageData.Length);
newImage = Image.FromStream(ms, true);
}
//set picture
pictureBox1.Image = newImage;
}
}
}
Thursday, March 18, 2010
Types of Classes
We have two types of classes..
1) Factory 2) Singleton
1) Factory : You can create a multiple object of factory class.
2) Singleton : only one instance of the class is created ex..Mouse Pointer,window popup.
//singleton programme
using system;
public class singleton
{
private static singleton instance;
private singleton()
{
}
public static singleton instance
{
get
{
if(instance==null)
{
instance=new singleton();
}
return instance;
}
}
}
1) Factory 2) Singleton
1) Factory : You can create a multiple object of factory class.
2) Singleton : only one instance of the class is created ex..Mouse Pointer,window popup.
//singleton programme
using system;
public class singleton
{
private static singleton instance;
private singleton()
{
}
public static singleton instance
{
get
{
if(instance==null)
{
instance=new singleton();
}
return instance;
}
}
}
Labels:
Types of Classes
Difference Between function and procedure in sqlserver
1)Function returns a value, but a procedure may return or may not return a value.
2)Function can take only input argument, but procedure may take both input and output parameters.
3)Function can be called inside the select statement but not the procedure
4)Function return 1 value only. Procedure can return multiple value.
5)Function are compiled and executed at runtime.Stored Procedure are stored in parsed and compiled format in the DataBase.
6)Function cannot affect the state of the database which means it cannot perform insert,update,delete and create operation on the database.
Stored procedure can affect the state of the database by using Insert,delete,update and create operation.
2)Function can take only input argument, but procedure may take both input and output parameters.
3)Function can be called inside the select statement but not the procedure
4)Function return 1 value only. Procedure can return multiple value.
5)Function are compiled and executed at runtime.Stored Procedure are stored in parsed and compiled format in the DataBase.
6)Function cannot affect the state of the database which means it cannot perform insert,update,delete and create operation on the database.
Stored procedure can affect the state of the database by using Insert,delete,update and create operation.
Number of user visit to your Website
//Take global.asax for make application level variable
void application_start(object sender,Eventargs e)
{
int count=convert.int32(application["hit"]);
count=0;
}
void session_start(object sender,eventargs e)
{
int count=convert.toint32(application["hit"]);
count=count+1;
application["hit"]=count;
}
//pageload
label1.text=convert.toint32(application["hit"]).tostrng();
void application_start(object sender,Eventargs e)
{
int count=convert.int32(application["hit"]);
count=0;
}
void session_start(object sender,eventargs e)
{
int count=convert.toint32(application["hit"]);
count=count+1;
application["hit"]=count;
}
//pageload
label1.text=convert.toint32(application["hit"]).tostrng();
Theme Asp.Net
//Take one dropdownlist insert the name of skin file (through collection or create the masters of themes)
Default
skinfile
Changetheme
BasicBlue
//page_preInit Event because theme work on preinit event
protected void page_PreInit(object Sender,EventArgs e)
{
string theme="";
if(page.request.form.count>0)
{
theme=page.request["Theme"].tostring();// Theme is the id of dropdown
if(theme=="Defaule")
{
theme="";
}
}
this.Theme=theme;
}
//page_preInit Event because theme work on preinit event
protected void page_PreInit(object Sender,EventArgs e)
{
string theme="";
if(page.request.form.count>0)
{
theme=page.request["Theme"].tostring();// Theme is the id of dropdown
if(theme=="Defaule")
{
theme="";
}
}
this.Theme=theme;
}
Asp.net page life cycle.
1)Init : When the page is instantiated.
2)Load : When the page is loaded into server memory.
3)Render : The brief moment before the page is displayed to the user as Html.
4)Unload : When page finish loading.
2)Load : When the page is loaded into server memory.
3)Render : The brief moment before the page is displayed to the user as Html.
4)Unload : When page finish loading.
Labels:
Asp.net page life cycle.
File Upload in Asp.net c#
//Take one file upload control and one button for save the file..
//button click
if(fileupload1.hasfile)
{
fileupload1.saveas(server.mappath(fileupload1.filename));
label1.text="file uploaded :" + fileupload1.filename;
}
else
{
label1.text="No file Upload";
}
//button click
if(fileupload1.hasfile)
{
fileupload1.saveas(server.mappath(fileupload1.filename));
label1.text="file uploaded :" + fileupload1.filename;
}
else
{
label1.text="No file Upload";
}
Labels:
File Upload in Asp.net c#
State Management
State Management is the process by which you maintain state and page information over multiple request for the same or different pages.
There are two types of state management..1) Client side
2) Server Side
Client Side : The store information on the client's computer by embedding the information into a webpage, a URL , or a Cookies ..The technique available to store the state information at the client end are listed down below..
a) View State: maintain the control state and retain the value of control.
b) Hidden field
c)Cookies: we have two types of cookies 1) persist: by default data has saved in persist cookies. and 2) NonPersist Cookies: By default data has lost in nonpersist cookies.
d) querystring: query string store value appended in the url that are visible to the user.maximum limit of query string is 255 character.
ServerSide State Management : Any data resides on the server and backand data base that's called in server side.
Two types of serverside state management: 1)Application State: Application state globaly for all user ..you can create global variable in Global.asax..inside the application.start event and session.start event.
2)Session Management : Its also globaly for a particular user...
There are two types of state management..1) Client side
2) Server Side
Client Side : The store information on the client's computer by embedding the information into a webpage, a URL , or a Cookies ..The technique available to store the state information at the client end are listed down below..
a) View State: maintain the control state and retain the value of control.
b) Hidden field
c)Cookies: we have two types of cookies 1) persist: by default data has saved in persist cookies. and 2) NonPersist Cookies: By default data has lost in nonpersist cookies.
d) querystring: query string store value appended in the url that are visible to the user.maximum limit of query string is 255 character.
ServerSide State Management : Any data resides on the server and backand data base that's called in server side.
Two types of serverside state management: 1)Application State: Application state globaly for all user ..you can create global variable in Global.asax..inside the application.start event and session.start event.
2)Session Management : Its also globaly for a particular user...
Labels:
State Management
Caching in Asp.Net
Caching : Caching is a feature of Asp.Net that improves the performance of web application by minimizing the usage of server resources to a greate extent.
Caching is a feature that store data in local memory ,allowing incoming request to be served from memory directly.
Benefits of caching : Faster page rendering.
: Minimizing of database hits.
: Minimizing of the consumption of server resources.
Asp.Net support three types of caching: 1)Page level caching(output caching)
2)Page fragment caching(partial page output
caching)
3)Programmatic or data caching .
Caching is a feature that store data in local memory ,allowing incoming request to be served from memory directly.
Benefits of caching : Faster page rendering.
: Minimizing of database hits.
: Minimizing of the consumption of server resources.
Asp.Net support three types of caching: 1)Page level caching(output caching)
2)Page fragment caching(partial page output
caching)
3)Programmatic or data caching .
Labels:
Caching in Asp.Net
Department Wise sum() of Salary
Select * from emp order by depart desc
compute sum(salary) by depart
compute sum(salary) by depart
Labels:
Department Wise sum() of Salary
Aalgorithm and FlowChart
Flowchart : A flowchart is a graphical representation of an algorithm..
Algorithm : An algorithm is just a detailed sequence of simple steps that are needed to solve a problem.
A formula or set of steps for solving a particular problem to be an algorithm..
Algorithm : An algorithm is just a detailed sequence of simple steps that are needed to solve a problem.
A formula or set of steps for solving a particular problem to be an algorithm..
Labels:
Aalgorithm and FlowChart
Value Type and Reference Type datatype
Value Type : All numeric data type,boolean type,char,Date,enumeration structure..
Reference Type :String,all array,class,delegate
Reference Type :String,all array,class,delegate
DDL,DML in sql server
DDL(Data Defination language): DDL are used to define the database structure or schema...example...Create Table, Alter Table,Drop,Truncate,Comment,Rename..
DML(Data Manipulation Language) : Statement are used to managing data within schema object.. example....Select,Insert,Delete,Update,Merge,Lock data.
DML(Data Manipulation Language) : Statement are used to managing data within schema object.. example....Select,Insert,Delete,Update,Merge,Lock data.
Labels:
DDL,
DML in sql server
Saturday, March 13, 2010
Insert only Numeric value in textbox
//Js Code
function numberValidation(txtbx,event)
{
var txtbx1=document.getElementById(txtbx);
if((event.keyCode >= 48 && event.keyCode <= 57)||(event.keyCode >= 96 && event.keyCode <= 105)||(event.keyCode == 8 ) ||(event.keyCode == 9) || (event.keyCode == 12) || (event.keyCode == 27) || (event.keyCode == 37) || (event.keyCode == 39) || (event.keyCode == 46) )
{
return true;
}
else
{
alert("Only Numeric Value");
txtbx1.value="";
return false;
}
}
//.cs file (PageLoad)
textbox1.Attributes.Add("onKeyDown", "return numberValidation('" + textbox1.ClientID + "',event);");
function numberValidation(txtbx,event)
{
var txtbx1=document.getElementById(txtbx);
if((event.keyCode >= 48 && event.keyCode <= 57)||(event.keyCode >= 96 && event.keyCode <= 105)||(event.keyCode == 8 ) ||(event.keyCode == 9) || (event.keyCode == 12) || (event.keyCode == 27) || (event.keyCode == 37) || (event.keyCode == 39) || (event.keyCode == 46) )
{
return true;
}
else
{
alert("Only Numeric Value");
txtbx1.value="";
return false;
}
}
//.cs file (PageLoad)
textbox1.Attributes.Add("onKeyDown", "return numberValidation('" + textbox1.ClientID + "',event);");
Primary and Foreign Key
//Priamry Table
create table tbluser(
UserId varchar(50) constraint [UID] primary key not null,
UserName varchar(100) not null)
//Foreign Key Table
create table tblUserPermission(
UserID varchar(50) constraint fkUId foreign key (UserId) references tbluser(UserId) not null)
create table tbluser(
UserId varchar(50) constraint [UID] primary key not null,
UserName varchar(100) not null)
//Foreign Key Table
create table tblUserPermission(
UserID varchar(50) constraint fkUId foreign key (UserId) references tbluser(UserId) not null)
Email Send
using System.Net.Mail;
private void btnSend_Click(object sender, EventArgs e)
{
MailAddress mailTo = new MailAddress(txtAddress.Text);
MailAddress mailFrom = new MailAddress(txtFrom.Text);
MailMessage message = new MailMessage(mailFrom, mailTo);
message.Subject = txtSubject.Text;
message.Body = txtMessage.Text;
message.Priority = MailPriority.High;
SmtpClient c = new SmtpClient("ServerName");
c.Send(message);
}
}
private void btnSend_Click(object sender, EventArgs e)
{
MailAddress mailTo = new MailAddress(txtAddress.Text);
MailAddress mailFrom = new MailAddress(txtFrom.Text);
MailMessage message = new MailMessage(mailFrom, mailTo);
message.Subject = txtSubject.Text;
message.Body = txtMessage.Text;
message.Priority = MailPriority.High;
SmtpClient c = new SmtpClient("ServerName");
c.Send(message);
}
}
Duplicate Value Findout(Sql server)
Select count(*) ,firstname,lastname,depart from emp group by firstname,lastname,depart having count(*)>1
Top 3 Salary
//You can find out top 3 salry.........like
Select Top 1 salary from Emp where salary in(Select Top 3 salary from emp order by salary desc)
Select Top 1 salary from Emp where salary in(Select Top 3 salary from emp order by salary desc)
Friday, March 12, 2010
connectionstring
connectionStrings
add name ="Master1" connectionString ="Data Source=OKH;database=leave; user id =sa; pwd="/
/connectionStrings
add name ="Master1" connectionString ="Data Source=OKH;database=leave; user id =sa; pwd="/
/connectionStrings
Labels:
connectionstring
Fill DropDown
SqlConnection con = new
//Connection String
//Page Load Code here
SqlConnection(ConfigurationManager.ConnectionStrings["Master1"].ConnectionString);
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
cmd = new SqlCommand("Select category_id,category_name from tbl_category order by category_id", con);
adp = new SqlDataAdapter(cmd);
ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
drpCategory1.Items.Add(ds.Tables[0].Rows[i]["Category_Name"].ToString());
drpCategory1.Items[i + 1].Value = ds.Tables[0].Rows[i]["Category_id"].ToString();
}
}
ds.Dispose();
adp=null;
con.Close();
}
}
//Connection String
//Page Load Code here
SqlConnection(ConfigurationManager.ConnectionStrings["Master1"].ConnectionString);
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
cmd = new SqlCommand("Select category_id,category_name from tbl_category order by category_id", con);
adp = new SqlDataAdapter(cmd);
ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
drpCategory1.Items.Add(ds.Tables[0].Rows[i]["Category_Name"].ToString());
drpCategory1.Items[i + 1].Value = ds.Tables[0].Rows[i]["Category_id"].ToString();
}
}
ds.Dispose();
adp=null;
con.Close();
}
}
Work with RSS
protected void Page_Load(object sender, EventArgs e)
{
Response.AppendHeader("refresh", "10");
// XmlTextReader reader = new XmlTextReader("http://cricket.ndtv.com/cricket/ndtvcricket/rssnews/ndtv/cat/news/rss.html");
DataSet ds = new DataSet();
ds.ReadXml(reader);
GridView1.DataSource = ds.Tables[3];
GridView1.DataBind();
}
{
Response.AppendHeader("refresh", "10");
// XmlTextReader reader = new XmlTextReader("http://cricket.ndtv.com/cricket/ndtvcricket/rssnews/ndtv/cat/news/rss.html");
DataSet ds = new DataSet();
ds.ReadXml(reader);
GridView1.DataSource = ds.Tables[3];
GridView1.DataBind();
}
Validate the contorl in java script
function Validate()
{
if (document.getElementById("Name").value == "") //"Name" == it is a control Id
{
alert("Please enter name");
return false;
}
if (document.getElementById("address").value == "")
{
alert("Please enter Address");
return false;
}
if (document.getElementById("contactno").value == "")
{
alert("Please enter contact no");
return false;
}
if (document.getElementById("query").value == "")
{
alert("Please enter Query");
return false;
}
return true;
}
{
if (document.getElementById("Name").value == "") //"Name" == it is a control Id
{
alert("Please enter name");
return false;
}
if (document.getElementById("address").value == "")
{
alert("Please enter Address");
return false;
}
if (document.getElementById("contactno").value == "")
{
alert("Please enter contact no");
return false;
}
if (document.getElementById("query").value == "")
{
alert("Please enter Query");
return false;
}
return true;
}
// Show the salary sum according to the dept wise
SELECT Tbl_Emp.empname, Tbl_Emp.salary AS Amount, TBL_Dept.Deptname
FROM Tbl_Emp INNER JOIN
TBL_Dept ON Tbl_Emp.deptid = TBL_Dept.Deptid
order BY deptname desc
COMPUTE SUM(salary) BY deptname
FROM Tbl_Emp INNER JOIN
TBL_Dept ON Tbl_Emp.deptid = TBL_Dept.Deptid
order BY deptname desc
COMPUTE SUM(salary) BY deptname
Threading
public void ThreadJob()
{
for (int i = 0; i < 10; i++)
{
MessageBox.Show(i.ToString());
Thread.Sleep(1000);
}
}
public void ThreadJob1()
{
for (int i = 0; i < 10; i++)
{
MessageBox.Show(i.ToString());
Thread.Sleep(2000);
}
}
private void button2_Click(object sender, EventArgs e)
{
ThreadStart job = new ThreadStart(ThreadJob);
ThreadStart job1 = new ThreadStart(ThreadJob1);
Thread thread = new Thread(job);
Thread thread1 = new Thread(job1);
thread.Start();
thread1.Start();
}
{
for (int i = 0; i < 10; i++)
{
MessageBox.Show(i.ToString());
Thread.Sleep(1000);
}
}
public void ThreadJob1()
{
for (int i = 0; i < 10; i++)
{
MessageBox.Show(i.ToString());
Thread.Sleep(2000);
}
}
private void button2_Click(object sender, EventArgs e)
{
ThreadStart job = new ThreadStart(ThreadJob);
ThreadStart job1 = new ThreadStart(ThreadJob1);
Thread thread = new Thread(job);
Thread thread1 = new Thread(job1);
thread.Start();
thread1.Start();
}
Events and Delegates
//Delegate is handler for the event. Delegate work without event but Event can't work without Delegate because Delegate work as a handler for Event.
Car on = new Car();
private void car_Change()
{
MessageBox.Show("Tankempty");
}
private void sum(int a, int b)
{
MessageBox.Show("Tankempty");
}
private void car_Change1()
{
MessageBox.Show("TankFull");
}
private void button1_Click(object sender, EventArgs e)
{
on.Change += new Car.ChangingHandler(car_Change);
on.Change1 += new Car.ChangingHandler(car_Change1);
on.SetTank(int.Parse(textBox1.Text));
}
//Class
public class Car
{
private int tank;
// delegate declaration
public delegate void ChangingHandler();
// event declaration
public event ChangingHandler Change;
public event ChangingHandler Change1;
public Car()
{
}
public void SetTank(int p)
{
this.tank = p;
// call the event
if (p < 51)
{
Change();
}
else
{
Change1();
}
}
public string GetTank()
{
return this.tank.ToString();
}
}
Car on = new Car();
private void car_Change()
{
MessageBox.Show("Tankempty");
}
private void sum(int a, int b)
{
MessageBox.Show("Tankempty");
}
private void car_Change1()
{
MessageBox.Show("TankFull");
}
private void button1_Click(object sender, EventArgs e)
{
on.Change += new Car.ChangingHandler(car_Change);
on.Change1 += new Car.ChangingHandler(car_Change1);
on.SetTank(int.Parse(textBox1.Text));
}
//Class
public class Car
{
private int tank;
// delegate declaration
public delegate void ChangingHandler();
// event declaration
public event ChangingHandler Change;
public event ChangingHandler Change1;
public Car()
{
}
public void SetTank(int p)
{
this.tank = p;
// call the event
if (p < 51)
{
Change();
}
else
{
Change1();
}
}
public string GetTank()
{
return this.tank.ToString();
}
}
Labels:
Events and Delegates
Show the javascript box in .cs fle
string s = "";
ClientScript.RegisterStartupScript(this.GetType(), "aa", s);
ClientScript.RegisterStartupScript(this.GetType(), "aa", s);
Find the control from gridview
TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
Posted by DeepakSinghRawat at 9:15 PM
Labels: Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
Posted by DeepakSinghRawat at 9:15 PM
Labels: Label lbnlid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblId");
Labels:
Find the control from gridview
Insert the values in GridView1_RowCancelingEdit
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
fillgridview();
}
{
GridView1.EditIndex = -1;
fillgridview();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
fillgridview();
}
delete duplicate data from Table
Note : You must have (Identity key) (EmpId) field in the table.
DELETE
FROM emp
WHERE empID NOT IN
(
SELECT MAX(empID)
FROM emp
GROUP BY empname)
DELETE
FROM emp
WHERE empID NOT IN
(
SELECT MAX(empID)
FROM emp
GROUP BY empname)
Labels:
delete duplicate data from Table
Subscribe to:
Posts (Atom)