1.FOR DIRECT ENTER CLICK 2. FOR GRID VIEW 3.FOR PAGE INDEX CHANGING 4. IF THE COMMAND IS SELECT IN THE GRID VIEW 5. If the command is update in gridview 6. If the command is Delete in grid view 7. FOR DATALIST BIND 8. TABLE CONTROLS 9. For image upload and auto generation of CategoryId 10. For linking the pages by clicking images 11. If we go to next page not changing the dropdown list value back 12. To Delete the memory of session: 13.files download for click event 14. for getting current time ,date. 15. Date Formatting in ASP.NET 17. Video uploading
FOR
DIRECT ENTER CLICK
txtpassword.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btnlogin.UniqueID + "').click();return false;}} else {return true};");
FOR GRID VIEW public void Bind() { SqlCommand cmd = new SqlCommand("select * from application", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "application"); grid1.DataSource = ds; grid1.DataBind(); }
FOR PAGE INDEX CHANGING
protected void grid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e) { grid1.CurrentPageIndex = e.NewPageIndex; Bind(); } IF THE COMMAND IS
SELECT
IN THE GRID VIEW
protected void grid1_ItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "select") { TableCell c = (TableCell)e.Item.Controls[0]; Session["asd"]=((Label)c.Controls[1]).Text; SELECTING Session["prop"] = ((Label)c.Controls[1]).Text; }
THROUGH THIS SESSION
//Response.Redirect("applicantdetails.aspx");
If the command is
update
in gridview
if (e.CommandName == "update") { TableCell c = (TableCell)e.Item.Controls[0]; Session["asd"] = ((Label)c.Controls[1]).Text; Response.Redirect("applicationupdate.aspx"); In applicationupdate.aspx page ----SqlCommand cmd1 = new SqlCommand("update application set reservationorraterequest='" + ddlresorratereq.SelectedValue + "',firstname='" + txtfirstname.Text + "',lastname='" + txtlastname.Text + "',address='" + txtaddress.Text + "',address1='" + txtaddress1.Text + "',city='" + txtcity.Text + "',state='" + ddlstate.SelectedValue + "',zipcode='" + txtzip.Text + "',homephone='" + txthomephone.Text + "',workphone='" + txtworkphone.Text + "',cellphone='" + txtcellphone.Text + "',email='" + txtemail.Text + "',howtocontact='" + ddlcontact.SelectedValue + "',datetime='" + txtmonth.Text + "/" + txtdate1.Text + "/" + txtyear.Text + " " + ddldrophours.SelectedValue + ":" + ddldropminutes.SelectedValue + "" + ddlamorpm.SelectedValue + "',airport='" + txtairport.Text + "',airline='" + txtairline.Text + "',flightnumber='" + txtflightno.Text + " " + ddlflighttrip.SelectedValue + "',pickupaddress='" + txtpickupaddress.Text + "',destinationaddress='" + txtdestaddress.Text + "',interestedvehicle='" + ddlvehicleintersted.SelectedValue + "',noofpassengers='" + txtnoofpassegrs.Text + "',specialevent='" + listbxspecialevent.SelectedValue + "',specialinstruction='" + txtspecialinsrtns.Text + "',paymentmethod='" + ddlpaymentmethod.SelectedValue + "',cardtype='" +
ddlcardtype.SelectedValue + "',cardnumber='" + txtcardnumber.Text + "',cardholder='" + txtcardholder.Text + "',expirydate='" + ddlexpmonth.SelectedValue + "/" + ddlexpyear.SelectedValue + "',phonenumber='" + txtphoneno.Text + "',myshippingaddress='" + rdbtnshippingaddrs.SelectedValue + "',address2='" + txtaddress2.Text + "' where serialno='" + Session["asd"] + "'", con); -----cmd1.ExecuteNonQuery(); ClientScript.RegisterStartupScript(this.GetType(), "asd", "alert(\"updated successfully\")", true);
If the command is
Delete
in grid view
if (e.CommandName == "delete") { TableCell c = (TableCell)e.Item.Controls[0]; string s = ((Label)c.Controls[1]).Text; SqlCommand cmddelete = new SqlCommand("delete from application where serialno='" + s.ToString() + "'", con); cmddelete.ExecuteNonQuery(); Page.RegisterStartupScript("asd", "<script>alert('Details deleted successfully')"); Bind(); }
FOR DATALIST BIND SqlCommand cmd = new SqlCommand("select * from application where firstname='" + Session["searchbyname"] + "' or email='" + Session["searchbymail"] + "' or phonenumber='" + Session["searchbyphone"] + "'",con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "application"); DataList1.DataSource = ds; DataList1.DataBind();
TABLE CONTROLS TableRow tr1=new TableRow(); TableRow tr = new TableRow(); TableCell tc1 = new TableCell(); TableCell tc2 = new TableCell(); int i = 0; Table1.CellSpacing = 100; for (i = 0; i < 3; i++) {
TableCell tc = new TableCell(); ImageButton img = new ImageButton(); img.ID = i.ToString(); img.Click += new ImageClickEventHandler(img_Click); tc.Controls.Add(img); tr.Cells.Add(tc); Table1.Rows.Add(tr); } void img_Click(object sender, ImageClickEventArgs e) { ImageButton ig = (ImageButton)sender; Session["Categoryid"] = ig.ID; if (ig.ID == "0") { Image1.ImageUrl = "images/" + "2000.jpg"; } else if (ig.ID == "1") { Image1.ImageUrl = "images/" + "2009.jpg"; } else { Image1.ImageUrl = "images/" + "2147.jpg"; } }
For image upload and auto generation of CategoryId protected void Button1_Click(object sender, EventArgs e) { string q, q1; q = "select max(CategoryId) from Category_Info"; SqlCommand cd = new SqlCommand(q, con); SqlDataReader dr = cd.ExecuteReader(); dr.Read(); if (dr[0].ToString() == "") { i = 1000; } else { i = Convert.ToInt32(dr[0]) + 1; } dr.Close();
string img = CategoryUpload.PostedFile.FileName.Substring(CategoryUpload.PostedFile.FileName .LastIndexOf("//") + 1); string ext = img.Substring(img.Length - 4); CategoryUpload.PostedFile.SaveAs(Server.MapPath("images\\"+i.ToString()+ext) ); SqlCommand cmd=new SqlCommand("insert into Category_Info values('"+i+"','"+txtCategoryName.Text+"','"+i.ToString()+ext+"')",con); cmd.ExecuteNonQuery(); Response.Write("Inserted"); con.Close(); } protected void LinkButton1_Click(object sender, EventArgs e) { Response.Redirect("AddSubCategory.aspx"); }
For linking the pages by clicking images protected void Page_Load(object sender, EventArgs e) { display(); } private void display() { con.Open(); DataSet ds= new DataSet(); SqlDataAdapter da = new SqlDataAdapter("select * from Category_info", con); da.Fill(ds); int ctn=ds.Tables[0].Rows.Count; if (ctn > 0) { TableRow tr = new TableRow(); TableRow tr1 = new TableRow(); foreach (DataRow dr in ds.Tables[0].Rows) { TableCell tc = new TableCell();
TableCell tc1 = new TableCell(); if (j > 6 && j < 15) { ImageButton ibtn = new ImageButton(); ibtn.ID = dr["categoryid"].ToString(); ibtn.ImageUrl = "images/" + dr["categoryid"] + ".jpg"; ibtn.Width = 100; ibtn.Height = 100; ibtn.Click += new ImageClickEventHandler(ibtn_Click); tc.Controls.Add(ibtn); tr.Cells.Add(tc); Table1.Rows.Add(tr); LinkButton lbtn = new LinkButton(); lbtn.ID = "lkn"+dr["categoryid"].ToString(); lbtn.Text = dr["categoryid"].ToString(); lbtn.Click += new EventHandler(lbtn_Click); tc1.Controls.Add(lbtn); tr1.Cells.Add(tc1); Table1.Rows.Add(tr1);
} j++; } } } void lbtn_Click(object sender, EventArgs e) { LinkButton lkbtn = (LinkButton)sender; Session["categoryid"] = lkbtn.ID; Response.Redirect("usersub.aspx"); } void ibtn_Click(object sender, ImageClickEventArgs e) { ImageButton igbtn = (ImageButton)sender; Session["categoryId"] = igbtn.ID; Response.Redirect("usersub.aspx"); }
If we go to next page not changing the dropdown list value back
ddlstate.SelectedIndex = ddlstate.Items.IndexOf(ddlstate.Items.FindByText(dr["state"].ToString( )));
---------------------------------------------------------------string[] na = name.Split(new char[] { ',' });for spliting the string if (na[0] != "") {
l1.Text = na[0];
} else {
ln1.Visible = false; } if (na[1] != "") { l2.Text = na[1]; } else { ln2.Visible = false; } if (na[2] != "") { l3.Text = na[2]; } else { ln3.Visible = false; } if (na[3] != "") { l4.Text = na[3]; } else { ln4.Visible = false; }
To Delete the memory of session: Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); --------------------------------------------------------------------13. protected void lkdownload_Click(object sender, EventArgs e) { // string str = "SELECT * FROM PRODUCTS"; string str = "select categoryid,categoryname from products group by categoryid,categoryname";
SqlDataAdapter da = new SqlDataAdapter(str, con); DataSet ds2 = new DataSet(); da.Fill(ds2); FileStream fs2; StreamWriter sw2; fs2 = new FileStream(Server.MapPath("") + "/Inventory.xls", FileMode.Create, FileAccess.ReadWrite); sw2 = new StreamWriter(fs2); sw2.Write("
STYLE='FONT-WEIGHT:BOLD'>");
sw2.Write("
"); sw2.Write("COMPUMAX INVENTORY
"); sw2.Write(" | "); sw2.Write(""); sw2.Write("
"); sw2.Write(""); sw2.Write(DateTime.Now.ToShortDateString() + "
"); sw2.Write(" | "); sw2.Write("
"); sw2.Write("
"); sw2.Write(""); sw2.Write("www.gocmax.net
"); sw2.Write(" | "); sw2.Write("
"); sw2.Write("
"); sw2.Write(""); sw2.Write(""); sw2.Write("Category"); sw2.Write(" | "); sw2.Write(""); sw2.Write("Product Name"); sw2.Write(" | "); sw2.Write(""); sw2.Write("Description"); sw2.Write(" | "); sw2.Write(""); sw2.Write("Condition"); sw2.Write(" | "); sw2.Write(""); sw2.Write("Quantity On Hand"); sw2.Write(" | "); sw2.Write(""); sw2.Write("Price "); sw2.Write(" | "); sw2.Write("
"); sw2.Write(""); sw2.Write("");
sw2.Write(" | "); sw2.Write("
"); //sw2.Write(""); //sw2.Write(""); foreach (DataRow dr in ds2.Tables[0].Rows) { sw2.Write(" | "); sw2.Write(dr["categoryname"].ToString()); sw2.Write(" | "); sw2.Write("
"); string catid = dr["categoryid"].ToString(); string strp = "SELECT * FROM PRODUCTS where categoryid='"+catid+"'"; SqlDataAdapter dap = new SqlDataAdapter(strp, con); DataSet dsp = new DataSet(); dap.Fill(dsp); foreach (DataRow drp in dsp.Tables[0].Rows) { sw2.Write(""); sw2.Write(""); sw2.Write(" "); sw2.Write(" | "); sw2.Write(""); sw2.Write(drp["productname"].ToString()); sw2.Write(" | "); sw2.Write(""); sw2.Write(drp["description"].ToString()); sw2.Write(" | "); sw2.Write(""); sw2.Write(drp["condition"].ToString()); sw2.Write(" | "); sw2.Write(""); sw2.Write(drp["quantity"].ToString()); sw2.Write(" | "); sw2.Write(" |
align='left'>");
sw2.Write("$ :"+drp["price"].ToString()); sw2.Write("");
}
sw2.Write(""); sw2.Write("
");
} sw2.Write("
"); sw2.Write(""); sw2.Close(); fs2.Close();
//Page.RegisterStartupScript("document", "<script>window.open('Inventory.xls');"); Response.Redirect("Inventory.xls",false); // Response.WriteFile("Inventory.xls"); }
14.for getting current time ,date.
<script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E) { Message.Text = "You last accessed this page at: " + DateTime.Now; }
15. Handling Control Action Events Please enter your name: Hi uma, welcome to ASP.NET!
<script language="C#" runat="server"> void EnterBtn_Click(Object Src, EventArgs E) { Message.Text = "Hi " + HttpUtility.HtmlEncode(Name.Text) + ", welcome to ASP.NET!"; }
Handling Control Action Events
This sample demonstrates how to access a <asp:textbox> server control within the "Click" event of a <asp:button>, and use its content to modify the text of a <asp:label>.
16. Performing Page Navigation (Scenario 1) Hi Adam please click this link! <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E) { Random randomGenerator = new Random(DateTime.Now.Millisecond); int randomNum = randomGenerator.Next(0, 3); switch(randomNum) { case 0: Name.Text = "Scott"; break; case 1: Name.Text = "Fred"; break; case 2: Name.Text = "Adam"; break;
} AnchorLink.NavigateUrl = "controls_navigationtarget.aspx?name=" + System.Web.HttpUtility.UrlEncode(Name.Text); }
Performing Page Navigation (Scenario 1)
This sample demonstrates how to generate a HTML Anchor tag that will cause the client to navigate to a new page when he/she clicks it within the browser.
link!
Hi please click this
Next page:--------------- Hi Adam! <script language="C#" runat="server"> void Page_Load(Object Sender, EventArgs e) { if (!Page.IsPostBack) { NameLabel.Text = Request.Params["Name"]; } }
Handling Page Navigation
This sample demonstrates how to receive a navigation request from another page, and extract the querystring argument within the Page_Load event.
16. Date Formatting in ASP.NET Specifier d D t T f F g G M r s u Y dd ddd dddd hh HH mm MM MMM MMMM ss tt yy yyyy : /
Description Output Short Date 08/04/2007 Long Date 08 April 2007 Short Time 21:08 Long Time 21:08:59 Full date and time 08 April 2007 21:08 Full date and time (long) 08 April 2007 21:08:59 Default date and time 08/04/2007 21:08 Default date and time (long) 08/04/2007 21:08:59 Day / Month 08 April RFC1123 date Sun, 08 Apr 2007 21:08:59 GMT Sortable date/time 2007-04-08T21:08:59 Universal time, local timezone 2007-04-08 21:08:59Z Month / Year April 2007 Day 08 Short Day Name Sun Full Day Name Sunday 2 digit hour 09 2 digit hour (24 hour) 21 2 digit minute 08 Month 04 Short Month name Apr Month name April seconds 59 AM/PM PM 2 digit year 07 4 digit year 2007 seperator, e.g. {0:hh:mm:ss} 09:08:59 seperator, e.g. {0:dd/MM/yyyy} 08/04/2007
17.Video uploading Response.Write(video.PostedFile.ContentType.ToString()); if (video.PostedFile.FileName != "") { if (video.PostedFile.ContentType.Substring(0, 5) == "video") { string vi = video.PostedFile.FileName.Substring(video.PostedFile.FileName.LastInde xOf("\\") + 1); video.PostedFile.SaveAs(Server.MapPath("video/" + vi)); string s = "<embed id='emb1' runat='server' src='" + Server.MapPath("video/" + vi )+ "'>"; div.InnerHtml = s; } }