In the case of Edit event
DatagridName.EditItemIndex = e.Item.ItemIndex;
datagrid.DataSource="Tablename";
datagrid.DataBind();
In case of Cancel event
Datagridname.EditItemIndex = -1;
datagrid.DataSource="Tablename";
datagrid.DataBind();
In case of paging
Datagridname.CurrentPageIndex = e.NewPageIndex;
datagrid.DataSource="Tablename";
datagrid.DataBind();
In case of updating
Datagridname.EditItemIndex = -1;
datagrid.DataSource="Tablename";
datagrid.DataBind();
Wednesday, April 8, 2009
Monday, March 30, 2009
how to Cache an object in asp.net using c#?
Suppose you want to cache an object say like datatable,you can easily do so by
Cache.Insert("DtIndustry", DtIndustry, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration);
The above command cache the datatable called DtIndustry from 10 min.
Next if u want that object first check the cache first if cache is null then fill that datatable and again add that object into cache.
if (Cache["DtIndustry"] == null)
{
DtIndustry = objDll.retieve_DtIndustry();
Cache.Insert("DtIndustry", DtIndustry, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration); ;
}
else
{
DtIndustry = (DataTable)Cache["DtIndustry"];
}
Cache.Insert("DtIndustry", DtIndustry, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration);
The above command cache the datatable called DtIndustry from 10 min.
Next if u want that object first check the cache first if cache is null then fill that datatable and again add that object into cache.
if (Cache["DtIndustry"] == null)
{
DtIndustry = objDll.retieve_DtIndustry();
Cache.Insert("DtIndustry", DtIndustry, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration); ;
}
else
{
DtIndustry = (DataTable)Cache["DtIndustry"];
}
Tuesday, March 24, 2009
Error while opening connection with sql as connection is already open using asp.net and c#?
There may e scenario where you are getting error while establishing connection with the database as connection is already open.
it can be easily solved using
if (mysqlcmd.Connection.State == ConnectionState.Closed)
{
mysqlcmd.Connection.Open();
}
//same for closing the connection
if (mysqlcmd.Connection.State == ConnectionState.Open)
{
mysqlcmd.Connection.Close();
}
it can be easily solved using
if (mysqlcmd.Connection.State == ConnectionState.Closed)
{
mysqlcmd.Connection.Open();
}
//same for closing the connection
if (mysqlcmd.Connection.State == ConnectionState.Open)
{
mysqlcmd.Connection.Close();
}
Friday, March 20, 2009
How to add new column in data table in asp.net c#?
Requirment may arise when you want to add column in data table at runtime.It is a really simple task to do.
dt.Columns.Add(new DataColumn("Column1", System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Column2", System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Column3", System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Column1", System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Column2", System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Column3", System.Type.GetType("System.String")));
Tuesday, March 17, 2009
How to send email using asp.net and c#?
Code for sending email:
using System.Web.Mail;
private void Button1_Click(object sender, System.EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To = txtTo.Text;
mail.From = txtFrom.Text;
mail.Subject = txtSubject.Text;
mail.Body = txtBody.Text;
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(mail);
}
You can also send email using
System.Net.Mail
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.IsBodyHtml = true;
mail.Headers.Add("Precedence", "bulk");//If u want to send mail in bulk
mail.From = new System.Net.Mail.MailAddress("EmailId", "Sender Name");
mail.ReplyTo = new System.Net.Mail.MailAddress("EmailId", "Name");
mail.Subject = " Subject";
System.Net.Mail.Attachment MailAttach = new System.Net.Mail.Attachment("path");
mail.Attachments.Add(MailAttach);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp server name", "port no");
smtp.Credentials = new System.Net.NetworkCredential("User Id for that email", "Password");
smtp.EnableSsl = true;
mail.To.Add("Reciever Email Id ");
mail.Body = "Body Text";
smtp.Send(mail);
using System.Web.Mail;
private void Button1_Click(object sender, System.EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To = txtTo.Text;
mail.From = txtFrom.Text;
mail.Subject = txtSubject.Text;
mail.Body = txtBody.Text;
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(mail);
}
You can also send email using
System.Net.Mail
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.IsBodyHtml = true;
mail.Headers.Add("Precedence", "bulk");//If u want to send mail in bulk
mail.From = new System.Net.Mail.MailAddress("EmailId", "Sender Name");
mail.ReplyTo = new System.Net.Mail.MailAddress("EmailId", "Name");
mail.Subject = " Subject";
System.Net.Mail.Attachment MailAttach = new System.Net.Mail.Attachment("path");
mail.Attachments.Add(MailAttach);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp server name", "port no");
smtp.Credentials = new System.Net.NetworkCredential("User Id for that email", "Password");
smtp.EnableSsl = true;
mail.To.Add("Reciever Email Id ");
mail.Body = "Body Text";
smtp.Send(mail);
Monday, March 16, 2009
How to check that the file which user is uploading should be only word file using asp.net RegularExpressionValidator?
ValidationExpression="^.+(.DOC|.DOCX|.doc|.docx)$">
Thursday, March 12, 2009
how to Post data from html using asp.net as a backend?
Some times you want to post your data from html page..
do this was a really simple task
<form method="post" action="URL" id="frmAddmissionEnquiry">
<input type="text" id="txtname" />
<input type="text" id="txtEmail" />
</form>
Capturing the same in asp page.
Request.Form["txtname"].ToString()
Returing back to the same form
Response.Redirect(Request.UrlReferrer.ToString());
do this was a really simple task
<form method="post" action="URL" id="frmAddmissionEnquiry">
<input type="text" id="txtname" />
<input type="text" id="txtEmail" />
</form>
Capturing the same in asp page.
Request.Form["txtname"].ToString()
Returing back to the same form
Response.Redirect(Request.UrlReferrer.ToString());
Sunday, March 8, 2009
Paging in grid view using asp.net with c#?
There are certain scenario when we required pagination in gridview
Solution for this is very simple.
In .aspx page
<asp:GridView ID="GvEmployee" runat="server" AllowPaging="True" Width="100%" PageSize="10" OnPageIndexChanging="GvEmployee_PageIndexChanging">
<columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
In c# Page
protected void GvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GvEmployee.PageIndex = e.NewPageIndex;
databind();
}
catch (Exception ex)
{
}
}
Solution for this is very simple.
In .aspx page
<asp:GridView ID="GvEmployee" runat="server" AllowPaging="True" Width="100%" PageSize="10" OnPageIndexChanging="GvEmployee_PageIndexChanging">
<columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
In c# Page
protected void GvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GvEmployee.PageIndex = e.NewPageIndex;
databind();
}
catch (Exception ex)
{
}
}
Friday, March 6, 2009
How to bind datat using Gridview in asp.net with c#?
Today we will learn how to use gridview in asp.net using c# to display records using dataset,datatable?
In .cs page
GridView1.DataSource = DataTable or Dataset
GridView1.DataBind()
In aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="CandidateName" DataField="name" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Email" DataField="emailid" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="DateTime" DataField="DateTime" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="Phone" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="CanName" runat="server" Text='<% #Bind("fname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LblClass" runat="server" Text='<%#Bind("Class") %>'>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDLClass" Width="100%" runat="server" DataSource='<%#Class%>' DataTextField="Class" DataValueField="id" >
<asp:listitem value="1" Text="1"></asp:listitem>
<asp:listitem value="2" Text="2"></asp:listitem>
<asp:listitem value="3" Text="3"></asp:listitem> </asp:DropDownList>
</EditItemTemplate>
</Columns>
</asp:GridView>
In .cs page
GridView1.DataSource = DataTable or Dataset
GridView1.DataBind()
In aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="CandidateName" DataField="name" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Email" DataField="emailid" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="DateTime" DataField="DateTime" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="Phone" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="CanName" runat="server" Text='<% #Bind("fname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LblClass" runat="server" Text='<%#Bind("Class") %>'>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDLClass" Width="100%" runat="server" DataSource='<%#Class%>' DataTextField="Class" DataValueField="id" >
<asp:listitem value="1" Text="1"></asp:listitem>
<asp:listitem value="2" Text="2"></asp:listitem>
<asp:listitem value="3" Text="3"></asp:listitem> </asp:DropDownList>
</EditItemTemplate>
</Columns>
</asp:GridView>
Thursday, March 5, 2009
Using string builder to write html on asp.net aspx page?
using System.Text;
StringBuilder sb = new StringBuilder();
sb.append("Your html body");
div.innerHTML=sb.ToString();
StringBuilder sb = new StringBuilder();
sb.append("Your html body");
div.innerHTML=sb.ToString();
Tuesday, March 3, 2009
How to tell search engine the page has moved using 301 permanent redirect asp.net c#?
Many a times you have a situation where you have to rename your page or move your page to a new location.In short URL for that page is change.we can tell search engine that this page is redirected to a newer location using 301 status.
HttpContext context = HttpContext.Current;
if(url=="Your Old URL")
context.Response.Status = "301 Moved Permanently";
context.Response.AddHeader("Location", strUrl );
context.Response.End();
endif
HttpContext context = HttpContext.Current;
if(url=="Your Old URL")
context.Response.Status = "301 Moved Permanently";
context.Response.AddHeader("Location", strUrl );
context.Response.End();
endif
Monday, March 2, 2009
How to generate unique number in asp.net using c#?
Many a times u want to generate unique number
string TranId = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Millisecond.ToString();
string TranId = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Millisecond.ToString();
Sunday, March 1, 2009
Connection string in web.config asp.net c#
We can also specify connection string in our web.config file.
In asp.net 1.1 we can specify connection in 2 ways
1) In AppSettings
<appSettings>
<add key="ConnectionInfo" value="server=servername;uid=userid;pwd=password;Initial Catalog=database"/>
<appSettings>
2)connectionStrings
<add connectionString="Server=severname;Database=DB;UID=userid; pwd=password;" name="conn" providerName="MySql.Data.MySqlClient;"/>
</connectionStrings>
In asp.net 1.1 we can specify connection in 2 ways
1) In AppSettings
<appSettings>
<add key="ConnectionInfo" value="server=servername;uid=userid;pwd=password;Initial Catalog=database"/>
<appSettings>
2)connectionStrings
<add connectionString="Server=severname;Database=DB;UID=userid; pwd=password;" name="conn" providerName="MySql.Data.MySqlClient;"/>
</connectionStrings>
Thursday, February 26, 2009
Image resizing asp.net c#
Some times you want to resize images as per your required size using asp.net.
using System.Drawing;
using System.Drawing.Drawing2D;
Resizeimage(intheight, intwidth, userPostedFile.FileName.ToString(), userPostedFile.InputStream);
public string Resizeimage(int intHeight, int intWidth, string ImageUrl, System.IO.Stream Buffer)
{
try
{ string filepath = ConfigurationManager.AppSettings["UploadURL"];
string savepath = ConfigurationManager.AppSettings["SaveURL"];
string filename;
string[] imagefilename = new string[2];
char[] split ={ '.' };
imagefilename = ImageUrl.Split(split);
imagefilename[0] = imagefilename[0].Replace(" ", "_") + DateTime.Now.ToFileTime();
filename = (imagefilename[0].ToString() + "." + imagefilename[1].ToString());
System.Drawing.Image image = System.Drawing.Image.FromStream(Buffer);
int srcWidth = image.Width;
int srcHeight = image.Height;
Decimal sizeRatio = ((Decimal)srcHeight / srcWidth);
Bitmap bmp = new Bitmap(intWidth, intHeight);
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, intWidth, intHeight);
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
bmp.Save(filepath + intHeight.ToString() + System.IO.Path.GetFileName(filename));
string strImageUrl=savepath+intHeight.ToString() + System.IO.Path.GetFileName(filename);
bmp.Dispose();
image.Dispose();
return strImageUrl;
}
catch (Exception ex)
{
// MessageBox("Some Error has occured while uploading the images");
}
return "";
}
using System.Drawing;
using System.Drawing.Drawing2D;
Resizeimage(intheight, intwidth, userPostedFile.FileName.ToString(), userPostedFile.InputStream);
public string Resizeimage(int intHeight, int intWidth, string ImageUrl, System.IO.Stream Buffer)
{
try
{ string filepath = ConfigurationManager.AppSettings["UploadURL"];
string savepath = ConfigurationManager.AppSettings["SaveURL"];
string filename;
string[] imagefilename = new string[2];
char[] split ={ '.' };
imagefilename = ImageUrl.Split(split);
imagefilename[0] = imagefilename[0].Replace(" ", "_") + DateTime.Now.ToFileTime();
filename = (imagefilename[0].ToString() + "." + imagefilename[1].ToString());
System.Drawing.Image image = System.Drawing.Image.FromStream(Buffer);
int srcWidth = image.Width;
int srcHeight = image.Height;
Decimal sizeRatio = ((Decimal)srcHeight / srcWidth);
Bitmap bmp = new Bitmap(intWidth, intHeight);
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, intWidth, intHeight);
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
bmp.Save(filepath + intHeight.ToString() + System.IO.Path.GetFileName(filename));
string strImageUrl=savepath+intHeight.ToString() + System.IO.Path.GetFileName(filename);
bmp.Dispose();
image.Dispose();
return strImageUrl;
}
catch (Exception ex)
{
// MessageBox("Some Error has occured while uploading the images");
}
return "";
}
W3c error on asp.net pages due to script tag on page?
certain times we put javascript on the page itself. but putting javascript on the page gives w3c validation error.
solution for this is
solution for this is
Generating random number asp.net c#
using System.Security;
protected void Page_Load(object sender, EventArgs e)
{ string abc = "";
for (int i = 0; i < abc =" RandomNumberGenerator(6);" rng =" System.Security.Cryptography.RandomNumberGenerator.Create();" chars =" new" validchars = "abcdefghijklmnopqrstuvwxyzABCEDFGH IJKLMNOPQRSTUVWXYZ1234567890!@$%^*();
for (int i = 0; i < length; i++)
{ byte[] bytes = new byte[1];
rng.GetBytes(bytes);
Random rnd = new Random(bytes[0]);
chars[i] = validChars[rnd.Next(0, 61)];
}
return (new string(chars));
}
}
protected void Page_Load(object sender, EventArgs e)
{ string abc = "";
for (int i = 0; i < abc =" RandomNumberGenerator(6);" rng =" System.Security.Cryptography.RandomNumberGenerator.Create();" chars =" new" validchars = "abcdefghijklmnopqrstuvwxyzABCEDFGH IJKLMNOPQRSTUVWXYZ1234567890!@$%^*();
for (int i = 0; i < length; i++)
{ byte[] bytes = new byte[1];
rng.GetBytes(bytes);
Random rnd = new Random(bytes[0]);
chars[i] = validChars[rnd.Next(0, 61)];
}
return (new string(chars));
}
}
Anchor Title vs alt tag
Q) Where to use alt and where to use title in anchor tag?
Ans: Its all depends on your requirment.
alt tag is for w3c validation and in IE it will display text on mouse hover.
title tag works in the same way, it will display text on mouse hover in all browser. if you have specified both title and alt tag then on mouse hover titlte tag will be displayed.
one thing to be noted if u dont want mouse hover dont specify title tag but alt tage is necessary as per w3c validation.
Ans: Its all depends on your requirment.
alt tag is for w3c validation and in IE it will display text on mouse hover.
title tag works in the same way, it will display text on mouse hover in all browser. if you have specified both title and alt tag then on mouse hover titlte tag will be displayed.
one thing to be noted if u dont want mouse hover dont specify title tag but alt tage is necessary as per w3c validation.
Wednesday, February 25, 2009
F5 problem..asp.net
Whenever we press f5 insert query between page execution whole page execute again.
Solution for this
1) Capcha
2)Maintaining session state and viewstate
How to maintain session and view state
protected void Page_PreRender(Object sender, EventArgs e)
{
ViewState["update"] = Session["update"];
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());//to avoid problem of refresh frm Browser
}
}
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString())
{
//Code
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}
if user press f5 again then the buttonclick will execute again but it will not enter in
if (Session["update"].ToString() == ViewState["update"].ToString())
bcoz now session["update"] value has change.
Solution for this
1) Capcha
2)Maintaining session state and viewstate
How to maintain session and view state
protected void Page_PreRender(Object sender, EventArgs e)
{
ViewState["update"] = Session["update"];
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());//to avoid problem of refresh frm Browser
}
}
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString())
{
//Code
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}
if user press f5 again then the buttonclick will execute again but it will not enter in
if (Session["update"].ToString() == ViewState["update"].ToString())
bcoz now session["update"] value has change.
Friday, February 20, 2009
How to send SQL parameters to sqlDataAdapter?
DataAdapter.SelectCommand.Parameters
.Add(New SqlParameter("@SomeParameter", someValue))
or
DataAdapter.SelectCommand.Parameters.Add("@SomeParameter", SqlDbType.NChar);
DataAdapter.SelectCommand.Parameters[0].Value = SomeParameter;
Thursday, February 12, 2009
GetDocumentById problem in javascript using masterpage
Many times you have faced a problem that you were not able to find the control which is there on ur page using document.getElementById("").
The solution for this problem is use document.getElementByID("")
The solution for this problem is use document.getElementByID("")
Subscribe to:
Posts (Atom)