Wednesday, December 30, 2009

Send Mail

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Web.Mail;


namespace MyCodeSnippet
{
public partial class Mail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

#region Mail
public void SendMailv1(String sTo, String sSubject, String sBody, String sCC)
{
try
{
System.Net.Mail.MailMessage oMail = new System.Net.Mail.MailMessage();
oMail.Subject = sSubject;
oMail.Body = sBody;
if (sCC.Length > 0)
{
oMail.CC.Add(sCC);
}

SendMailV2(sTo, sSubject, oMail);
}
catch (Exception exp)
{
throw new Exception(exp.Message);
}
}
public void SendMailv1(String sTo, String sSubject, String sBody, String sCC, string sBcc)
{
System.Net.Mail.MailMessage oMail = new System.Net.Mail.MailMessage();
oMail.Subject = sSubject;
oMail.Body = sBody;
//oMail.Attachments.Add(oAttch);
if (sCC.Length > 0)
{
oMail.CC.Add(sCC);
}
if (sBcc.Length > 0)
{
oMail.Bcc.Add(sBcc);
}
SendMailV2(sTo, sSubject, oMail);
}

public void SendMailv1(String sTo, String sSubject, String sBody, String sCC, System.Net.Mail.Attachment oAtch)
{
System.Net.Mail.MailMessage oMail = new System.Net.Mail.MailMessage();
oMail.Subject = sSubject;
oMail.Body = sBody;
oMail.Attachments.Add(oAtch);

if (sCC.Length > 0)
{
oMail.CC.Add(sCC);
}
SendMailV2(sTo, sSubject, oMail);
}

public void SendMailV2(string sTo, string sSubject, System.Net.Mail.MailMessage oMail)
{
String sErrMessage;
try
{
// Add To, From an Subject

oMail.To.Add(sTo);
string sFrom = System.Configuration.ConfigurationManager.AppSettings["AdminMailId"].ToString();
oMail.From = new MailAddress(sFrom);
oMail.Subject = sSubject;

string sReplyTo = System.Configuration.ConfigurationManager.AppSettings["ReplyToMailId"].ToString();
//oMail.ReplyTo = new MailAddress(sReplyTo);

//oMail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
oMail.IsBodyHtml = true;

// Set Mail Server Credentials

SmtpClient smtpc = new SmtpClient(ConfigurationSettings.AppSettings["SMTPIP"].ToString());
//smtpc.Port = 25;

smtpc.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SMTPPort"]);
//string sUserName = System.Configuration.ConfigurationManager.AppSettings["AdminMailId"].ToString();
//string sPassword = System.Configuration.ConfigurationManager.AppSettings["AdminPId"].ToString();
// smtpc.Credentials = new NetworkCredential(sUserName, sPassword);
//smtpc.Timeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SMTPTimeOut"]);// 180 sec
//smtpc.Send(oMail);

smtpc.Send(oMail);
//if You want to save the mail in your database.
//Email.SaveMail(oMail.From.ToString(), oMail.To.ToString(), oMail.CC.ToString(), oMail.Bcc.ToString(), oMail.Subject, oMail.Body, InitilizePage());
oMail.Dispose();

}
catch (SmtpFailedRecipientsException ex)
{
sErrMessage = "Mail send failed. Mail could not be delivered to all recipients.";
throw new Exception(sErrMessage);
}
catch (SmtpException ex)
{
sErrMessage = "Mail send failed. Error Code: " + ex.StatusCode.ToString() + ex.InnerException.Message;

throw new Exception(sErrMessage);
}
catch (Exception ex)
{
sErrMessage = "Mail send failed. Unknown error occured.";
throw new Exception(sErrMessage);
}
}
#endregion

protected void btnsend_Click(object sender, EventArgs e)
{

SendMailv1(txtTo.Text,txtsub.Text,txtbody.Text,txtcc.Text);

}

}
}

DB Class

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace MyCodeSnippet.DAL
{
public class DataBase
{
#region "member variable"
static SqlConnection conn = new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");
private SqlCommand cmd;
private SqlDataAdapter da;
#endregion


#region "member function"


public static void ExecuteNonQuery(string query)
{
try
{
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.Text;
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
cmd.ExecuteNonQuery();

}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();

}
}



public static DataTable ExecuteQuery(string query)
{
DataTable dt = new DataTable();
try
{

SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}

da.Fill(dt);

}
catch(Exception ex)
{

throw new Exception(ex.Message);
}
finally
{

if (conn.State == ConnectionState.Open)
conn.Close();



}
return dt;


}



#endregion
}
}

Grid view Desgin

<%--<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GV.aspx.cs" Inherits="MyCodeSnippet.GV1" %>







Sample Grid View











User Details



DataKeyNames="UserId" ForeColor="#333333" GridLines="None" ShowFooter="true"
AllowPaging="True" PageSize="5" AllowSorting="True" OnPageIndexChanging="GridView1_PageIndexChanging"
OnRowCreated="GridView1_RowCreated" OnRowDataBound="GridView1_RowDataBound"
OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowEditing="grdview_RowEditing" OnRowCancelingEdit="grdview_RowCancelingEdit" OnDataBound="grdview_DataBound" OnRowCommand="grdview_RowCommand" OnSorting="grdview_Sorting"
>









































Runat="server" ID="delete" onclientclick="return confirm('Are you sure you want to delete this Record?');" />


























Pages:

1
3
5
10
20





runat="server" AlternateText="First Page"

CommandName="Page" CommandArgument="First"

ImageUrl="~/Pics/left2.GIF" />


runat="server" AlternateText="Previous Page"

CommandName="Page" CommandArgument="Prev"

ImageUrl="~/Pics/left.GIF" />



Page 
AutoPostBack="true"

OnSelectedIndexChanged="PageNumberDropDownList_OnSelectedIndexChanged"

runat="server">


 of 
ID="PageCountLabel" runat="server" />




runat="server" AlternateText="Next Page"

CommandName="Page" CommandArgument="Next"

