SQL Select Command
SQL Select Command
[code:c#]
// SQL Select Command
SqlCommand mySqlSelect = new SqlCommand("select * from categories",
mySQLconnection);
mySqlSelect.CommandType = CommandType.Text;
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);
// Convert DataSet to DataTable by getting DataTable at first zero-based index of
DataTableCollection
DataTable myDataTable = myDataSet.Tables[0];
[/code]
Above C# code shows how to fill the DataSet with data retrieved from the SQL
Database and convert it into a single DataTable. Next step is to display the data stored
in DataTable. You can bind the Data Table directly to the ASP.Net Data presentation
controls such as GridView, DataList or repeater to display the data. Or you can read the
data stored in each DataRow using the C# foreach loop as following:
[code:c#]
// foreach loop to get each DataRow of DataTable retrieved from DataSet
foreach (DataRow dRow in myDataTable.Rows)
{
Response.Write(dRow[ "categoryId" ].ToString() + " " + dRow[ "categoryName"
].ToString() + "<br/>");
}
[/code
p 2008
Now the next step is also necessary to retrieve the values of columns stored in each
row added to the ArrayList collection. Following C# code shows how to retrieve the
ArrayList item as object, then convert it to DataRow and read the column value to
display it on the ASP.Net web page:
[code:c#]
// foreach loop to get each item of ArrayList
foreach (Object objRow in myArrayList)
{
Response.Write(((DataRow)objRow)[ "categoryId" ].ToString() + " " +
((DataRow)objRow)[ "categoryName" ].ToString() + "<br/>");
}
[/code]
dataRow["Units_In_Pack"] = "3";
// add new data row to the data table.
myDataTable.Rows.Add(dataRow);
// similarly adds the second row to the DataTable
dataRow = myDataTable.NewRow();
dataRow["Unit_Name"] = "ASP.Net 2.0 with AJAX [4 in 1 Pack]";
dataRow["Unit_Price"] = "39.39";
dataRow["Units_In_Pack"] = "4";
myDataTable.Rows.Add(dataRow);
// similarly adds the third row to the DataTable
dataRow = myDataTable.NewRow();
dataRow["Unit_Name"] = "ASP.Net 3.5 with AJAX [4 in 1 Pack]";
dataRow["Unit_Price"] = "42.19";
dataRow["Units_In_Pack"] = "4";
myDataTable.Rows.Add(dataRow);
myDataTable.AcceptChanges();
GridView1.DataSource = myDataTable;
GridView1.DataBind();
[/code]
Above C# code shows how to create a DataTable and bind it to GridView to display the
data stored in it. To filter the Rows you use the following C# code line before the
"GridView1.DataSource = myDataTable":
myDataTable.DefaultView.RowFilter = "unit_price < 40";
Above filter expression will generate the customized view within the myDataTable
object of DataTable. RowFilter property accepts the string value similar to the where
clause of SQL select query. For example: "columnName = 10", "columnName <= 10",
"columnName >= 10" or "columnName <> 10" for integer values, and "columnName =
Tim" for string values.
myDataTable.DefaultView.RowFilter = "unit_price < 40";
GridView1.DataSource = myDataTable;
GridView1.DataBind();
You can use both properties of DefaultView property of DataTable to sort the filtered
rows. Or you can use one of them to Sort all the rows present in the DataTable. Above
code will generate the following output:
Above C# code shows the use of sort parameter with string value to filter the rows of
DataTable based on search filterExpression. You can match the output here:
while(rdr.Read())
{
// Operate on fetched data
}
}
catch(Exception exp)
{
MessageBox(exp.Message);
}
finally
{
if(cmd != null)
cmd.Close();
if(con != null)
con.Close();
if(rdr != null)
rdr.Dispose();
}
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
m.Id = (int)reader[0];
m.Name = reader[1].ToString();
m.Age = (int)reader[2];
sequence.Add(m);
}
dataGridView1.DataSource = sequence;
}
finally
{
sqlCon.Close();
}
Inside the using statement, we can use myClazz as a regular instance of MyClass in
this case, call its publicmethod. Outside the using statement, myClazz doesn't exist.
What happens behind the scenes? Actually, it's very simple. The C# compiler will translate
the above usingstatement at compile time into something like this:
The foreach statement repeats a group of embedded statements for each element in an array or an
object collection. The foreach statement is used to iterate through the collection to get the desired
information, but should not be used to change the contents of the collection to avoid unpredictable side
effects.
Remarks
The embedded statements continue to execute for each element in the array or collection. After the
iteration has been completed for all the elements in the collection, control is transferred to the next
statement following the foreach block.
At any point within the foreach block, you can break out of the loop using the break keyword, or step
directly to the next iteration in the loop by using the continue keyword.
A foreach loop can also be exited by the goto, return, or throwstatements.
For more information on the foreach keyword and code samples, see the following topics:
Using foreach with Arrays (C# Programming Guide)
How to: Access a Collection Class with foreach (C# Programming Guide)
Example
In this example, foreach is used to display the contents of an array of integers.
// cs_foreach.cs
class ForEachTest
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}
Output
0
1
2
3
5
8
13
}
}
// Abstract product A
public abstract class AbstractProductA
{
public abstract void MethodA();
}
// Abstract product B
public abstract class AbstractProductB
{
public abstract void MethodB();
}
// Product A1
public class ProductA1: AbstractProductA
{
public override void MethodA()
{
Console.WriteLine("ProductA1.MethodA() Called");
}
}
// Product A2
public class ProductA2: AbstractProductA
{
public override void MethodA()
{
Console.WriteLine("ProductA2.MethodA() Called");
}
}
// Product B1
public class ProductB1: AbstractProductB
{
public override void MethodB()
{
Console.WriteLine("ProductB1.MethodB() Called");
}
}
// Product B2
public class ProductB2: AbstractProductB
{
public override void MethodB()
{
Console.WriteLine("ProductB2.MethodB() Called");
}
}
// Client class, consumer of products and
// user of Abstract Factory
public class Client
{
public static void Main()
{
AbstractFactory factory;
AbstractProductA prodA;
AbstractProductB prodB;
// Create instances of products from factory A
<script type="text/JavaScript">
alert('hello world');
</script>
As you can see from the example above, the developer isn't restricted to displaying one
message box.
To accomplish this we simply use the Page's reference as the key in theHashTable. We
obtain a reference to the current executing page by casting the
current IHttpHandler toSystem.Web.UI.Page. The current IHttpHandler can be
obtained from HttpContext.Current.Handler. In most cases this will be a class either
directly or indirectly derived from System.Web.UI.Page.
Source Code
Collapse | Copy Code
public class MessageBox
{
private static Hashtable m_executingPages = new Hashtable();
private MessageBox(){}
public static void Show( string sMessage )
{
// If this is the first time a page has called this method then
if( !m_executingPages.Contains( HttpContext.Current.Handler ) )
{
// Attempt to cast HttpHandler as a Page.
Page executingPage = HttpContext.Current.Handler as Page;
if( executingPage != null )
{
// Create a Queue to hold one or more messages.
Queue messageQueue = new Queue();
// Add our message to the Queue
messageQueue.Enqueue( sMessage );
// Add our message queue to the hash table. Use our page reference
// (IHttpHandler) as the key.
m_executingPages.Add( HttpContext.Current.Handler, messageQueue );
// Wire up Unload event so that we can inject
// some JavaScript for the alerts.
executingPage.Unload += new EventHandler( ExecutingPage_Unload );
}
}
else
{
// If were here then the method has allready been
// called from the executing Page.
// We have allready created a message queue and stored a
// reference to it in our hastable.
Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ];
// Add our message to the Queue
queue.Enqueue( sMessage );
}
}
// Our page has finished rendering so lets output the
// JavaScript to produce the alert's
private static void ExecutingPage_Unload(object sender, EventArgs e)
{
// Get our message queue from the hashtable
Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ];
<style type="text/css">
#pscroller1{
width: 200px;
height: 100px;
border: 1px solid black;
padding: 5px;
background-color: lightyellow;
}
#pscroller2{
width: 350px;
height: 20px;
border: 1px solid black;
padding: 3px;
}
#pscroller2 a{
text-decoration: none;
}
</style>
<script type="text/javascript">
</script>
<script type="text/javascript">
/***********************************************
* Pausing up-down scroller- Dynamic Drive (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/
pausescroller.prototype.initialize=function(){
this.tickerdiv=document.getElementById(this.tickerid)
this.visiblediv=document.getElementById(this.tickerid+"1")
this.hiddendiv=document.getElementById(this.tickerid+"2")
this.visibledivtop=parseInt(pausescroller.getCSSpadding(this.tickerdiv))
//set width of inner DIVs to outer DIV's width minus padding (padding assumed to be top padding x 2)
this.visiblediv.style.width=this.hiddendiv.style.width=this.tickerdiv.offsetWidth(this.visibledivtop*2)+"px"
this.getinline(this.visiblediv, this.hiddendiv)
this.hiddendiv.style.visibility="visible"
var scrollerinstance=this
document.getElementById(this.tickerid).onmouseover=function(){scrollerinstance.mouseoverBol=1}
document.getElementById(this.tickerid).onmouseout=function(){scrollerinstance.mouseoverBol=0}
if (window.attachEvent) //Clean up loose references in IE
window.attachEvent("onunload",
function(){scrollerinstance.tickerdiv.onmouseover=scrollerinstance.tickerdiv.onmouseout=null})
setTimeout(function(){scrollerinstance.animateup()}, this.delay)
}
// ------------------------------------------------------------------// animateup()- Move the two inner divs of the scroller up and in sync
// -------------------------------------------------------------------
pausescroller.prototype.animateup=function(){
var scrollerinstance=this
if (parseInt(this.hiddendiv.style.top)>(this.visibledivtop+5)){
this.visiblediv.style.top=parseInt(this.visiblediv.style.top)-5+"px"
this.hiddendiv.style.top=parseInt(this.hiddendiv.style.top)-5+"px"
setTimeout(function(){scrollerinstance.animateup()}, 50)
}
else{
this.getinline(this.hiddendiv, this.visiblediv)
this.swapdivs()
setTimeout(function(){scrollerinstance.setmessage()}, this.delay)
}
// ------------------------------------------------------------------// swapdivs()- Swap between which is the visible and which is the hidden div
// -------------------------------------------------------------------
pausescroller.prototype.swapdivs=function(){
var tempcontainer=this.visiblediv
this.visiblediv=this.hiddendiv
this.hiddendiv=tempcontainer
}
pausescroller.prototype.getinline=function(div1, div2){
div1.style.top=this.visibledivtop+"px"
div2.style.top=Math.max(div1.parentNode.offsetHeight, div1.offsetHeight)+"px"
}
// ------------------------------------------------------------------// setmessage()- Populate the hidden div with the next message before it's visible
// -------------------------------------------------------------------
pausescroller.prototype.setmessage=function(){
var scrollerinstance=this
if (this.mouseoverBol==1) //if mouse is currently over scoller, do nothing (pause it)
setTimeout(function(){scrollerinstance.setmessage()}, 100)
else{
var i=this.hiddendivpointer
var ceiling=this.content.length
this.hiddendivpointer=(i+1>ceiling-1)? 0 : i+1
this.hiddendiv.innerHTML=this.content[this.hiddendivpointer]
this.animateup()
}
}
</script>
<script type="text/javascript">
</script>
<asp:ScriptManager id="Scrptmanagr" runat="server"></asp:ScriptManager>
<asp:UpdatePanel id="updtpanl" runat="server">
<ContentTemplate>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$
ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [arrange_by_id], [arrange_by] FROM [arrange_by]">
</asp:SqlDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:HyperLink ID="HyperLink3" NavigateUrl='<%#
string.Format("{0}?SortingType={1}",Request.AppRelativeCurrentExecutionFilePath,
Eval("arrange_by_id"))%>' runat="server"><%# Eval("arrange_by")
%></asp:HyperLink>
</ItemTemplate>
<SeparatorTemplate>
|
</SeparatorTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$
ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [alphabet_id],[arrange_by_id], [value] FROM [alphabet] WHERE
([arrange_by_id] = @arrange_by_id)">
<SelectParameters>
<asp:QueryStringParameter Name="arrange_by_id" QueryStringField="SortingType"
Type="Int32" DefaultValue="1" />
</SelectParameters>
</asp:SqlDataSource>
<br /><br />
<asp:Repeater ID="Repeater2" runat="server" DataSourceID="SqlDataSource2">
<ItemTemplate>
<asp:HyperLink ID="hyper1" runat="server"
NavigateUrl='<%#string.Format("{0}?SortingType={1}&SortBy={2}",Request.AppRelative
CurrentExecutionFilePath, Eval("arrange_by_id"),Eval("value"))%>'><%#
Eval("value")%></asp:HyperLink>
</ItemTemplate>
<SeparatorTemplate>
|
</SeparatorTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
C# Code behind:
}
protected void MySponsoredChildrenList_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "ViewProfile")
{
int ChildIDQuery =
Convert.ToInt32(e.Item.FindControl("ChildID"));
Response.Redirect("~/ChildDescription.aspx?ID=" + ChildIDQuery);
}
}