We often want the first option in a drop-down list to not default to the first item in the list. Instead we would prefer the option of adding a --Select Item-- at the top of the asp:DropDownList. After the DataBind, execute an Item.Insert. ddlAuthor.DataTextField = "FullName"; ddlAuthor.DataValueField = "AuthorID"; ddlAuthor.DataSource = authorDB.GetAuthors(); ddlAuthor.DataBind(); ddlAuthor.Items.Insert(0, "-- Select Author --");
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultipleUploads.aspx.cs" Inherits="MultipleUploads" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <p id="upload-area"> <input id="File1" type="file" runat="server" size="60" /> </p> <input id="AddFile" type="button" value="Add file" onclick="addFileUploadBox()" /> <p> <asp:Button ID="btnSubmit" runat="server" Text="Upload Now" OnClick="btnSubmit_Click" /></p> <span id="Span1" runat="server" /> </div> </form> <script type="text/javascript"> function addFileUploadBox() { if (!document.getElementById || !document.createElement) return false; var uploadArea = document.getElementById ("upload-area"); if (!uploadArea) return; var newLine = document.createElement ("br"); uploadArea.appendChild (newLine); var newUploadBox = document.createElement ("input"); // Set up the new input for file uploads newUploadBox.type = "file"; newUploadBox.size = "60"; // The new box needs a name and an ID if (!addFileUploadBox.lastAssignedId) addFileUploadBox.lastAssignedId = 100; newUploadBox.setAttribute ("id", "dynamic" + addFileUploadBox.lastAssignedId); newUploadBox.setAttribute ("name", "dynamic:" + addFileUploadBox.lastAssignedId); uploadArea.appendChild (newUploadBox); addFileUploadBox.lastAssignedId++; } </script> </body> </html>
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.IO; public partial class MultipleUploads : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { String UpPath; UpPath = "C:\\UploadedUserFiles"; if (!Directory.Exists(UpPath)) { Directory.CreateDirectory("C:\\UploadedUserFiles\\"); } } protected void btnSubmit_Click(object sender, EventArgs e) { HttpFileCollection uploads = HttpContext.Current.Request.Files; for (int i = 0; i < uploads.Count; i++) { HttpPostedFile upload = uploads[i]; if (upload.ContentLength == 0) continue; string c = System.IO.Path.GetFileName(upload.FileName); // We don't need the path, just the name. try { upload.SaveAs("C:\\UploadedUserFiles\\" + c); Span1.InnerHtml = "Upload(s) Successful."; } catch (Exception Exp) { Span1.InnerHtml = "Upload(s) FAILED."; } } } }
Step1.Create an asp.net application with 2 Button and a GridViewas shown below.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicTextboxJavascript.aspx.cs" Inherits="DynamicTextboxJavascript" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <script type="text/javascript"> function addElement() { var ni = document.getElementById('myDiv'); var numi = document.getElementById('theValue'); var num = (document.getElementById('theValue').value -1)+2; numi.value = num; var newdiv = document.createElement('div'); var divIdName = 'my'+num+'Div'; newdiv.setAttribute('id',divIdName); newdiv.innerHTML = '<input type="text" name="TextBox'+num+'" value="TextBox'+num+'" >'; ni.appendChild(newdiv); } </script> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> <div id="myDiv"> </div> <input type="button" id="btnOfficial" value="Add Another TextBox" onclick="addElement();" /> <input type="hidden" value="1" id="theValue" runat="server" /> <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Read" /> </form> </body> </html>
Step 2: Add the following code behind.
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; public partial class DynamicTextboxJavascript : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSave_Click(object sender, EventArgs e) { ArrayList alForm = new ArrayList(); //Because my textbox id is started // with 2 like(TextBox2,TextBox3..... for (int i = 2; i< Request.Form.Count - 2;i++) { string strId = "TextBox" + i.ToString(); string strValue = Request.Form[strId].ToString(); alForm.Add(strValue); strValue = ""; } //Uncomment this line and test. //foreach (string x in Request.Form) //{ // string strValue = Request.Form[x].ToString(); // alForm.Add(strValue); //} GridView1.DataSource = alForm; GridView1.DataBind(); } }
There are some features in the System.Data.DataTable class that a lot of developers don’t utilize. I base that statement on different code samples I’ve seen on blogs and article bases during the last couple of years. Some of these features can improve the performance. Calculated columns First of all, I’ll create a DataTable manually, even though it is more likely to be created from querying a database. DataTable dt = new DataTable(); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Price", typeof(double)); dt.Columns.Add("ItemsInStock", typeof(double)); Imaging that there is 100 rows in that DataTable and you now want to calculate total price of all item currently in stock. The calculation is Price*ItemsInStock. What I see in a lot of code samples is that this column is calculated in the database by a SQL statement like this: “SELECT name, price, itemsinstock, (price*itemsinstock) AS stockprice FROM products” The overhead in letting the database do the calculation is not that much in this particular example, because it is a simple multiplication of two rows. It could easily be more complicated than this example. The thing is, that .NET performs these kinds of calculation much more efficient than a database and that’s why we would like .NET to do them. The DataTable class supports on-the-fly calculated columns and they are perfect to use in the example. Just add another column to the DataTable and give it a calculation formula. dt.Columns.Add("StockPrice", typeof(double), "Price*ItemsInStock"); The calculation expression ("Price*ItemsInStock") can also use predefined functions like an if-statement. "IIF(ItemsInStock = 0, 100, PricePrice*ItemsInStock)" There a many different functions to use in the calculation expression. Auto increment Let’s say you want to bind the DataTable to a DataGrid in an ASP.NET page and that you want a column to display the row number. This can be done by adding a column to the DataTable that has enabled the AutoIncrement property. DataColumn col = new DataColumn("#", typeof(int)); col.AutoIncrement = true; col.AutoIncrementSeed = 1; dt.Columns.Add(col); Now you have a column named “#” that contains the row number. Querying the DataTable You can query a DataTable in different ways in order to find the row you need. If you want all the rows in the DataTable that matches a search expression then you would use the Select method. DataRow[] rows = dt.Select("Price > 159"); The Select method returns a DataRow array you can loop through like you normally would loop through all the rows in the DataTable. foreach (DataRow row in rows) { DoSomeThing(); } If you just want a single row based on the DataTable’s primary key, then you have to let the DataTable know which of the columns is the primary key. dt.PrimaryKey = new DataColumn[] { dt.Columns["#"]}; When you have defined the DataTable’s primary key, you can now query directly for that key and get the whole row returned by using the Find method. DataRow oneRow = dt.Rows.Find("19"); This method is faster than the Select method. If there is no row with the primary key value of “19”, the Find method returns null. So, before you use the returned DataRow, you probably want to check if the row exist first. if (oneRow != null) { DoSomething(); } Column totals You decide to add totals to the footer row of the DataGrid and therefore needs to sum the integer type columns. You can do that very easy with the Compute method. dt.Compute("sum(price)", null) Or, put a filter on dt.Compute("sum(price)", "price > 40") The DataTable class is very powerful and can improve the performance by removing calculations to .NET instead of doing them on the database. The different ways to query the rows are also very impressive and flexible and that makes the DataTable a serious in-memory database.
While for many applications, it is easier to display data-bound information using the Repeater, DataList, or DataGrid, it is possible to display database information using the Table Web server control. In the most common scenario for displaying data in a Table control, each row of the table represents a data row from the data source, and each cell of the table displays a single field from a row. Unlike the list controls ( Repeater, DataList, etc. ), the Table control does not have a mechanism for automatically iterating through the rows in a data source. Therefore, you must do this yourself. For general details about data binding in Web server controls, see Web Forms Data Binding. To display database information in a Table Web server control * Set the contents of a TableCell control to the data to be displayed. Most often you set the cell's Text property to an expression that extracts data from a data source. It is also possible to include controls in a TableCell control and bind the controls to a source of data. For details about using controls to display information, see Adding Rows and Cells Dynamically to a Table Control. The following example illustrates one way to display data in a Table control. The sample shows an event-handling method for a button. The method loops through the DefaultView object of a dataset, creating a TableRow control for each row in the dataset. The code then creates a TableCell control in each table row and sets its Text property to the "Id" field of the current data row.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicTextBox.aspx.cs" Inherits="DynamicTextBox" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Table ID="Table1" runat="server" CellPadding="2" CellSpacing="2"></asp:Table> <asp:Button ID="btnFill" runat="server" Text="Fill" OnClick="btnFill_Click" /> </div> </form> </body> </html>
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;
public partial class DynamicTextBox : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public DataTable GetCustomMadeDataTable()
{
//Create a new DataTable object
System.Data.DataTable objDataTable = new System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("Id", typeof(string));
objDataTable.Columns.Add("Column1", typeof(string));
objDataTable.Columns.Add("Column2", typeof(string));
objDataTable.Columns.Add("Column3", typeof(string));
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 0; i <= 10; i++)
{
dr = objDataTable.NewRow();
dr[0] = "Id" + i.ToString();
dr[1] = "Item" + i.ToString();
dr[2] = "Product" + i.ToString();
dr[3] = "Description" + i.ToString();
objDataTable.Rows.Add(dr);
}
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["dtTemp"] = objDataTable;
return objDataTable;
}
protected void btnFill_Click(object sender, EventArgs e)
{
DataTable dt = GetCustomMadeDataTable() as DataTable;
DataView dv = dt.DefaultView;
// Create a row with one column for each row in the DataView
foreach (DataRowView dataRow in dv)
{
TableRow tRow = new TableRow();
TableCell tCell = new TableCell();
TableCell tCell2 = new TableCell();
TableCell tCell3 = new TableCell();
tCell.Text = dataRow.Row.ItemArray[0].ToString();
tCell2.Text = dataRow.Row.ItemArray[1].ToString();
tCell3.Text = dataRow.Row.ItemArray[2].ToString();
tRow.Cells.Add(tCell);
tRow.Cells.Add(tCell2);
tRow.Cells.Add(tCell3);
Table1.Rows.Add(tRow);
}
}
}
Among the differences between version 1.1 and 2.0 of .NET Framework is the many new controls. Even though most of them don’t add new functionality they make a lot of things much easier and cleaner than before. Some of these new controls in ASP.NET are the HTML controls HtmlHead, HtmlMeta and HtmlLink.
They don’t add much new functionality by them selves, but look at how clean the code becomes when you use them:
protected void Page_Load(object sender, EventArgs e)
{
AddMetaContentType();
AddMetaTag(“keywords”, “word1, word2, word3…”);
AddMetaTag(“description”, “bla bla bla”);
AddStyleSheet(“/includes/style.css”);
}
private void AddMetaContentType()
{
HtmlMeta meta = new HtmlMeta();
meta.HttpEquiv = “content-type”;
meta.Content = Response.ContentType + “; charset=” + Response.ContentEncoding.HeaderName;
Page.Header.Controls.Add(meta);
}
private void AddMetaTag(string name, string value)
{
HtmlMeta meta = new HtmlMeta();
meta.Name = name;
meta.Content = value;
Page.Header.Controls.Add(meta);
}
private void AddStyleSheet(string relativePath)
{
HtmlLink link = new HtmlLink();
link.Href = relativePath;
link.Attributes["type"] = “text/css”;
link.Attributes["rel"] = “stylesheet”;
Page.Header.Controls.Add(link);
}
This is much more cleaner than adding literal controls to the page header or whatever trick you used before. Just remember to add a runat=”server” attribute to the tag of your web page.
Q.How do I show numbers with 5 fixed digits with leading zeroes
Ans:
int _num1 = 123;
int _num2 = 45;
int _num3 = 123456;
String.Format(”{0:00000}”, _num1); //”00123″
String.Format(”{0:00000}”, _num2); //”00045″
String.Format(”{0:00000}”, _num3); //”123456″
String.Format(”{0:d5}”, _num1); //”00123″
String.Format(”{0:d5}”, _num2); //”00045″
String.Format(”{0:d5}”, _num3); //”123456″
Q:Can I substitute a string for a value?
Ans:
Yes:
String.Format(”{0:yes;;no}”, value)
This will print “no” if value is 0, “yes” if value is 1.
Q:What’s the most efficient way to convert a type into a string?
Ans:
Double testDouble = 19.95;
String testString1 = String.Format(”{0:C}”, testDouble); // Boxing operation required.
String testString2 = testDouble.ToString(”C”); // No boxing operation required.
Q:How can I use curly brackets within a formatted number?
Ans:
Yes - doubling them escapes them. For example:
string.format(”{{SomeString}}={0}”,”Hello”);
will produce: “{SomeString}=Hellow”
Q:How can I convert from currency back to a number?
Ans:
You can add the bitmapped values of the Globalization.NumberStyles enumeration.
// format double to currency
str = string.Format(”{0:c}”, pmt);
// parse currency formatted string to double
double.Parse(str, Globalization.NumberStyles.AllowCurrencySymbol +
Globalization.NumberStyles.AllowDecimalPoint +
Globalization.NumberStyles.AllowThousands);
Q:What’s a good way to format currency?
Ans:
double val = 4219.6;
str = string.Format(”{0:$#,#.00;Call Us;Call Us}”, val);
This will return “$4,219.60″. The .00 will force 2 decimals and the “;Call Us;Call Us” to show the text “Call Us” in place of negative and null values respectively. (Just in case)
Q:How do I format an integer, with commas for thousands?
A:
string str = string.Format(”{0:#,0}”, intValue);
Q:How can I format a phone number to look like 800.555.1212?
A:
There’s no direct way to do this; however you can get dashes in the output. So you can do this:
string tempStr = String.Format(”{0:###-###-####}”, 8005551212);
string result =tempStr.Replace(’-’,’.’);
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HideColumnGridview.aspx.cs" Inherits="HideColumnGridview" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <script language="JavaScript"> function hideColumn() { col_num = document.getElementById("column_numbder").value; rows = document.getElementById("GridView1").rows; for(i=0;i <rows.length;i++) { rows[i].cells[col_num].style.display="none"; } } </script> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </div> <input id="column_numbder" type="text"> <input type="button" value="Hide" onclick="hideColumn()"> </form> </body> </html>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; public partial class HideColumnGridview : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Session["strTemp"] != null) { GridView1.DataSource = Session["strTemp"] as DataTable; GridView1.DataBind(); } else { GridView1.DataSource = GetCustomMadeDataTable(); GridView1.DataBind(); } } } public DataTable GetCustomMadeDataTable() { //Create a new DataTable object System.Data.DataTable objDataTable = new System.Data.DataTable(); //Create three columns with string as their type objDataTable.Columns.Add("Id", typeof(string)); objDataTable.Columns.Add("Column1", typeof(string)); objDataTable.Columns.Add("Column2", typeof(string)); objDataTable.Columns.Add("Column3", typeof(string)); //Adding some data in the rows of this DataTable DataRow dr; for (int i = 0; i <= 20; i++) { dr = objDataTable.NewRow(); dr[0] = i.ToString(); dr[1] = "Column1Data" + i.ToString(); dr[2] = "Column2Data" + i.ToString(); dr[3] = "Column3Data" + i.ToString(); objDataTable.Rows.Add(dr); } DataColumn[] dcPk = new DataColumn[1]; dcPk[0] = objDataTable.Columns["Id"]; objDataTable.PrimaryKey = dcPk; Session["strTemp"] = objDataTable; return objDataTable; } }
When you add a Label control to your page you can associate the label to a control, for example to a TextBox or CheckBox etc. If you use the AssociatedControlID and associate a control to the label, the runtime will automatically render the “for” attribute to the label element (The “for” attribute is use to specify which control the label is associated to).
For example:
<asp:Label ID=”Label1″ Runat=”server” Text=”Label” AssociatedControlID=”TextBox1″>></asp:Label>
<asp:TextBox ID=”TextBox1″ Runat=”server”>
The control above will be genereated to the following code at runtime:
<label for=”TextBox1″ id=”Label1″>Label</label>
<input name=”TextBox1″ type=”text” id=”TextBox1″/>
If the “for” attribute is added to a label element, you can click the mouse button on the label and the associated control (in the above example the TextBox) will be selected. If you associate a checkbox to a label, the checbox will be selected or deslected if you click on the label assocated for the checkbox.