ImageUrl="~/Pics/right.GIF" />


runat="server" AlternateText="Last Page"

CommandName="Page" CommandArgument="Last"

ImageUrl="~/Pics/right2.GIF" />

















--%>

Thursday, May 14, 2009

How to use Repeter Control

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace MyCodeSnippet
{
public partial class SampleRC : System.Web.UI.Page
{
#region Private Members
private string qry = "select * from UserLogin";
private string SortField;
private string SortOrder;
private int PageNumber;
private int UserId;
private int pgCount;
public static int countPerRenderPage = 0;
public static int countTotalRec = 0;
static int PageSize;
static int TotalSize;
static int CurrentPage;
#endregion


#region connection string

static SqlConnection conn = new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");

#endregion

#region GetViewState/SetViewState
private void GetViewState()
{
this.UserId = Convert.ToInt32(ViewState["UserId"]);

}
private void SetViewState()
{
ViewState["UserId"] = this.UserId;

}
#endregion

#region Public Members

#region Init
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
rptPages.ItemCommand += new RepeaterCommandEventHandler(rptPages_ItemCommand);
}
#endregion
#endregion

//#region Init
//protected override void OnInit(EventArgs e)
//{
// base.OnInit(e);
// rptPages.ItemCommand += new RepeaterCommandEventHandler(rptPages_ItemCommand);
//}
//#endregion

#region PageLoad
protected void Page_Load(object sender, EventArgs e)
{
divUpdate.Visible = false;
divpagination.Visible = true;
if (!IsPostBack)
{
BindDataByChar("");
// BindPaging();
//bindrepeater();
SetViewState();
}
else
{
GetViewState();
}
}
#endregion


#region DeleteOperaion
protected void Button_Click(Object sender, CommandEventArgs e)
{
//foreach(RepeaterItem item in rptUser.Items)
//{
// CheckBox chk = (CheckBox)item.FindControl("chkbox");

// if (chk.Checked)
// {

UserId = Convert.ToInt32(e.CommandName);
string qry = "Delete from UserLogin where UserId=" + UserId;
SqlCommand cmd = new SqlCommand(qry, conn);
cmd.CommandType = CommandType.Text;
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
cmd.ExecuteNonQuery();
conn.Close();
//For Refresh the Repeter Control
BindDataByChar("");

// }
//}


}
#endregion

#region Insert
protected void ButtonInsert_Click(Object sender, CommandEventArgs e)
{
divUpdate.Visible = true;
this.UserId = -1;
SetViewState();
if (txt1.Text == "" && txt2.Text == "")
{
Response.Write("Please Enter the Data");

}
else
{
btnUpdate_Click(sender, e);

}


}

#endregion




#region Sorting
void SortData(string SortExpression)
{
if (ViewState["SortOrder"] == null)
{
ViewState["SortOrder"] = " ASC";
}
else if (ViewState["SortOrder"].ToString() == " ASC")
{
ViewState["SortOrder"] = " DESC";
}
else
{
ViewState["SortOrder"] = " ASC";
}
qry = qry + " ORDER BY " + SortExpression.ToString() + " " + ViewState["SortOrder"];
BindDataByChar("");
}

protected void lnkbtnUserIdSort_Click(object sender, EventArgs e)
{
SortField = "UserId";
SortData(SortField);
}

protected void lnkbtnPassSort_Click(object sender, EventArgs e)
{
SortField = "Password";
SortData(SortField);
}
#endregion


#region Pagination

// Bind repeater control..
public void rptBindGrid()

{
PageSize = int.Parse(DropDownListRowsPerPage.SelectedValue);

int count = 0;

string strCount = "select count(*) from UserLogin";


DataSet ds = new DataSet();

using (SqlConnection con = (new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123")))
{

using (SqlCommand cmd = new SqlCommand(strCount, con))

{

con.Open();

TotalSize = Convert.ToInt32(cmd.ExecuteScalar());

}

using (SqlDataAdapter da = new SqlDataAdapter("select * from UserLogin", con))

{


int StartRecord = ((CurrentPage) - 1) * ((PageSize));

da.Fill(ds, StartRecord, (PageSize), "UserLogin");


if ((count = ds.Tables[0].Rows.Count) > 0)

{

BuildPagers();

rptUser.DataSource = ds.Tables[0].DefaultView;

rptUser.DataBind();

}


}

}

}

private void BindPaging()
{

int i = 49;

if (countPerRenderPage != 0 && countTotalRec != 0)
{

int tillLoop = countTotalRec / countPerRenderPage;

for (int k = 0; k <= tillLoop; k++)
{

if (i < 58)
{

char c = (char)i;

LinkButton lnk = new LinkButton();

lnk.ID = "lnk" + c;

lnk.CausesValidation = false;

lnk.CssClass = "white12boldtxt";

lnk.Style["padding-right"] = "10px";

lnk.ForeColor = System.Drawing.Color.Red;

lnk.Text = c.ToString();

lnk.CommandArgument = c.ToString();

lnk.Command += new CommandEventHandler(Page_List_lnk);
rptPages.Controls.Add(lnk);
//lblPaging.Controls.Add(lnk);

i++;

}

}

}


}


void BindDataByChar(string alphabet)

{

int count = 0;

string qry = string.Empty;

if (!String.IsNullOrEmpty(alphabet))

qry = "select * from UserLogin where UserLogin like '" + alphabet + "%'";

else

qry="select * from UserLogin" ;

string strCount = "select count(*) from UserLogin";

DataTable dt = new DataTable();
SqlConnection con=new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");


DataSet ds = new DataSet();

using (con)

{
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
if (conn.State == ConnectionState.Closed)
{
con.Open();
}

da.Fill(dt);
if (dt.Rows.Count > 0)
{
TotalSize=dt.Rows.Count;
countTotalRec = Convert.ToInt32(TotalSize);
}






}
SqlConnection con1 = new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");
using (SqlDataAdapter da = new SqlDataAdapter(qry, con1))

{
CurrentPage = 1;
PageSize = Convert.ToInt32(DropDownListRowsPerPage.SelectedValue);
int StartRecord = ((CurrentPage) - 1) * ((PageSize));

da.Fill(ds, StartRecord, (PageSize), "UserLogin");

if ((countPerRenderPage = count = ds.Tables[0].Rows.Count) > 0)

{

BuildPagers();

//rptUser.DataSource = ds.Tables[0].DefaultView;

//rptUser.DataBind();
//Pagination
PagedDataSource pgitems = new PagedDataSource();
DataView dv = new DataView(dt);
pgitems.DataSource = dv;
pgitems.AllowPaging = true;
pgitems.PageSize = int.Parse(DropDownListRowsPerPage.SelectedValue);
pgitems.CurrentPageIndex = PageNumber;
//Total No of pages
//int j = 49;
//LinkButton lnk =FindControl("btnPage") as LinkButton;
//if (countPerRenderPage != 0 && countTotalRec != 0)
//{

// int tillLoop = countTotalRec / countPerRenderPage;

// for (int k = 0; k <= tillLoop; k++)
// {

// if (j < 58)
// {

// rptPages.Controls.Add(lnk):
// }
// }
//}
if (pgitems.PageCount > 1)
{
rptPages.Visible = true;
ArrayList pages = new ArrayList();
int i = 1;
for (; i < pgitems.PageCount; i++)
{
if (i < 10)
{

pages.Add((i).ToString());
rptPages.DataSource = pages;
rptPages.DataBind();

}
}
}
else
rptPages.Visible = false;
rptUser.DataSource = pgitems;
rptUser.DataBind();
}

}

}

void rptPages_ItemCommand(object source, RepeaterCommandEventArgs e)
{
PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
BindDataByChar("");
}


private void BuildPagers()
{

if ((((CurrentPage)) - 1) > 0)
{

prev.Visible = true;

first.Visible = true;

}

else
{

prev.Visible = false;

first.Visible = false;

}

if ((CurrentPage) * (PageSize) > (TotalSize))
{

next.Visible = false;

last.Visible = false;

}

else
{

next.Visible = true;

last.Visible = true;

}

}
protected void next_Click(object sender, EventArgs e)
{

Page_List(sender, e);

}

protected void prev_Click(object sender, EventArgs e)
{

Page_List(sender, e);

}

protected void last_Click(object sender, EventArgs e)
{

Page_List(sender, e);

}

protected void first_Click(object sender, EventArgs e)
{

Page_List(sender, e);

}

public void Page_List(object sender, EventArgs e)
{

if (((LinkButton)sender).ID == "prev")
{

if ((CurrentPage) >0)
{

if ((((CurrentPage)) - 1) > 0)
{

CurrentPage = ((CurrentPage) - 1);

}

}

}

else if (((LinkButton)sender).ID == "next")
{

if ((CurrentPage)>0)
{

if ((CurrentPage) * (PageSize) < (TotalSize))
{

CurrentPage = (CurrentPage + 1);

}

}

}

else if (((LinkButton)sender).ID == "last")
{

if ((CurrentPage)>0)
{

if ((CurrentPage) * (PageSize) < (TotalSize))
{

CurrentPage = (((TotalSize) / (PageSize)) );

}

}

}

else if (((LinkButton)sender).ID == "first")
{

if ((CurrentPage) == 0)

CurrentPage = 1;

if ((((CurrentPage)) - 1) > 0)

CurrentPage= 1;

}

// Now bind data

rptBindGrid();

}

public void Page_List_lnk(object sender, EventArgs e)
{

string[] charval = { "lnk" };

string[] strlId = (((LinkButton)sender).ID).Split(charval, StringSplitOptions.RemoveEmptyEntries);

string xfdsf = (((LinkButton)sender).ID).Remove(0, 3);

if (!String.IsNullOrEmpty(xfdsf))

rptBindGrid_k(xfdsf);


}

public void rptBindGrid_k(string val)

{

CurrentPage = int.Parse(val);

int StartRecord = 0;

int count = 0;

string strCount = "select count(*) from UserLogin";

DataSet ds = new DataSet();
SqlConnection con = new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");
using (con)

{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(strCount, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
if (conn.State == ConnectionState.Closed)
{
con.Open();
}

da.Fill(dt);
if (dt.Rows.Count > 0)
{
TotalSize=dt.Rows.Count;

}

}
SqlConnection con1 = new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");
using (SqlDataAdapter da = new SqlDataAdapter("select * from UserLogin", con1))

{

if ((CurrentPage) >0)

{

StartRecord = ((CurrentPage) - 1) * ((PageSize));

da.Fill(ds, StartRecord, (PageSize), "UserLogin");

}

else

{

StartRecord = 0;

da.Fill(ds, StartRecord, (TotalSize), "UserLogin");

}

if ((count = ds.Tables[0].Rows.Count) > 0)

{

if(StartRecord != 0)

BuildPagers();

rptUser.DataSource = ds.Tables[0].DefaultView;

rptUser.DataBind();

}

}

}





protected void DropDownListRowsPerPage_SelectedIndexChanged(object sender, EventArgs e)
{

//PageNumber = int.Parse(DropDownListRowsPerPage.SelectedValue);
//ViewState["PageNumber"] = PageNumber;
//bindrepeater();
BindDataByChar("");



}
#endregion

#region serach
protected void btnserach_Click(object sender, EventArgs e)
{
if (txtsUserId.Text == "")
{
Response.Write("Please enter the data");
}
else
{
qry = qry + " where UserId=" + txtsUserId.Text;
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(qry, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}

da.Fill(dt);
if (dt.Rows.Count > 0)
{
rptUser.DataSource = dt;
rptUser.DataBind();
TotalSize = dt.Rows.Count;
countTotalRec = Convert.ToInt32(TotalSize);
}

}
}
#endregion


#region Select
protected void ButtonSelect_Click(Object sender, CommandEventArgs e)
{
divUpdate.Visible = true;
this.UserId = Convert.ToInt32(e.CommandName);
SetViewState();
string qry = "select * from UserLogin where UserId=" + UserId;
DataTable dt = new DataTable();

SqlCommand cmd = new SqlCommand(qry, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}

da.Fill(dt);
if (dt.Rows.Count > 0)
{
txt1.Text = dt.Rows[0]["UserId"].ToString();
txt2.Text = dt.Rows[0]["Password"].ToString();
}
}
#endregion

#region UpDate
protected void btnUpdate_Click(object sender, EventArgs e)
{
divUpdate.Visible = true;
GetViewState();
string qry1;
if (this.UserId == -1)
{
qry1 = "insert into UserLogin values(" + Convert.ToInt32(txt1.Text) + "," + "'"+ txt2.Text + "'" + ")";
}
else
{
qry1 = "update UserLogin set UserId=" + Convert.ToInt32(txt1.Text) + ",Password=" + "'" + txt2.Text + "'" + " where UserId=" + this.UserId;
}

SqlCommand cmd = new SqlCommand(qry1, conn);
cmd.CommandType = CommandType.Text;
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
cmd.ExecuteNonQuery();
conn.Close();
//For Refresh the Repeter Control
//bindrepeater();
BindDataByChar("");
divUpdate.Visible = false;

}
#endregion

protected void rptUser_ItemCreated(object sender, RepeaterItemEventArgs e)
{

}
}
}

How to Use grid View

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace MyCodeSnippet
{
public partial class GV1 : System.Web.UI.Page
{

#region connection string
private int UserId;
private string qry = "select * from UserLogin";
private int UId;
private string Password;
//static string txtpass;
static SqlConnection conn = new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");

#endregion

#region GetViewState/SetViewState
private void GetViewState()
{
this.UserId = Convert.ToInt32(ViewState["UserId"]);

}
private void SetViewState()
{
ViewState["UserId"] = this.UserId;

}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.SetData();
//this.UserId = Convert.ToInt32(dvUser.Rows[0].Cells[1].Text);
//SetViewState();


}
}
private void SetData()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM UserLogin", conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);

try
{
conn.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);

grdview.DataSource = ds;
grdview.DataBind();
conn.Close();





}
finally
{

}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{


this.UserId = Convert.ToInt32(grdview.DataKeys[e.RowIndex].Value);
GridViewRow row =grdview.Rows[e.RowIndex];

TextBox txtUserId = (TextBox)row.FindControl("txtUserId");
TextBox txtPassword = (TextBox)row.FindControl("txtPassword");

if (txtUserId == null) { return; }
if (txtPassword == null) { return; }



SqlCommand cmd = new SqlCommand(
"update UserLogin set UserId=" + Convert.ToInt32(txtUserId.Text) + ",Password=" + "'" + txtPassword.Text + "'" + " where UserId=" + this.UserId,
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
grdview.EditIndex = -1;
this.SetData();

}
finally
{

}
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
this.UserId = Convert.ToInt32(grdview.DataKeys[e.RowIndex].Value);
SqlCommand cmd = new SqlCommand("DELETE FROM UserLogin WHERE UserId =" + this.UserId,
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
this.SetData();

}
finally
{

}
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdview.PageIndex = e.NewPageIndex;

this.SetData();
}
protected void DropDownListRowsPerPage_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr=grdview.BottomPagerRow;
DropDownList ddl = (DropDownList)(gvr.Cells[0].FindControl("DropDownListRowsPerPage"));
grdview.PageSize=int.Parse(ddl.SelectedValue);
//grdview.PageIndex = (ddl.SelectedIndex);
this.SetData();



}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

}

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{

}

