Monday, November 15, 2010

get items data at run time using the ItemDataBound, RowDataBound event

protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//For Fill Data in DataTable
dt = clsemp.GetData();
//For DataList
DataList1.DataSource = dt;
DataList1.DataBind();
//for GridView
GridView1.DataSource = dt;
GridView1.DataBind();
//for repeater
Repeater1.DataSource = dt;
Repeater1.DataBind();

}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.Item.DataItem != null)
{
int intEmployeeId = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "EmployeeId"));
string strFName = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "FirstName"));
string strLName = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "LastName"));

//work do as per require
}
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.DataItem != null)
{
int intEmployeeId = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "EmployeeId"));
string strFName = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "FirstName"));
string strLName = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "LastName"));

//work do as per require
}
}
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.Item.DataItem != null)
{
int intEmployeeId = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "EmployeeId"));
string strFName = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "FirstName"));
string strLName = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "LastName"));

//work do as per require
}
}

}

Tuesday, November 9, 2010

Paging ListView With DataPager

<asp:ListView ID="EmpListView" runat="server">
<LayoutTemplate>

<tr>
<td align="center">Employee Data</td>
</tr>

</LayoutTemplate>

<ItemTemplate>

<tr>
<td>
<br />
Employee Id:&nbsp;<b><%# Eval("employeeId") %>'></b>
<br /><br />
Employee Name::&nbsp;<b><%# Eval("FirstName") %>'>&nbsp;<%# Eval("LastName") %>'></b>
<br />
</td>
</tr>

</ItemTemplate>

</asp:ListView>
</table>
<br />
<asp:DataPager ID="PagerRow" runat="server" PagedControlID="EmpListView"
OnPreRender="EmpList_PreRender">
<Fields>
<asp:TemplatePagerField>
<PagerTemplate>
Page
<asp:Label runat="server" ID="lbCurrentPage"
Text="<%# Container.TotalRowCount>0 ? (Container.StartRowIndex / Container.PageSize) + 1 : 0 %>" />
of
<asp:Label runat="server" ID="lbTotalPages"
Text="<%# Math.Ceiling ((double)Container.TotalRowCount / Container.PageSize) %>" />
(Total:
<asp:Label runat="server" ID="lbTotalItems"
Text="<%# Container.TotalRowCount%>" />
records)
<br /><br />
</PagerTemplate>
</asp:TemplatePagerField>


<asp:NextPreviousPagerField ButtonType ="Button" ShowFirstPageButton="True" ShowPreviousPageButton="True" ShowNextPageButton="True" ShowLastPageButton="True" />

<asp:TemplatePagerField OnPagerCommand="PagerNextPrevious_OnPagerCommand">
<PagerTemplate>
<br /><br />

<asp:LinkButton ID="lbtnFirst" runat="server" CommandName="First"
Text="First" Visible='<%# Container.StartRowIndex > 0 %>' />

<asp:LinkButton ID="lbtnPrevious" runat="server" CommandName="Previous"
Text='<%# (Container.StartRowIndex - Container.PageSize + 1) + " - " + (Container.StartRowIndex) %>'
Visible='<%# Container.StartRowIndex > 0 %>' />

<asp:Label ID="lbtnCurrent" runat="server"
Text='<%# (Container.StartRowIndex + 1) + "-" + (Container.StartRowIndex + Container.PageSize > Container.TotalRowCount ? Container.TotalRowCount : Container.StartRowIndex + Container.PageSize) %>' />

<asp:LinkButton ID="lbtnNext" runat="server" CommandName="Next"
Text='<%# (Container.StartRowIndex + Container.PageSize + 1) + " - " + (Container.StartRowIndex + Container.PageSize*2 > Container.TotalRowCount ? Container.TotalRowCount : Container.StartRowIndex + Container.PageSize*2) %>'
Visible='<%# (Container.StartRowIndex + Container.PageSize) < Container.TotalRowCount %>' />

<asp:LinkButton ID="lbtnLast" runat="server" CommandName="Last"
Text="Last" Visible='<%# (Container.StartRowIndex + Container.PageSize) < Container.TotalRowCount %>' />
</PagerTemplate>
</asp:TemplatePagerField>

