<html> <head> <title>Conditional CSS</title> <style type="text/css"> body { color:blue; } </style> <!--[if IE 7]> <style type="text/css"> body { background-color:red; } </style> <![endif]--> </head> <body> <p> Conditional CSS </p> </body> </html>
If you are displaying a DataTable with a DataGrid and would like to have it sorted
by a column, here is the two line solution (copy it to a DataView, sort the DataView, and then define the DataSource of the DataGrid as the DATAVIEW, not the DataGrid. <%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <script runat="server"> public void Page_Load(Object sender, EventArgs E) { DataTable dt = GetDataTable(); //sort the DataTable DataView dv=dt.DefaultView; dv.Sort="LastName DESC"; dgMembers.DataSource = dv; dgMembers.DataBind(); } private DataTable GetDataTable() { //create table DataTable dt = new DataTable("Members"); dt.Columns.Add("ID",Type.GetType("System.Int32")); dt.Columns.Add("LastName",Type.GetType("System.String")); dt.Columns.Add("Lectures",Type.GetType("System.Int32")); //create fields DataColumn[] pk = new DataColumn[1]; pk[0] = dt.Columns["ID"]; dt.PrimaryKey = pk; dt.Columns["ID"].AutoIncrement = true; dt.Columns["ID"].AutoIncrementSeed = 1; dt.Columns["ID"].ReadOnly = true; //fill rows DataRow dr; for(int x=1;x<=10;x++) { //make every other one different if(Math.IEEERemainder(x,2) == 0) { dr = dt.NewRow(); dr["LastName"] = "Riss"; dr["Lectures"] = 14; dt.Rows.Add(dr); } else { dr = dt.NewRow(); dr["LastName"] = "Anders"; dr["Lectures"] = 3; dt.Rows.Add(dr); } } return dt; } </script> <html> <head> </head> <body> <form runat="server"> <asp:DataGrid id="dgMembers" runat="server"></asp:DataGrid> </form> </body> </html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default13.aspx.cs" Inherits="Default13" %> <!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:GridView ID="grd" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="Key" HeaderText="Date" /> <asp:BoundField DataField="Value" HeaderText="Date" /> </Columns> </asp:GridView> </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; using System.Collections; using System.Collections.Generic; public partial class Default13 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DateTime StartingDate = DateTime.Parse("03/29/2008"); DateTime EndingDate = DateTime.Parse("04/30/2008"); Hashtable ht=new Hashtable(); foreach (DateTime date in GetDateRange(StartingDate, EndingDate)) { if (date.DayOfWeek.ToString() == "Monday" || date.DayOfWeek.ToString()=="Sunday") { ht.Add(date.ToShortDateString(),date.DayOfWeek.ToString()); } } grd.DataSource=ht; grd.DataBind(); } private static List<DateTime> GetDateRange(DateTime StartingDate, DateTime EndingDate) { if (StartingDate > EndingDate) { return null; } List<DateTime> rv = new List<DateTime>(); DateTime tmpDate = StartingDate; do { rv.Add(tmpDate); tmpDate = tmpDate.AddDays(1); } while (tmpDate <= EndingDate); return rv; } }
You can create your own configuration section and use one of the staic
methods in the System.Configuration namespace to retrieve the information.
Attached is a simple example. Also lookup configSection element and
IConfigurationSectionHandler interface for additional information.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserSection.aspx.cs" Inherits="UserSection" %> <!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:GridView ID="GridView1" runat="server"> <Columns> <asp:BoundField DataField="Key" HeaderText="Key" /> <asp:BoundField DataField="Value" HeaderText="Value" /> </Columns> </asp:GridView> </div> </form> </body> </html>
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 UserSection : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GridView1.DataSource = ConfigExample(); GridView1.DataBind(); } private static ArrayList ConfigExample() { Hashtable htList = new Hashtable(); System.Collections.Specialized.StringDictionary dictionary = (System.Collections.Specialized.StringDictionary) System.Configuration.ConfigurationSettings.GetConfig("MySection"); IEnumerator iterator = dictionary.GetEnumerator(); DictionaryEntry entry; while (iterator.MoveNext()) { entry = (DictionaryEntry)iterator.Current; htList.Add(entry.Key); } return arList; } }
/* IConfigurationSectionHandler Implementation */ 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.Xml; /// <summary> /// Summary description for MySectionHander /// </summary> namespace MyNamespace { public class MySectionHandler : System.Configuration.IConfigurationSectionHandler { #region IConfigurationSectionHandler Members public object Create(object parent, object configContext, XmlNode section) { System.Collections.Specialized.StringDictionary mySection = new System.Collections.Specialized.StringDictionary(); if (section == null || section.ChildNodes.Count == 0) { return mySection; } foreach (XmlNode node in section.ChildNodes) { mySection.Add(node.Attributes[0].Value, node.Attributes[1].Value); } return mySection; } #endregion } }
/* APP.CONFIG OR WEB.CONFIG */ <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="MySection" type="MyNamespace.MySectionHandler, MyAssemblyName"/> </configSections> <MySection> <add key="key1" value="value1" /> <add key="key2" value="value2" /> <add key="key3" value="value3" /> </MySection> </configuration>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewInsideGridView.aspx.cs" Inherits="GridViewInsideGridView" %> <!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:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True" DataKeyNames="Id" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"> <Columns> <asp:BoundField DataField="Id" /> <asp:BoundField DataField="Name" /> </Columns> </asp:GridView> <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" Height="50px" Width="176px"> <Fields> <asp:BoundField DataField="Id" /> <asp:BoundField DataField="Qul" /> </Fields> </asp:DetailsView> </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 GridViewInsideGridView : System.Web.UI.Page { DataSet ds; protected void Page_Load(object sender, System.EventArgs e) { ds = Data(); if (!this.IsPostBack) { if (Session["parent"] == null) { GridView1.DataSource = ds.Tables["Parent"]; GridView1.DataBind(); } else { GridView1.DataSource = Session["Parent"] as DataTable; GridView1.DataBind(); } } } private DataSet Data() { DataTable dt = new DataTable(); dt.Columns.Add("Id", typeof(int)); dt.Columns.Add("Name", typeof(string)); dt.Rows.Add(new object[] { 1, "aaaa" }); dt.Rows.Add(new object[] { 2, "bbbb" }); dt.Rows.Add(new object[] { 3, "cccc" }); dt.TableName = "Parent"; DataTable dtc = new DataTable(); dtc.Columns.Add("Id", typeof(int)); dtc.Columns.Add("Qul", typeof(string)); dtc.Rows.Add(new object[] { 1, "aaaa" }); dtc.Rows.Add(new object[] { 2, "bbbb" }); dtc.Rows.Add(new object[] { 3, "bbbb" }); dtc.TableName = "Child"; DataSet ds = new DataSet(); ds.Tables.Add(dt); ds.Tables.Add(dtc); Session["Parent"] = dt; return ds; } protected void GridView1_SelectedIndexChanged(object sender, System.EventArgs e) { DataView dv = new DataView(ds.Tables["Child"]); dv.RowFilter = "Id=" + this.GridView1.SelectedValue.ToString(); DetailsView1.DataSource = dv; DetailsView1.DataBind(); } }
Let’s take an Excel Workbook with a worksheet, called Data, that contains 1000 rows of data broken into 2 columns, ID and Data.
I want to copy this data into a SQL Server Database Table, called ExcelData, with the same schema.
Just a little bit of code transfers the data from the Excel Spreadsheet into the SQL Server Database Table:
// Connection String to Excel Workbook string excelConnectionString = @"Provider=Microsoft .Jet.OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;"""; // Create Connection to Excel Workbook using (OleDbConnection connection = new OleDbConnection(excelConnectionString)) { OleDbCommand command = new OleDbCommand ("Select ID,Data FROM [Data$]", connection); connection.Open(); // Create DbDataReader to Data Worksheet using (DbDataReader dr = command.ExecuteReader()) { // SQL Server Connection String string sqlConnectionString = "Data Source=.; Initial Catalog=Test;Integrated Security=True"; // Bulk Copy to SQL Server using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString)) { bulkCopy.DestinationTableName = "ExcelData"; bulkCopy.WriteToServer(dr); } } }
SqlBulkCopy is a new feature in ADO.NET 2.0 that gives you DTS-like speeds when you need to programmatically copy data from one database to another. Late last night I needed to harness SqlBulkCopy when for some unknown reason my beloved Red Gate Tools kept hanging when trying to transfer data from SQL Server 2000 to SQL Server 2005.
Lucky for me my situation was simple. I had identical tables on both databases. I just needed to populate those empty tables on SQL Server 2005 with the data on SQL Server 2000. It took me about 20 minutes to write the code as SqlBulkCopy does the bulk of the work.
Shown below is my slapped-together CopyData Class that accepts 2 connection strings, one for the source database and one for the destination database. A single method CopyTable is called with the name of the table whose data needs to be transferred from one database to another.
///
/// CopyData
///
public class CopyData
{
string _sourceConnectionString;
string _destinationConnectionString;
public CopyData(string sourceConnectionString,
string destinationConnectionString)
{
_sourceConnectionString =
sourceConnectionString;
_destinationConnectionString =
destinationConnectionString;
}
public void CopyTable(string table)
{
using (SqlConnection source =
new SqlConnection(_sourceConnectionString))
{
string sql = string.Format(”SELECT * FROM [{0}]“,
table);
SqlCommand command = new SqlCommand(sql, source);
source.Open();
IDataReader dr = command.ExecuteReader();
using (SqlBulkCopy copy =
new SqlBulkCopy(_destinationConnectionString))
{
copy.DestinationTableName = table;
copy.WriteToServer(dr);
}
}
}
}
It assumes you passed in valid connection strings, the databases actually exist, and the table exists at both databases. If not, you can count on an unhandled SqlException being thrown at you.
SqlBulkCopy has the option of accepting an IDataReader as input, so the CopyTable method opens up a connection to the source database and does a “SELECT *” on the source table using the SqlCommand object’s ExecuteReader.
An instance of SqlBulkCopy is created and passed the connectionstring of the destination database in its constructor. The name of the destination table is provided and WriteToServer takes all the information from the IDataReader and puts it in the empty destination table.
Copying table data is as simple as:
CopyData copier = new CopyData(”.ConnectionString1.”,
“.ConnectionString2.”);
copier.CopyTable(”.TableName.”);
All spreadsheet applications (Excel, Calc etc.) understand semicolon separated files natively, so everyone can use this method – you don’t even have to use Excel for it to work.
public static void ExportToExcel(DataTable table, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in table.Columns)
{
context.Response.Write(column.ColumnName + “;”);
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i <>
{
context.Response.Write(row[i].ToString().Replace(”;”, string.Empty) + “;”);
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = “text/csv”;
context.Response.AppendHeader(”Content-Disposition”, “attachment; filename=” + name + “.csv”);
context.Response.End();
}
>
Then just call this method and pass the DataTable and the filename as parameters.
ExportToSpreadsheet(table, “products”);
The method is static so you can use it anywhere in a web application. Put it on a page, a HTTP Handler, add it to the App_Code folder or stick it in a separate assembly. As long as you call it from a web application it will work.
The ASP.NET web controls provide a TabIndex property, but this property only applies to Internet Explorer and can't be used to programmatically set the focus to a control of your choice. To perform this task, you'll need the help of some JavaScript code. In this case, you need to find the JavaScript object that corresponds to the control, and call its focus() method.The easiest way to handle this task is to create a function that accepts a control, extracts its client-side ID, and uses it to generate the JavaScript function required to set the focus to that control. You can then register this function so it will set the focus the next time the next time the page is sent to the user.
Here's the function you will need in C#:
private void SetFocus(Control ctrl)
{
// Define the JavaScript function for the specified control.
string focusScript = "<script language='javascript'>" +
"document.getElementById('" + ctrl.ClientID +
"').focus();</script>";
// Add the JavaScript code to the page.
Page.RegisterStartupScript("FocusScript", focusScript);
}
In order to use AJAX in ASP.NET we need to have a minimum of ASP.NET 2.0 Framework and AJAX Extensions 1.0 for ASP.NET.
In order to upload a file using AJAX, we are in need of the following main Web Server controls:
1. FileUpload Server Control
2. Button Server Control
Apart from the above, we need to specify the usual AJAX tags ScriptManager, UpdatePanel and ContentTemplate so that during run time the ASP.NET AJAX will know which section of the web page needs to be updated. Let us take a look at the code which uses the above:
<%@ Page Language="C#" AutoEventWireup="true"%>
<html>
<head>
<script runat="server">
protected void UploadFile(object src, EventArgs e)
{
if (myFile.HasFile)
{
string strFileName;
strFileName = myFile.FileName;
myFile.PostedFile.SaveAs(Server.MapPath(".") + "//" + strFileName);
}
}
script>
<script language="javascript" type="text/javascript">
function showWait()
{
if ($get('myFile').value.length > 0)
{
$get('UpdateProgress1').style.display = 'block';
}
}
script>
<title>File Uploadtitle>
head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload" />
Triggers>
<ContentTemplate>
<asp:FileUpload ID="myFile" runat="server" />
<asp:Label ID="lblMsg" runat="server">asp:Label>
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="UploadFile" OnClientClick="javascript:showWait();"/>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<asp:Label ID="lblWait" runat="server" BackColor="#507CD1"
Font-Bold="True" ForeColor="White"
Text="Please wait ... Uploading file">asp:Label>
ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>