protected void grdview_RowEditing(object sender, GridViewEditEventArgs e)
{

grdview.EditIndex = e.NewEditIndex;
this.SetData();

}

protected void grdview_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{

grdview.EditIndex = -1;
this.SetData();
}

protected void grdview_DataBound(object sender, EventArgs e)
{

InitialiseGridViewPagerRow(grdview.TopPagerRow);
InitialiseGridViewPagerRow(grdview.BottomPagerRow);
}
#region Pagination
private void InitialiseGridViewPagerRow(GridViewRow GridViewRow)
{

if (GridViewRow != null)
{

// Check the page index so that we can :

// 1. Disable the 'First' and 'Previous' paging image buttons if paging index is at 0

// 2. Disable the 'Last' and 'Next' paging image buttons if paging index is at the end

// 3. Enable all image buttons if the conditions of 1 and 2 are not satisfied



if (grdview.PageIndex == 0)
{

// Disable 'First' and 'Previous' Paging image buttons



ImageButton firstPageImageButton = GridViewRow.FindControl(

"FirstPageImageButton") as ImageButton;



ImageButton previousPageImageButton = GridViewRow.FindControl(

"PreviousPageImageButton") as ImageButton;



if (firstPageImageButton != null && previousPageImageButton != null)
{

firstPageImageButton.Enabled = false;



previousPageImageButton.Enabled = false;

}

}

else if ((grdview.PageIndex + 1) == grdview.PageCount)
{

// Disable 'Last' and 'Next' Paging image buttons



ImageButton lastPageImageButton = GridViewRow.FindControl(

"LastPageImageButton") as ImageButton;



ImageButton nextPageImageButton = GridViewRow.FindControl(

"NextPageImageButton") as ImageButton;



if (lastPageImageButton != null && nextPageImageButton != null)
{

lastPageImageButton.Enabled = false;



nextPageImageButton.Enabled = false;

}

}

else
{

// Enable the Paging image buttons



ImageButton firstPageImageButton = GridViewRow.FindControl(

"FirstPageImageButton") as ImageButton;



ImageButton previousPageImageButton = GridViewRow.FindControl(

"PreviousPageImageButton") as ImageButton;



ImageButton lastPageImageButton = GridViewRow.FindControl(

"LastPageImageButton") as ImageButton;



ImageButton nextPageImageButton = GridViewRow.FindControl(

"NextPageImageButton") as ImageButton;



if (firstPageImageButton != null && lastPageImageButton != null &&

previousPageImageButton != null && nextPageImageButton != null)
{

firstPageImageButton.Enabled = true;



lastPageImageButton.Enabled = true;



nextPageImageButton.Enabled = true;



previousPageImageButton.Enabled = true;

}

}



// Get the DropDownList found as part of the Pager Row.

// One can then initialise the DropDownList to contain

// the appropriate page settings. Eg. Page Number and

// number of Pages

DropDownList pageNumberDropDownList = GridViewRow.FindControl(

"PageNumberDropDownList") as DropDownList;



Label pageCountLabel = GridViewRow.FindControl(

"PageCountLabel") as Label;



if (pageNumberDropDownList != null && pageCountLabel != null)
{

for (int i = 0; i < grdview.PageCount; i++)
{

int page = i + 1;


ListItem li = new ListItem(page.ToString(), i.ToString());
pageNumberDropDownList.Items.Add(li);


}



pageNumberDropDownList.SelectedIndex = grdview.PageIndex;



pageCountLabel.Text = grdview.PageCount.ToString();

}

}

}