<asp:TemplatePagerField OnPagerCommand = "PagerNo_OnPagerCommand">
<PagerTemplate>
<br /><br />
<asp:TextBox ID="txtPageNo" runat="server" Width="30px" onKeyUp = "value = value.replace(/[^0-9]/g,'')"
Text="<%# Container.TotalRowCount>0 ? (Container.StartRowIndex / Container.PageSize) + 1 : 0 %>" ></asp:TextBox>
<asp:Button ID="btnsubmit" runat="server" Text="Go" />
</PagerTemplate>
</asp:TemplatePagerField>
</Fields>
</asp:DataPager>
private void DataBindList()
{
connectionlayer dl = new connectionlayer();
DataSet emp = new DataSet();
dl.LoadDataSet(CommandType.Text, "SELECT employeeId,LastName,FirstName FROM Employees", ref emp, "emp");
EmpListView.DataSource = emp;
EmpListView.DataBind();

}


protected void PagerNextPrevious_OnPagerCommand(object sender, DataPagerCommandEventArgs e)
{
switch (e.CommandName)
{

case "First":
e.NewStartRowIndex = 0;
e.NewMaximumRows = e.Item.Pager.MaximumRows;
break;
case "Previous":
e.NewStartRowIndex = e.Item.Pager.StartRowIndex - e.Item.Pager.PageSize;
e.NewMaximumRows = e.Item.Pager.MaximumRows;
break;
case "Next":
int NewIndexNo = e.Item.Pager.StartRowIndex + e.Item.Pager.PageSize;
if (NewIndexNo <= e.TotalRowCount)
{
e.NewStartRowIndex = NewIndexNo;
e.NewMaximumRows = e.Item.Pager.MaximumRows;
}
break;

case "Last":
e.NewStartRowIndex = e.TotalRowCount - e.TotalRowCount % e.Item.Pager.PageSize;
e.NewMaximumRows = e.Item.Pager.MaximumRows;
break;
}
}

protected void PagerNo_OnPagerCommand(object sender, DataPagerCommandEventArgs e)
{
int NewPageNo = Convert.ToInt32((e.Item.FindControl("txtPageNo") as TextBox).Text);
int NewIndexNo = e.Item.Pager.PageSize * (NewPageNo - 1);
if (NewIndexNo <= e.TotalRowCount)
{
e.NewStartRowIndex = NewIndexNo;
e.NewMaximumRows = e.Item.Pager.MaximumRows;
}
}
protected void EmpList_PreRender(object sender, EventArgs e)
{
DataBindList();
PagerRow.PageSize = 5;
}

Friday, October 29, 2010

add edit and delete xml item using XPath and xmlnode

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=false onrowcommand="GridView1_RowCommand" PageSize=20 AllowPaging=true Width="80%" >
<Columns>

<asp:TemplateField HeaderText="Sno.">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Name">
<ItemTemplate>
<%#Eval("ProjectName") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Client Name">
<ItemTemplate>
<%#Eval("ClientName") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Images">
<ItemTemplate>
<img src="../<%#Eval("ThumbImage") %>" width=100 height=100 border=0 />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" >
<ItemTemplate>
<asp:LinkButton ID="lnklink" Text="Edit" runat="server" CommandName="Edit" CommandArgument='<%#Eval("ProductId") %>' ></asp:LinkButton>
<asp:Button ID="Button2" runat="server" Text="Delete" CommandName="Del" CommandArgument='<%#Container.DataItemIndex%>' />

</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Xml;
using System.Web.UI.WebControls;