///

/// Handle the SelectedIndexChanged event for the Page Number

/// DropDownList. This allows one to select a page index via a

/// DropDownList.

///


protected void PageNumberDropDownList_OnSelectedIndexChanged(

object sender, EventArgs e)
{

DropDownList pageNumberDropDownList = sender as DropDownList;



if (pageNumberDropDownList != null)
{

if (grdview.Rows.Count > 0)
{

if (pageNumberDropDownList.SelectedIndex < grdview.PageCount ||

pageNumberDropDownList.SelectedIndex >= 0)
{

grdview.PageIndex = pageNumberDropDownList.SelectedIndex;
this.SetData();

}

}

}

}
#endregion

protected void grdview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")

{

//handle insert here

TextBox newUserId = grdview.FooterRow.FindControl("txtNewUserId") as TextBox;
TextBox newpass = grdview.FooterRow.FindControl("txtnewpass") as TextBox;
SqlCommand cmd = new SqlCommand(
"insert into UserLogin values(" + Convert.ToInt32(newUserId.Text) + "," + "'" + newpass.Text + "'" + ")",
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
grdview.EditIndex = -1;
this.SetData();
}
finally
{

}


}
}

#region sorting
protected void grdview_Sorting(object sender, GridViewSortEventArgs e)
{
string Sort=e.SortExpression;
SortData(Sort);

//GridViewSortExpression = e.SortExpression;
//int pageIndex = gridView.PageIndex;
//gridView.DataSource = SortData(gridView.DataSource as DataTable, false);
//gridView.DataBind();
//gridView.PageIndex = pageIndex;
}

void SortData(string SortExpression)
{
if (ViewState["SortOrder"] == null)
{
ViewState["SortOrder"] = " ASC";
}
else if (ViewState["SortOrder"].ToString() == " ASC")
{
ViewState["SortOrder"] = " DESC";
}
else
{
ViewState["SortOrder"] = " ASC";
}
//string qry = "select * from UserLogin";
qry = qry + " ORDER BY " + SortExpression.ToString() + " " + ViewState["SortOrder"];
SqlCommand cmd = new SqlCommand(qry, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);

try
{
conn.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);

grdview.DataSource = ds;
grdview.DataBind();
conn.Close();





}
finally
{

}
}
#endregion


}
}

How to use Form View

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace MyCodeSnippet
{
public partial class FV : System.Web.UI.Page
{
#region connection string
private int UserId;
//static string txtpass;
static SqlConnection conn = new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");

#endregion

#region GetViewState/SetViewState
private void GetViewState()
{
this.UserId = Convert.ToInt32(ViewState["UserId"]);

}
private void SetViewState()
{
ViewState["UserId"] = this.UserId;

}
#endregion
private void SetData()
{

SqlCommand cmd = new SqlCommand("SELECT * FROM UserLogin", conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);

try
{
conn.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);

frmview.DataSource = ds;
frmview.DataBind();




conn.Close();
}
finally
{

}
}


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.SetData();
Label lblUID = frmview.FindControl("lblUserId") as Label;
this.UserId = Convert.ToInt32(lblUID.Text);
SetViewState();


}

}








protected void frmview_ItemInserting(object sender, FormViewInsertEventArgs e)
{

TextBox txtUserId = frmview.FindControl("txtInsUserId") as TextBox;
TextBox txtPass = frmview.FindControl("txtInsPass") as TextBox;

if (txtUserId == null) { return; }
if (txtPass == null) { return; }


SqlCommand cmd = new SqlCommand(
"insert into UserLogin values(" + Convert.ToInt32(txtUserId.Text) + "," + "'" + txtPass.Text + "'" + ")",
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
frmview.ChangeMode(FormViewMode.ReadOnly);

this.SetData();

}
finally
{

}

}




protected void frmview_ModeChanging1(object sender, FormViewModeEventArgs e)
{

frmview.ChangeMode(e.NewMode);
this.SetData();


}

protected void frmview_ItemUpdating1(object sender, FormViewUpdateEventArgs e)
{

TextBox txtUId = frmview.FindControl("txtUpUserId") as TextBox;
TextBox txtPassword = frmview.FindControl("txtUpPass") as TextBox;
GetViewState();
if (txtUId == null) { return; }
if (txtPassword == null) { return; }


SqlCommand cmd = new SqlCommand(
"update UserLogin set UserId=" + Convert.ToInt32(txtUId.Text) + ",Password=" + "'" + txtPassword.Text + "'" + " where UserId=" + this.UserId,
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
frmview.ChangeMode(FormViewMode.ReadOnly);
this.SetData();

}
finally
{

}
//string qry = "update UserLogin set UserId=" + Convert.ToInt32(txtUserId.Text) + ",Password=" + "'" + txtpassword.Text + "'" + " where UserId=" + this.UserId;
}