public partial class cpanel_Add_Project : System.Web.UI.Page
{
string Id
{
get
{
if (ViewState["Id"] == null)
return "";
else
return (string)ViewState["Id"];
}
set
{
ViewState["Id"] = value;
}
}
DataSet Table
{
get
{
if (ViewState["Table"] == null)
return new DataSet();
else
return (DataSet)ViewState["Table"];
}
set
{
ViewState["Table"] = value;
}
}
string ThumbImage
{
get
{
if (ViewState["ThumbImage"] == null)
return "";
else
return (string)ViewState["ThumbImage"];
}
set
{
ViewState["ThumbImage"] = value;
}
}

protected void Page_Load(object sender, EventArgs e)
{


if (!string.IsNullOrEmpty(Request.QueryString["id"]))
{
Id = Convert.ToString(Request.QueryString["id"]);
}
if (!IsPostBack)
{

BindData();

}

}
class ClsProducts
{
string _ProductId = string.Empty;

public string ProductId
{
get { return _ProductId; }
set { _ProductId = value; }
}
string _projectName = string.Empty;

public string ProjectName
{
get { return _projectName; }
set { _projectName = value; }
}
string _clientName = string.Empty;

public string ClientName
{
get { return _clientName; }
set { _clientName = value; }
}
string _thumbImage = string.Empty;

public string ThumbImage
{
get { return _thumbImage; }
set { _thumbImage = value; }
}
}
private void BindData()
{
XmlDocument item = new XmlDocument();

item.Load(Server.MapPath("~/") + "projects.xml");

XmlNodeList itemdata = item.SelectNodes("//projects/project");
if (itemdata != null)
{
List<ClsProducts> itemProduct = new List<ClsProducts>();
for (int n = 0; n < itemdata.Count; n++)
{
ClsProducts obj = new ClsProducts();
obj.ProductId = itemdata.Item(n).ChildNodes.Item(0).InnerText;
obj.ProjectName = itemdata.Item(n).ChildNodes.Item(1).InnerText;
obj.ClientName = itemdata.Item(n).ChildNodes.Item(2).InnerText;
obj.ThumbImage = itemdata.Item(n).ChildNodes.Item(3).InnerText;
itemProduct.Add(obj);

}
GridView1.DataSource = itemProduct;
GridView1.DataBind();
}
if (Id != "")
{
XmlNode xlist = item.SelectSingleNode("//projects/project[projectID=" + Id + "]");
if (xlist != null)
{
txtProjectName.Value = xlist.ChildNodes.Item(1).InnerText;
txtprojectClient.Value = xlist.ChildNodes.Item(2).InnerText;
ThumbImage = xlist.ChildNodes.Item(3).InnerText;
Image1.ImageUrl = "../" + ThumbImage;
}
else
{
Image1.Visible = false;
}
}
else
{
Image1.Visible = false;
}
}
protected void btnImage_Click(object sender, ImageClickEventArgs e)
{
if (UpThumbImage.HasFile)
{
string filename = DateTime.Now.ToString("MMddyyyyHHmmss") + UpThumbImage.FileName;
string location = Server.MapPath("~/images/thumbnails/") + filename;
UpThumbImage.PostedFile.SaveAs(location);
ThumbImage = "images/thumbnails/" + filename;
}
else
{
if (ThumbImage.Length == 0)
{
WebUtility.PageAlert(Page, "Please Upload Images!");
return;
}
}
XmlDocument item = new XmlDocument();

item.Load(Server.MapPath("~/") + "projects.xml");
if (Id!="")
{

XmlNode xlist = item.SelectSingleNode("//projects/project[projectID=" + Id + "]");
if (xlist != null)
{
xlist.ChildNodes.Item(1).InnerText = txtProjectName.Value;
xlist.ChildNodes.Item(2).InnerText = txtprojectClient.Value;
xlist.ChildNodes.Item(3).InnerText = ThumbImage;
item.Save(Server.MapPath("~/") + "projects.xml");
}

}
else
{
XmlNodeList xlist1 = item.SelectNodes("//projects/project");
string xmlvalue=""
+ "<projectID>" + DateTime.Now.ToString("MMddyyHHmmss")+ "</projectID>" +
"<projectName>"+txtProjectName.Value+"</projectName>"+
"<projectClient>"+txtprojectClient.Value+"</projectClient>"+
"<imagethumb>"+ThumbImage+"</imagethumb>"+
"";
XmlNode newnode = item.LastChild.FirstChild.Clone();

newnode.InnerXml = xmlvalue;
item.LastChild.AppendChild(newnode);
item.Save(Server.MapPath("~/") + "projects.xml");
}
BindData();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
Response.Redirect("Add-Project.aspx?id=" + e.CommandArgument.ToString());
}
else if (e.CommandName == "Del")
{
XmlDocument item = new XmlDocument();
int n = Convert.ToInt32(e.CommandArgument.ToString());
item.Load(Server.MapPath("~/") + "projects.xml");
XmlNodeList xlist = item.SelectNodes("//projects/project");
xlist.Item(n).ParentNode.RemoveChild(xlist.Item(n));
item.Save(Server.MapPath("~/") + "projects.xml");

WebUtility.PageAlert(Page, "Delete Product successfully", "Add-Project.aspx");
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<projects>
<project>
<projectID>4</projectID>
<projectName>project 4</projectName>
<projectClient>client 4</projectClient>
<imagethumb>images/thumbnails/4.jpg</imagethumb>
</project>
<project>
<projectID>5</projectID>
<projectName>project 5</projectName>
<projectClient>client 5</projectClient>
<imagethumb>images/thumbnails/5.jpg</imagethumb>
</project>
<project>
<projectID>6</projectID>
<projectName>project 6</projectName>
<projectClient>client 6</projectClient>
<imagethumb>images/thumbnails/6.jpg</imagethumb>
</project>
<project>
<projectID>7</projectID>
<projectName>project 7</projectName>
<projectClient>client 7</projectClient>
<imagethumb>images/thumbnails/7.jpg</imagethumb>
</project>
<project>
<projectID>102310214626</projectID>
<projectName>Rishabh Sharma</projectName>
<projectClient>Rishabh client</projectClient>
<imagethumb>images/thumbnails/10232010214626client5.png</imagethumb>
</project>
</projects>

Monday, October 18, 2010

Add confirm box on button click using C#

public static void ButtonAddConfirmation (WebControl control,string message )
{
control.Attributes.Add("onclick","if (confirm('" +message +"')){}else {return false}");
}

Tie button to textbox control

public static void TieButton(Page page,Control TextBoxToTie,Control ButtonToTie )   
     {                       
     string JsScript = "";
 if (ButtonToTie is LinkButton)            
{    JsScript = "if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) 
{"+ page.ClientScript.GetPostBackEventReference( ButtonToTie, "" ).Replace( ":", "$" ) + ";
return false;} else return true;";            
}            
else if (ButtonToTie is ImageButton)
 {  JsScript = "if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) 
{"+ page.ClientScript.GetPostBackEventReference( ButtonToTie, "" ).Replace( ":", "$" ) + ";return false;} 
else return true;";            
}            
else            
{                
JsScript = "if ((event.which && event.which == 13) || "+ "(event.keyCode && event.keyCode == 13)) 
{document."+ "forms[0].elements['"+ ButtonToTie.UniqueID.Replace( ":", "_" ) + "'].click();return false;
} else return true; ";            
} 
if (TextBoxToTie is HtmlControl)            
{ ((HtmlControl) TextBoxToTie).Attributes.Add( "onkeydown", JsScript );            
}            
else if (TextBoxToTie is WebControl)            
{                
((WebControl) TextBoxToTie).Attributes.Add( "onkeydown", JsScript );            
}        
}

Friday, October 15, 2010

Post Data using HttpWebRequest

public static string PostData(string url, string data, string contentType)
{
string result = "";
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = data.Length;
objRequest.ContentType = contentType;
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(data);
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
public static string PostData(string url, string data)
{
return PostData(url, data, "application/x-www-form-urlencoded");
}

Filter Rows from DataTable Using Filter


public static DataTable FilterRows(DataTable source)
{ string root = parentID;
DataTable result = source.Clone();
string filter = "CategoryID = '" + root + "'";
DataRow[] rows = source.Select(filter);
foreach (DataRow row in rows)
{
result.ImportRow(row);
}
return result;
}

Get record in specific range from DataTable

public static DataTable CopyTableRows(
DataTable source, int startIndex, int endIndex )
{
DataTable result = source.Clone();
for (int i = startIndex; i <= endIndex && i < source.Rows.Count; i++)
{
result.ImportRow( source.Rows[i] );
}
return result;
}

Saturday, September 11, 2010

onchange event in DropDownList through Jquery


$(document).ready(function() {
$('#<%=DropDownList1.ClientID %>').change(function() {
if (($("#<%=DropDownList1.ClientID %> option:selected").val() == "0"))
{
... // do your stuff
}
else
{
// do your stuff
}

});});

Cross browser opecity in css

.opecity{
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
filter: alpha(opacity=50);
-moz-opacity: 0.5;
-khtml-opacity: 0.5;
-webkit-opacity: 0.5;
opacity: 0.5;
}

Getting GridViewRow Value on Button Click Event

public void User_Click_detail(object sender, EventArgs e)
{
LinkButton LB = (LinkButton)sender;
GridViewRow Grid1 = (GridViewRow)LB.NamingContainer;
... int indexid = Convert.ToInt32((GridView1.DataKeys[Grid1.RowIndex].Values[0].ToString()));
//perform CRUD on based on indexid value
}
AJAX, asp, Asp.net, asp.net and sql server security, Asp.net IntemIndex, C#, Css, DataBinder.Eval, DataKeyNames, Datalist, Datapager, DataSet, DataTable, DropDownList, FindControl, gridview, JavaScript, jquery, Listview, Paging, Regex, RegularExpression, Repeater, Server side validation, Sql Server, timer, timercallback, Validation, XML, xmlnode, XPath