protected void frmview_ItemDeleting(object sender, FormViewDeleteEventArgs e)
{

GetViewState();
SqlCommand cmd = new SqlCommand("DELETE FROM UserLogin WHERE UserId ="+this.UserId,
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
frmview.ChangeMode(FormViewMode.ReadOnly);
this.SetData();

}
finally
{

}

}

#region Pagination
private void InitialiseFormViewPagerRow(FormViewRow formViewRow)
{

if (formViewRow != null)
{

// Check the page index so that we can :

// 1. Disable the 'First' and 'Previous' paging image buttons if paging index is at 0

// 2. Disable the 'Last' and 'Next' paging image buttons if paging index is at the end

// 3. Enable all image buttons if the conditions of 1 and 2 are not satisfied



if (frmview.PageIndex == 0)
{

// Disable 'First' and 'Previous' Paging image buttons



ImageButton firstPageImageButton = formViewRow.FindControl(

"FirstPageImageButton") as ImageButton;



ImageButton previousPageImageButton = formViewRow.FindControl(

"PreviousPageImageButton") as ImageButton;



if (firstPageImageButton != null && previousPageImageButton != null)
{

firstPageImageButton.Enabled = false;



previousPageImageButton.Enabled = false;

}

}

else if ((frmview.PageIndex + 1) == frmview.PageCount)
{

// Disable 'Last' and 'Next' Paging image buttons



ImageButton lastPageImageButton = formViewRow.FindControl(

"LastPageImageButton") as ImageButton;



ImageButton nextPageImageButton = formViewRow.FindControl(

"NextPageImageButton") as ImageButton;



if (lastPageImageButton != null && nextPageImageButton != null)
{

lastPageImageButton.Enabled = false;



nextPageImageButton.Enabled = false;

}

}

else
{

// Enable the Paging image buttons



ImageButton firstPageImageButton = formViewRow.FindControl(

"FirstPageImageButton") as ImageButton;



ImageButton previousPageImageButton = formViewRow.FindControl(

"PreviousPageImageButton") as ImageButton;



ImageButton lastPageImageButton = formViewRow.FindControl(

"LastPageImageButton") as ImageButton;



ImageButton nextPageImageButton = formViewRow.FindControl(

"NextPageImageButton") as ImageButton;



if (firstPageImageButton != null && lastPageImageButton != null &&

previousPageImageButton != null && nextPageImageButton != null)
{

firstPageImageButton.Enabled = true;



lastPageImageButton.Enabled = true;



nextPageImageButton.Enabled = true;



previousPageImageButton.Enabled = true;

}

}



// Get the DropDownList found as part of the Pager Row.

// One can then initialise the DropDownList to contain

// the appropriate page settings. Eg. Page Number and

// number of Pages

DropDownList pageNumberDropDownList = formViewRow.FindControl(

"PageNumberDropDownList") as DropDownList;



Label pageCountLabel = formViewRow.FindControl(

"PageCountLabel") as Label;



if (pageNumberDropDownList != null && pageCountLabel != null)
{

for (int i = 0; i < frmview.PageCount; i++)
{

int page = i + 1;


ListItem li = new ListItem(page.ToString(), i.ToString());
pageNumberDropDownList.Items.Add(li);


}



pageNumberDropDownList.SelectedIndex = frmview.PageIndex;



pageCountLabel.Text = frmview.PageCount.ToString();

}

}

}



///

/// Handle the SelectedIndexChanged event for the Page Number

/// DropDownList. This allows one to select a page index via a

/// DropDownList.

///


protected void PageNumberDropDownList_OnSelectedIndexChanged(

object sender, EventArgs e)
{

DropDownList pageNumberDropDownList = sender as DropDownList;



if (pageNumberDropDownList != null)
{

if (frmview.DataItemCount > 0)
{

if (pageNumberDropDownList.SelectedIndex < frmview.PageCount ||

pageNumberDropDownList.SelectedIndex >= 0)
{

frmview.PageIndex = pageNumberDropDownList.SelectedIndex;
this.SetData();
Label lblUID = frmview.FindControl("lblUserId") as Label;
this.UserId = Convert.ToInt32(lblUID.Text);
SetViewState();
}

}

}

}
#endregion

protected void frmview_PageIndexChanging(object sender, FormViewPageEventArgs e)
{

frmview.PageIndex = e.NewPageIndex;

this.SetData();
Label lblUID = frmview.FindControl("lblUserId") as Label;
this.UserId = Convert.ToInt32(lblUID.Text);
SetViewState();


}





protected void frmview_DataBound1(object sender, EventArgs e)
{
InitialiseFormViewPagerRow(frmview.TopPagerRow);
InitialiseFormViewPagerRow(frmview.BottomPagerRow);

}




}
}

How to use Details View

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace MyCodeSnippet
{
public partial class DV : System.Web.UI.Page
{
#region connection string
private int UserId;
//static string txtpass;
static SqlConnection conn = new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");

#endregion

#region GetViewState/SetViewState
private void GetViewState()
{
this.UserId = Convert.ToInt32(ViewState["UserId"]);

}
private void SetViewState()
{
ViewState["UserId"] = this.UserId;

}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetData();
this.UserId = Convert.ToInt32(dvUser.Rows[0].Cells[1].Text);
SetViewState();


}
}

private void GetData()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM UserLogin", conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);

try
{
conn.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);

dvUser.DataSource = ds;
dvUser.DataBind();





conn.Close();
}
finally
{

}
}

protected void dvUser_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
TextBox UserId =dvUser.Rows[0].Cells[1].Controls[0] as TextBox;
TextBox Password = dvUser.Rows[1].Cells[1].Controls[0] as TextBox;

if (UserId == null) { return; }
if (Password == null) { return; }


SqlCommand cmd = new SqlCommand(
"insert into UserLogin values(" + Convert.ToInt32(UserId.Text) + "," + "'" + Password.Text + "'" + ")",
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
dvUser.ChangeMode(DetailsViewMode.ReadOnly);


this.GetData();

}
finally
{

}
}

protected void dvUser_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
GetViewState();


TextBox UserId =dvUser.Rows[0].Cells[1].Controls[0] as TextBox;
TextBox Password = dvUser.Rows[1].Cells[1].Controls[0] as TextBox;

if (UserId == null) { return; }
if (Password == null) { return; }

SqlCommand cmd = new SqlCommand(
"update UserLogin set UserId=" + Convert.ToInt32(UserId.Text) + ",Password=" + "'" + Password.Text + "'" + " where UserId=" + this.UserId,
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
dvUser.ChangeMode(DetailsViewMode.ReadOnly);

this.GetData();

}
finally
{
}

}

protected void dvUser_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
{
GetViewState();
SqlCommand cmd = new SqlCommand("DELETE FROM UserLogin WHERE UserId =" + this.UserId,
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
dvUser.ChangeMode(DetailsViewMode.ReadOnly);
this.GetData();

}
finally
{

}
}

protected void dvUser_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
dvUser.ChangeMode(e.NewMode);
this.GetData();
}

protected void dvUser_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
dvUser.PageIndex = e.NewPageIndex;
this.GetData();

//e.Item.Cells[n].Text;
//int i = dvUser.PageIndex;
this.UserId= Convert.ToInt32(dvUser.Rows[0].Cells[1].Text);
SetViewState();


}

protected void dvUser_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
this.UserId = Convert.ToInt32(e.Keys["UserId"]);
SetViewState();
}

#region Pagination
private void InitialiseDetailsViewPagerRow(DetailsViewRow DetailsViewRow)
{

if (DetailsViewRow != null)
{

// Check the page index so that we can :

// 1. Disable the 'First' and 'Previous' paging image buttons if paging index is at 0

// 2. Disable the 'Last' and 'Next' paging image buttons if paging index is at the end

// 3. Enable all image buttons if the conditions of 1 and 2 are not satisfied



if (dvUser.PageIndex == 0)
{

// Disable 'First' and 'Previous' Paging image buttons



ImageButton firstPageImageButton = DetailsViewRow.FindControl(

"FirstPageImageButton") as ImageButton;



ImageButton previousPageImageButton = DetailsViewRow.FindControl(

"PreviousPageImageButton") as ImageButton;



if (firstPageImageButton != null && previousPageImageButton != null)
{

firstPageImageButton.Enabled = false;



previousPageImageButton.Enabled = false;

}

}

else if ((dvUser.PageIndex + 1) == dvUser.PageCount)
{

// Disable 'Last' and 'Next' Paging image buttons



ImageButton lastPageImageButton = DetailsViewRow.FindControl(

"LastPageImageButton") as ImageButton;



ImageButton nextPageImageButton = DetailsViewRow.FindControl(

"NextPageImageButton") as ImageButton;



if (lastPageImageButton != null && nextPageImageButton != null)
{

lastPageImageButton.Enabled = false;



nextPageImageButton.Enabled = false;

}

}

else
{

// Enable the Paging image buttons



ImageButton firstPageImageButton = DetailsViewRow.FindControl(

"FirstPageImageButton") as ImageButton;



ImageButton previousPageImageButton = DetailsViewRow.FindControl(

"PreviousPageImageButton") as ImageButton;



ImageButton lastPageImageButton = DetailsViewRow.FindControl(

"LastPageImageButton") as ImageButton;



ImageButton nextPageImageButton = DetailsViewRow.FindControl(

"NextPageImageButton") as ImageButton;



if (firstPageImageButton != null && lastPageImageButton != null &&

previousPageImageButton != null && nextPageImageButton != null)
{

firstPageImageButton.Enabled = true;



lastPageImageButton.Enabled = true;



nextPageImageButton.Enabled = true;



previousPageImageButton.Enabled = true;

}

}



// Get the DropDownList found as part of the Pager Row.

// One can then initialise the DropDownList to contain

// the appropriate page settings. Eg. Page Number and

// number of Pages

DropDownList pageNumberDropDownList = DetailsViewRow.FindControl(

"PageNumberDropDownList") as DropDownList;



Label pageCountLabel = DetailsViewRow.FindControl(

"PageCountLabel") as Label;



if (pageNumberDropDownList != null && pageCountLabel != null)
{

for (int i = 0; i < dvUser.PageCount; i++)
{

int page = i + 1;


ListItem li = new ListItem(page.ToString(), i.ToString());
pageNumberDropDownList.Items.Add(li);


}



pageNumberDropDownList.SelectedIndex = dvUser.PageIndex;



pageCountLabel.Text = dvUser.PageCount.ToString();

}

}

}



///

/// Handle the SelectedIndexChanged event for the Page Number

/// DropDownList. This allows one to select a page index via a

/// DropDownList.

///


protected void PageNumberDropDownList_OnSelectedIndexChanged(

object sender, EventArgs e)
{

DropDownList pageNumberDropDownList = sender as DropDownList;



if (pageNumberDropDownList != null)
{

if (dvUser.DataItemCount > 0)
{

if (pageNumberDropDownList.SelectedIndex < dvUser.PageCount ||

pageNumberDropDownList.SelectedIndex >= 0)
{

dvUser.PageIndex = pageNumberDropDownList.SelectedIndex;
this.GetData();
this.UserId = Convert.ToInt32(dvUser.Rows[0].Cells[1].Text);
SetViewState();
}

}

}

}
#endregion
protected void dvUser_DataBound(object sender, EventArgs e)
{

InitialiseDetailsViewPagerRow(dvUser.TopPagerRow);
InitialiseDetailsViewPagerRow(dvUser.BottomPagerRow);
}
}
}

How to Use DataList

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace MyCodeSnippet
{
public partial class DataList : System.Web.UI.Page
{

#region connection string

//static string txtpass;
static SqlConnection conn = new SqlConnection("server=sys17;Persist Security Info=False;database=Demo;User ID=sa;Password=Sunarc123");

#endregion
#region GetViewState/SetViewState
private int UserId;
private void GetViewState()
{
this.UserId = Convert.ToInt32(ViewState["UserId"]);

}
private void SetViewState()
{
ViewState["UserId"] = this.UserId;

}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.SetData();



}
}
private void SetData()
{

SqlCommand cmd = new SqlCommand("SELECT * FROM UserLogin", conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);

try
{
conn.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);

dlview.DataSource = ds;
dlview.DataBind();




conn.Close();
}
finally
{

}
}

protected void Update_Command(object source, DataListCommandEventArgs e)
{

this.UserId=Convert.ToInt32(dlview.DataKeys[e.Item.ItemIndex]);

SetViewState();
TextBox tbox = default(TextBox);
TextBox txtUserId = (TextBox)e.Item.FindControl("EditUser");
TextBox txtPassword = (TextBox)e.Item.FindControl("EditPassword");
GetViewState();
if (txtUserId == null) { return; }
if (txtPassword == null) { return; }


SqlCommand cmd = new SqlCommand(
"update UserLogin set UserId=" + Convert.ToInt32(txtUserId.Text) + ",Password=" + "'" + txtPassword.Text + "'" + " where UserId=" + this.UserId,
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
dlview.EditItemIndex = -1;
this.SetData();

}
finally
{

}





}

protected void Cancel_Command(object source, DataListCommandEventArgs e)
{
dlview.EditItemIndex = -1;
this.SetData();
}

protected void Delete_Command(object source, DataListCommandEventArgs e)
{
this.UserId = Convert.ToInt32(dlview.DataKeys[e.Item.ItemIndex]);
SqlCommand cmd = new SqlCommand("DELETE FROM UserLogin WHERE UserId =" + this.UserId,
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
this.SetData();

}
finally
{

}
}

protected void Edit_Command(object source, DataListCommandEventArgs e)
{
dlview.EditItemIndex=e.Item.ItemIndex;
this.SetData();

}

protected void dlview_ItemCommand(object source, DataListCommandEventArgs e)
{


if (e.CommandName == "Insert")
{

TextBox UserId = (TextBox)e.Item.FindControl("InsUser");
TextBox Password = (TextBox)e.Item.FindControl("InsPassword");
if (UserId == null) { return; }
if (Password == null) { return; }


SqlCommand cmd = new SqlCommand(
"insert into UserLogin values(" + Convert.ToInt32(UserId.Text) + "," + "'" + Password.Text + "'" + ")",
conn);


try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
dlview.EditItemIndex = -1;
this.SetData();
}
finally
{

}
}
if (e.CommandName == "InsCancel")
{
dlview.EditItemIndex = -1;
this.SetData();
}

}
}
}

Code snippet for Return Table

#region ReturnTable
public DataTable $getDBTable$(string $sQuery$)
{
DataTable $retDt$ = null;
string $constring$ =$connectionstring$;
SqlConnection $conn$ = new SqlConnection($constring$);
SqlDataAdapter $sqlDa$ = new SqlDataAdapter();
DataSet $ds$ = new DataSet();
$sqlDa$.SelectCommand = new SqlCommand($sQuery$, $conn$);
$sqlDa$.Fill($ds$);
if ($ds$.Tables.Count > 0)
{
$retDt$ = $ds$.Tables[0];
}

return $retDt$;
}
#endregion

Saturday, May 9, 2009

How to Use Window Mobile 6

Links for WM

WM Library:-

http://msdn.microsoft.com/en-us/library/bb158492.aspx

Videos:

http://msdn.microsoft.com/hi-in/windowsmobile/bb495180(en-us).aspx

All About WM:-

http://msdn.microsoft.com/hi-in/windowsmobile/bb250560(en-us).aspx

EBOOKS:

http://msdn.microsoft.com/hi-in/windowsmobile/dd727733(en-us).aspx

User INTERFACE COMPONENT:

http://msdn.microsoft.com/en-us/library/bb158595.aspx

Emulator:

http://msdn.microsoft.com/en-us/library/bb278114.aspx

Comman Controls:

http://msdn.microsoft.com/en-us/library/aa932754.aspx

How to connent to DB:

http://msdn.microsoft.com/en-us/library/aa454889.aspx

http://www.devx.com/MicrosoftISV/Article/34341

//check it first. for this you have to create ur DB on your m/c.

WM Application:

http://en.softonic.com/s/windows-mobile-6-application:pocketpc

Examples:

http://www.christec.co.nz/blog/page/2

How to connect celluar and device emulators:

http://www.devx.com/wireless/Article/40981/1954

Tasks 1:

http://freelance.geekinterview.com/112123-windows-mobile-ringtone-read.html

How to Use Active Sync:-

http://msdn.microsoft.com/en-us/library/aa458829.aspx

http://www.answerbag.com/articles/How-to-Check-Outlook-Email-Remotely/411117d2-ea77-d17e-f1fe-66c149930447

About Connection b/w emulators and device:-

http://msdn.microsoft.com/en-us/library/dd721907.aspx

http://blogs.msdn.com/fzandona/archive/2007/04/11/wm-6-sdk-and-cellular-emulator-can-you-hear-me-now.aspx

How to Load files in emulator OS:-

http://www.windowsdevcenter.com/pub/a/windows/2006/01/24/windows-mobile5-emulators-in-visual-studio-2005.html?page=4

connection string:-

http://www.bigresource.com/MS_SQL-Connection-string-for-PDA-EBCNkN9l.html

Zoom the pics:-

http://www.codeproject.com/KB/mobile/TouchPictureBox.aspx

How to Deploy the Application:

Videos:-

http://techtips.timlaytonllc.com/2009/04/how-to-deploy-windows-mobile.html

http://www.youtube.com/watch?v=knZFkt_4wOI

http://www.youtube.com/watch?v=prNXoxFd70g

How to put cab files into Relese Mode and how to deploy on to Real Device:-

http://www.devx.com/SpecialReports/Article/37718/1954

msdn link:-

http://msdn.microsoft.com/en-us/library/zcebx8f8.aspx