Tuesday, January 14, 2014
Toggle Two Classes in Jquery - Best way
Toggle Two Classes in Jquery - Best way |
$("#TriggerElement").toggle(function()
{
$('#TargerElement').removeClass("FirstClass").addClass("SecondClass");
}, function() {
$('#TargerElement').removeClass("SecondClass").addClass("FirstClass");
});
$('#TriggerElement').click(function(){ $('#TargerElement').toggleClass('FirstClass','SecondClass'); });
Wednesday, January 8, 2014
Limit characters in textbox textarea with counter
Bind Text Counter
function TextCounter (CountLimit, Elem, CounterElem) {
var elem = $("#" + Elem);var Counterelem = $("#" + CounterElem);
elem.bind("keyup focus", function () {
setCount(elem[0], Counterelem,CountLimit);
});
setCount(elem[0], Counterelem,CountLimit);
}
function setCount (src, elem,limit) {
var chars = src.value.length;
if (chars > limit) {
src.value = src.value.substr(0, limit);
chars = limit;
}
elem.html(limit - chars);
}
Calling Method
TextCounter(5,'samp','counter');
Allow only numeric in text box jquery
Use the following code for allowing only numbers while entering in text box
var Elem=$("#"+ElemId);
Elem.on('input propertychange', function () {
Elem.val(Elem.val().replace(/[^0-9]/g, ''));
});
Javascript Keycode for Chrome,Mozilla Firefox,Internet Explorer
Javascript Keycode for Chrome,Mozilla Firefox,Internet Explorer |
keypress
keypress
character codes are not key-specific and may be enirely different fromkeydown/keyup
key codes.Opera MSIE Firefox Safari Chrome Key pressed
_________________________________________________________ 8 8 8 8 8 Backspace 9 9 9 9 9 Tab 13 13 13 13 13 Enter 16 16 16 16 16 Shift 17 17 17 17 17 Ctrl 18 18 18 18 18 Alt 19 19 19 19 19 Pause, Break 20 20 20 20 20 CapsLock 27 27 27 27 27 Esc 32 32 32 32 32 Space 33 33 33 33 33 Page Up 34 34 34 34 34 Page Down 35 35 35 35 35 End 36 36 36 36 36 Home 37 37 37 37 37 Left arrow 38 38 38 38 38 Up arrow 39 39 39 39 39 Right arrow 40 40 40 40 40 Down arrow 44 44 44 44 PrntScrn (see below†) 45 45 45 45 45 Insert 46 46 46 46 46 Delete 48-57 48-57 48-57 48-57 48-57 0 to 9 65-90 65-90 65-90 65-90 65-90 A to Z 112-123 112-123 112-123 112-123 112-123 F1 to F12 144 144 144 144 144 NumLock 145 145 145 145 145 ScrollLock 188 188 188 188 188 , < 190 190 190 190 190 . > 191 191 191 191 191 / ? 192 192 192 192 192 ` ~ 219 219 219 219 219 [ { (see below‡) 220 220 220 220 220 \ | 221 221 221 221 221 ] } 222 222 222 222 222 ' "†
keyup
events only.‡
The following key codes differ across browsers:
keydown/keyup event.keyCode Opera MSIE Firefox Safari Chrome Key pressed _________________________________________________________ 59 186 59 186 186 ; : 61 187 107 187 187 = + 109 189 109 189 189 - _ 219 91 91 91 91 WIN Key (Start) 0 93 93 93 93 WIN Menu Opera All Others (NumLock On/Off) Key pressed _________________________________________________________ 48/45 96/45 Numpad 0 Ins 49/35 97/35 Numpad 1 End 50/40 98/40 Numpad 2 Down 51/34 99/34 Numpad 3 Pg Down 52/37 100/37 Numpad 4 Left 53/12 101/12 Numpad 5 54/39 102/39 Numpad 6 Right 55/36 103/36 Numpad 7 Home 56/38 104/38 Numpad 8 Up 57/33 105/33 Numpad 9 Pg Up 42/42 106/106 Numpad * 43/43 107/107 Numpad + 45/45 109/109 (45 is also Ins) Numpad - 78/46 110/46 (78 is also N) Numpad . Del 47/47 111/111 Numpad /
10 useful libraries for JavaScript developers
10 useful libraries for JavaScript developers |
Here I highlight ten tools that you can use to enhance your users' experience on your website.
Hammer.js
Probably one of the lightest JavaScript libraries around, hammer.js weighs at only 2KB. The library offers touch support for touch devices. The library allows a developer to add tap, double tap, drag, hold and transform actions. In addition, hammer.js can be bound to an HTML element allowing a touch event to return a callback with any kind of array whether it is an event, rotation, position, scale or touch.
HTML Canvas Library
Even with the new
Smoke.js
Have you ever wanted to customize alert notifications for your website? Smoke.js is a small JavaScript library that helps you do that. The library replaces the default alert function with CSS notifications that do not require any JavaScript frameworks. Each alert can be customized inside functions by specifying styles using CSS3 animations and backgrounds.
Kinetic.js
The
JSZip
If you are looking to serve your users with zip files without wasting server resources and bandwidth, JSZip can do it for you. Not only is it simple to use but it allows you to zip multiple files without generating a lot of data. By getting the client-side to do the heavy-lifting, no server-side resource is used allowing you to use the saved bandwidth for other things.
PDFKit
Allowing PDF document viewing or download on your site will require that all your documents reside in that format. The PDFKit document generation library makes your work easy by creating printable PDF documents for you. Generating documents has been made easy and only requires a few function calls. It supports vector graphics, font and image embedding and annotations within the generated documents. The library runs on the node.js platform and has a great API for integrating with apps using server-side JavaScript.
Fitvids.js
If you deliver video on your website, you need the flexibility to resize your video embeds. Unfortunately, this can be a little hectic as you have to code that into every video that you embed. Fitvids.js saves you that hustle by use of a JQuery plugin. With this plugin, you can add fluid video embeds to make responsive websites that your users will love to interact with.
Impress.js
Who still uses programs like Powerpoint when your browser can serve the same purpose? Theimpress.js library turns your browser into a powerful presentation tool. It uses CSS3 transforms and transition to deliver powerful presentation features right within the browser window. Just visit the link above to get the feel of what this library can do.
Colors
Color adds.....well, color to your website and applications. The Color JavaScript library allows you to manipulate colors in multiple ways and can generate random color values. In addition, it can get complimentary color values and handle unit conversions of multiple types including RGB to Hexadecimal, Hexadecimal to RGB among others.
GMap
Do you find it difficult or challenging to embed Google Maps on sites? This GMap offers a flexible and highly customizable way of embedding Google Maps onto your website. The plugin weighs in at only 2KB, giving developers a way to have maps on sites in a lightweight style.
Sunday, June 16, 2013
show or hide div in jquery with example
How to Show or Hide div's using jQuery
Show DIV in jquery
jQuery('div').show(); --- Displays all the div's
jQuery('#thisdiv').show(); ---- Displays a div having the id as thisdiv
jQuery('#thisdiv div').show(); ---- Displays all the div's inside the div having the id thisdiv
Hide DIV in jquery
jQuery('div').hide(); --- Hides all the div's
jQuery('#thisdiv').hide(); ---- Hides a div having the id as thisdiv
jQuery('#thisdiv div').hide(); ---- Hides all the div's inside the div having the id thisdiv
div outside thisdiv
thisdiv
div inside thisdiv
Monday, June 3, 2013
Get or Set Http Cookies in server side of C# on Asp.Net Website
Set and Get Cookies
Get Cookie
Sample Code
HttpCookie myCookie = new HttpCookie("sampleCookie");
SampleCookie= Request.Cookies["sampleCookie"];
// Read the cookie information and display it.
if (SampleCookie!= null){
string value= SampleCookie.Value;
string name= SampleCookie.Name;
Explanation
1.Create an object for the HttpCookie Class
HttpCookie myCookie = new HttpCookie("sampleCookie");
2. Get the Cookie from Request.Cookies Collection
SampleCookie= Request.Cookies["view"];
3.Check whether the cookie object is null
if (SampleCookie!= null)
4. Get the Cookie Value and Cookie Name
string value= SampleCookie.Value;
string name= SampleCookie.Name;
Sample Code
Read More
Get Cookie
Sample Code
HttpCookie myCookie = new HttpCookie("sampleCookie");
SampleCookie= Request.Cookies["sampleCookie"];
// Read the cookie information and display it.
if (SampleCookie!= null){
string value= SampleCookie.Value;
string name= SampleCookie.Name;
Explanation
1.Create an object for the HttpCookie Class
HttpCookie myCookie = new HttpCookie("sampleCookie");
2. Get the Cookie from Request.Cookies Collection
SampleCookie= Request.Cookies["view"];
3.Check whether the cookie object is null
if (SampleCookie!= null)
4. Get the Cookie Value and Cookie Name
string value= SampleCookie.Value;
string name= SampleCookie.Name;
Set Cookie
Sample Code
HttpCookie SampleCookie= new HttpCookie("SampleCookie");
SampleCookie.Value="SampleName";
SampleCookie.Name="SampleValue";
myCookie.Domain="sampleDomain.com"
SampleCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(SampleCookie);
Saturday, June 1, 2013
static vs instance members in C Sharp
Static Versus Instance Members in C#
- By default, members are per instance
- Each instance gets its own fields
- Methods apply to a specific instance
- Static members are per type
- Static methods can’t access instance data
- No this variable in static methods
Static methods
public class Area { private int side; public Rectangle(int side) { this.side= side; } public void Area() { Console.WriteLine("Area output: " + Area.CalculateArea(this.side)); } public static int CalculateArea(int side) { return side* side; } }
Sample
Friday, May 31, 2013
hasclass in jquery with example
JQuery hasClass() for single and multiple Class
The general syntax for hasClass is as follows
Check single Class
$("selector").hasClass("ClassName")
It will return true if the class is exists else return false
Check Multiple Classes
$("selector").hasClass("ClassName1 ClassName2 ClassName3")
Read More
The general syntax for hasClass is as follows
Check single Class
$("selector").hasClass("ClassName")
It will return true if the class is exists else return false
Check Multiple Classes
$("selector").hasClass("ClassName1 ClassName2 ClassName3")
<html> <head> </head> <body> <input class="found" type="button" value="Found" /> <input class="notfound" type="button" value="Not Found" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(".found").click(function(){ if($(this).hasClass("found")) alert("found"); }); $(".notfound").click(function(){ if($(this).hasClass("notfound")) alert("notfound"); }); </script> </body> </html>
Thursday, April 25, 2013
How to create a data set
How to create a data set
Create your dataset and table adapter
1. Create your frame
2. Drop a Data Grid View control
3. Create a Dataset (xsd) File.
4. Open your xsd file.
5. Drag the table that you want to work with from the server explorer. Your table and table adapter will be created.
If you click the Table Adapter and check its properties you will see that the select, insert, update and delete command are automatically generated.
That depends on how your table is designed. When I was working with a table with no primary key, the updated command was not generated. You can add the command, but when it is time to update a record in the data grid view, it could generate some issues and you will not able to update.
If you do not want to deal with these problems, set a primary key field to your table when you are designing it; if you do not want to deal these problems, set a primary key field to your table when you are designing it in your data base.
Now you check the code that is created automatically in the load form event. This code will fill the data grid view with the current data in your table.
6. Enable the insert, update and delete properties in your data grid view control clicking the option control button .
7. In that same box, choose your data table as your data source
Now your data grid view columns will be generated automatically. Also as your table adapter object, binding source object and dataset object.
Also in the Load Form event this code will appear to fill with the table info every time this window form is loaded.
private void dsDemo001GUI_Load(object sender, EventArgs e)
1. Create your frame
2. Drop a Data Grid View control
3. Create a Dataset (xsd) File.
4. Open your xsd file.
5. Drag the table that you want to work with from the server explorer. Your table and table adapter will be created.
If you click the Table Adapter and check its properties you will see that the select, insert, update and delete command are automatically generated.
That depends on how your table is designed. When I was working with a table with no primary key, the updated command was not generated. You can add the command, but when it is time to update a record in the data grid view, it could generate some issues and you will not able to update.
If you do not want to deal with these problems, set a primary key field to your table when you are designing it; if you do not want to deal these problems, set a primary key field to your table when you are designing it in your data base.
Now you check the code that is created automatically in the load form event. This code will fill the data grid view with the current data in your table.
6. Enable the insert, update and delete properties in your data grid view control clicking the option control button .
7. In that same box, choose your data table as your data source
Now your data grid view columns will be generated automatically. Also as your table adapter object, binding source object and dataset object.
Also in the Load Form event this code will appear to fill with the table info every time this window form is loaded.
private void dsDemo001GUI_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dsDemoDatabase.People' table. You can move, or remove it, as needed.
this.peopleTableAdapter.Fill(this.dsDemoDatabase.People);
}
8. Now you need to add a button that will deleted a selected record.
9. Now is time to use the event to update the records from the data grid view. Select the grid view and go to event properties section.
10. Create a CellEndEdit Event.
11. In the code go the event method and type the following code
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
}
8. Now you need to add a button that will deleted a selected record.
9. Now is time to use the event to update the records from the data grid view. Select the grid view and go to event properties section.
10. Create a CellEndEdit Event.
11. In the code go the event method and type the following code
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
this.peopleTableAdapter.Update(dsDemoDatabase);
}
Now set your grid view needs the Allow User to Add Row to TRUE.
Now create a click event button, and type the following code
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
dataGridView1.Rows.Remove(row);
this.peopleTableAdapter.Update(dsDemoDatabase); }
The button will delete the selected rows from the data grid view and then call the method Update from the Table Adapter object. Also the grid view selection mode property is change to full row selection to avoid exceptions while the row is deleting.
Depends of what you are doing the Table Adapter Object call the Update method, and update table in the Dataset and in the base. If you remove rows, calls the delete query; if you add a new row, calls the insert query; and if you are modifying an existing cell calls the update query.
Now set your grid view needs the Allow User to Add Row to TRUE.
Now create a click event button, and type the following code
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
dataGridView1.Rows.Remove(row);
this.peopleTableAdapter.Update(dsDemoDatabase); }
The button will delete the selected rows from the data grid view and then call the method Update from the Table Adapter object. Also the grid view selection mode property is change to full row selection to avoid exceptions while the row is deleting.
Depends of what you are doing the Table Adapter Object call the Update method, and update table in the Dataset and in the base. If you remove rows, calls the delete query; if you add a new row, calls the insert query; and if you are modifying an existing cell calls the update query.
Tuesday, April 16, 2013
Filter Data in DataSet using C#
How to filter Data in DataSet
DataView Class is used to filter and sorting of data in Data Set
Here I m giving an example of how we can filter and sort data in data set.
DataView: A DataView is used to create different views of the data stored in a DataSet of DataTable
I am using following sqlserver database table in my example. Create a table using this script
CREATE TABLE tbemp
(
eno int NULL ,
ename varchar (50) NULL,
eadd varchar (50) NULL,
esal int NULL
)
GO
Use Following code in your .aspx page
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Show All Data" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Filter By Salary" ToolTip="Salary > 20000 and < 50000" />
I have used following namespaces in my .cs (code) file
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
Now write followin code in your.cs file
private DataSet getdata()
{
SqlConnection con = new SqlConnection("server=tiger;database=database1;uid=sa");
SqlDataAdapter adp = new SqlDataAdapter("Select eno,ename,eadd,esal from tbemp", con);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = getdata();
//Filtering Data (Showing record where salary is >20000 and <50000
DataView dv = ds.Tables[0].DefaultView;
//RowFilter is used to filter data in dataview
dv.RowFilter = "esal>=20000 and esal<=50000";// 'and' operator can be used for multipal conditions
//Sorting Record in Descending order
dv.Sort = "esal desc";//Sort property is used to data in dataview
GridView1.DataSource = dv;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
DataSet ds = getdata();
GridView1.DataSource = ds;
GridView1.DataBind();
}
Read More
DataView Class is used to filter and sorting of data in Data Set
Here I m giving an example of how we can filter and sort data in data set.
DataView: A DataView is used to create different views of the data stored in a DataSet of DataTable
I am using following sqlserver database table in my example. Create a table using this script
CREATE TABLE tbemp
(
eno int NULL ,
ename varchar (50) NULL,
eadd varchar (50) NULL,
esal int NULL
)
GO
Use Following code in your .aspx page
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Show All Data" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Filter By Salary" ToolTip="Salary > 20000 and < 50000" />
I have used following namespaces in my .cs (code) file
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
Now write followin code in your.cs file
private DataSet getdata()
{
SqlConnection con = new SqlConnection("server=tiger;database=database1;uid=sa");
SqlDataAdapter adp = new SqlDataAdapter("Select eno,ename,eadd,esal from tbemp", con);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = getdata();
//Filtering Data (Showing record where salary is >20000 and <50000
DataView dv = ds.Tables[0].DefaultView;
//RowFilter is used to filter data in dataview
dv.RowFilter = "esal>=20000 and esal<=50000";// 'and' operator can be used for multipal conditions
//Sorting Record in Descending order
dv.Sort = "esal desc";//Sort property is used to data in dataview
GridView1.DataSource = dv;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
DataSet ds = getdata();
GridView1.DataSource = ds;
GridView1.DataBind();
}
Looping through DataSet in C#
To loop through DataTable, try this
Read More
if (datatable1 !=null) { foreach (DataRow dr i datatable1.Rows) { string text1 = dr["Column1Name"].ToString(); string text2 = dr["Column1Name"].ToString(); // and so on //You can also set your Literal cotrol as } }
Dataset Data set Dataset in C-sharp Dataset C-Sharp example Dataset in .net
DataSet is a collection of DataTables. We use the DataSet type to store many DataTables in a single collection. Conceptually, the DataSet acts as a set of DataTable instances. This simplifies programs that use many DataTables.
DataTable
Create
To effectively use the DataSet, you will need to have some DataTables handy. In this program, we create two DataTables. One stores two rows of patient information. And the second stores two rows of medication information.
Next:
We create a DataSet with the DataSet constructor.
Then we add the two DataTables to the DataSet instance.
Finally we print the XML.
XMLProgram that uses DataSet [C#] using System; using System.Data; class Program { static void Main() { // Create two DataTable instances. DataTable table1 = new DataTable("patients"); table1.Columns.Add("name"); table1.Columns.Add("id"); table1.Rows.Add("sam", 1); table1.Rows.Add("mark", 2); DataTable table2 = new DataTable("medications"); table2.Columns.Add("id"); table2.Columns.Add("medication"); table2.Rows.Add(1, "atenolol"); table2.Rows.Add(2, "amoxicillin"); // Create a DataSet and put both tables in it. DataSet set = new DataSet("office"); set.Tables.Add(table1); set.Tables.Add(table2); // Visualize DataSet. Console.WriteLine(set.GetXml()); } } Output <office> <patients> <name>sam</name> <id>1</id> </patients> <patients> <name>mark</name> <id>2</id> </patients> <medications> <id>1</id> <medication>atenolol</medication> </medications> <medications> <id>2</id> <medication>amoxicillin</medication> </medications> </office>
Dispose, using DataSet
You can put your DataSet in a using block. This ensures the Dispose method is called as soon as possible when the DataSet is no longer being used. If you are having resource usage problems, adding using blocks can help.Using
Program that creates DataSet in using block [C#] using System.Data; class Program { static void Main() { // Create a DataSet in using statement. using (DataSet set = new DataSet("office")) { // Put code that adds stuff to DataSet here. // ... The DataSet will be cleaned up outside the block. } } }
Namespace, Prefix
One important use of the DataSet is to encode data in XML format. Often, XML data needs to have an XML namespace of a tag element prefix. Fortunately, the DataSet provides the Namespace and Prefix properties to specify this.
Next:
This example specifies both the Namespace and the Prefix, and you can see them
appear in the output.
Program that uses Namespace and Prefix [C#] using System; using System.Data; class Program { static void Main() { DataTable table1 = new DataTable("patients"); table1.Columns.Add("name"); table1.Columns.Add("id"); table1.Rows.Add("sam", 1); // Create a DataSet. DataSet set = new DataSet("office"); set.Tables.Add(table1); set.Namespace = "y"; set.Prefix = "x"; // Visualize DataSet. Console.WriteLine(set.GetXml()); } } Output <x:office xmlns:x="y"> <patients xmlns="y"> <name>sam</name> <id>1</id> </patients> </x:office>
DataSetName
Every DataSet can have a name specified. Usually, it is easiest to specify this inside the DataSet constructor. However, you can also change the name by assigning to the DataSetName property. You can also read the DataSetName property.Program that uses DataSetName [C#] using System; using System.Data; class Program { static void Main() { // Create a DataSet. DataSet set = new DataSet("office"); // Show original name. Console.WriteLine(set.DataSetName); // Change its name. set.DataSetName = "unknown"; Console.WriteLine(set.DataSetName); } } Output office unknown
Copy, Clear
The DataSet is similar to other popular collections. For example, it has a Clear method that clears all the DataTables in the set. It also provides a Copy method that will make a deep copy of all the DataTables in the set.
Tip:
If you call Copy and the Clear the original, your copied data will still exist unchanged.
Program that uses Copy and Clear [C#] using System; using System.Data; class Program { static void Main() { DataTable table1 = new DataTable("patients"); table1.Columns.Add("name"); table1.Columns.Add("id"); table1.Rows.Add("sam", 1); DataTable table2 = new DataTable("medications"); table2.Columns.Add("id"); table2.Columns.Add("medication"); table2.Rows.Add(1, "atenolol"); // Create a DataSet. DataSet set = new DataSet("office"); set.Tables.Add(table1); set.Tables.Add(table2); // Copy the DataSet. DataSet copy = set.Copy(); // Clear the first DataSet. set.Clear(); // Show contents. Console.WriteLine("set: {0}", set.GetXml()); Console.WriteLine("copy: {0}", copy.GetXml()); } } Output set: <office /> copy: <office> <patients> <name>sam</name> <id>1</id> </patients> <medications> <id>1</id> <medication>atenolol</medication> </medications> </office>
Tables
Understanding the Tables collection in the DataSet is important. The Tables property returns an instance of a DataTableCollection. You can use the Count property and indexer on this sub-collection to access all the individual tables.Indexer
Program that uses Tables and DataTableCollection [C#] using System; using System.Data; class Program { static void Main() { DataTable table1 = new DataTable("patients"); table1.Columns.Add("name"); table1.Columns.Add("id"); table1.Rows.Add("sam", 1); DataTable table2 = new DataTable("medications"); table2.Columns.Add("id"); table2.Columns.Add("medication"); table2.Rows.Add(1, "atenolol"); table2.Rows.Add(6, "trifluoperazine"); // Create a DataSet. DataSet set = new DataSet("office"); set.Tables.Add(table1); set.Tables.Add(table2); // Loop over DataTables in DataSet. DataTableCollection collection = set.Tables; for (int i = 0; i < collection.Count; i++) { DataTable table = collection[i]; Console.WriteLine("{0}: {1}", i, table.TableName); } // Write name of first table. Console.WriteLine("x: {0}", set.Tables[0].TableName); // Write row count of medications table. Console.WriteLine("y: {0}", set.Tables["medications"].Rows.Count); } } Output 0: patients 1: medications x: patients y: 2Also, you can get a DataTable from the Tables collection with its name. The last part of the program where we use set.Tables["medications"] shows this behavior. This is an intuitive way of getting a certain table.
Relations
The Relations property is a way to specify many DataRelations on the DataTables. A DataRelation indicates which tables are dependent on other tables (sub-tables). The Relations property is not covered in this document.CaseSensitive
The DataSet provides the CaseSensitive property. The default value of this property is False. There may be cases where you want string lookups on your DataSet to be case-sensitive.
Note:
One case involves two elements with the same name but different character casing
("Medications", "medications").
GetXml
It is possible to convert a DataSet to a string representation in XML syntax. The GetXml() method on the DataSet instance is ideal for this. The example program constructs a new DataSet instance with the name "Hospital".
Then:
It adds a new DataTable to this set.
This DataTable has four rows and five columns.
Finally:
The GetXml instance method is invoked on the DataSet,
and the result is printed to the screen.
Program that uses GetXml method [C#] using System; using System.Data; class Program { static DataTable Table() { DataTable table = new DataTable("Prescription"); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patient", typeof(string)); table.Columns.Add("Date", typeof(DateTime)); table.Rows.Add(25, "Indocin", "David", DateTime.Now); table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); return table; } static void Main() { // Create DataSet instance. DataSet set = new DataSet("Hospital"); // Add new table. set.Tables.Add(Table()); // Write xml data. Console.WriteLine(set.GetXml()); } } Output <Hospital> <Prescription> <Dosage>25</Dosage> <Drug>Indocin</Drug> <Patient>David</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> <Prescription> <Dosage>50</Dosage> <Drug>Enebrel</Drug> <Patient>Sam</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> <Prescription> <Dosage>10</Dosage> <Drug>Hydralazine</Drug> <Patient>Christoff</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> <Prescription> <Dosage>21</Dosage> <Drug>Combivent</Drug> <Patient>Janet</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> <Prescription> <Dosage>100</Dosage> <Drug>Dilantin</Drug> <Patient>Melanie</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> </Hospital>In the XML file, the element names Hospital, Prescription, Dosage, Drug, Patient and Date correspond to the name of the DataSet, the name of the DataTable, and then the four different DataColumns. The data is preserved.
GetXmlSchema
An XML schema is a text document that indicates the structure of an XML document. The GetXmlSchema() method on the DataSet type generates an XML schema from the known structure encoded in your DataSet.
Then:
We create a DataSet and then add a DataTable instance to it.
We call the GetXmlSchema instance method, which reveals the XML schema.
Program that demonstrates GetXmlSchema [C#] using System; using System.Data; class Program { static DataTable Table() { DataTable table = new DataTable("Prescription"); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patient", typeof(string)); table.Columns.Add("Date", typeof(DateTime)); table.Rows.Add(25, "Indocin", "David", DateTime.Now); table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); return table; } static void Main() { // Create DataSet instance. DataSet set = new DataSet("Hospital"); // Add new table. set.Tables.Add(Table()); // Write xml schema data. Console.WriteLine(set.GetXmlSchema()); } } Output: edited <?xml version="1.0" encoding="utf-16"?> <xs:schema id="Hospital" xmlns="" xmlns:xs="" xmlns:msdata=""> <xs:element name="Hospital" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="Prescription"> <xs:complexType> <xs:sequence> <xs:element name="Dosage" type="xs:int" minOccurs="0" /> <xs:element name="Drug" type="xs:string" minOccurs="0" /> <xs:element name="Patient" type="xs:string" minOccurs="0" /> <xs:element name="Date" type="xs:dateTime" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema>Using XML schema with DataSet. Now that we have an XML schema file, what can we do with it? The DataSet type provides two methods, InferXmlSchema and ReadXmlSchema, which can load a file we specify that contains the schema data.
Then:
We have a DataSet with all the appropriate constraints in it.
After this, we could use ReadXml on an XML file of the data itself.
Summary
The DataSet type provides a way to collect many DataTables inside a single collection. It provides useful helper methods for acting upon those DataTables. By providing a container for DataTables, DataSet introduces a key abstraction.Convert DataSet to DataTable
A
DataSet
already contains DataTables
. You can just use:DataTable firstTable = dataSet.Tables[0];
or by name:DataTable customerTable = dataSet.Tables["Customer"];
Note that you should have using
statements for your SQL code, to ensure the connection is disposed properly:using (SqlConnection conn = ...)
{
// Code here...
}
Sunday, April 7, 2013
dataset to excel c#
here is the solution for that.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.Office.Interop;
private void btn_ETexcel_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 10;
for (int i = 1; i < GridView1.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = GridView1.Columns[i - 1].HeaderText;
ExcelApp.Cells.Font.Bold = true;
}
for (int i = 0; i < GridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < GridView1.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = GridView1.Rows.Cells[j].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs ("D:\\reports.xls");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
MessageBox.Show("Excel file created,you can find the file D:\\reports.xls");
}
Read More
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.Office.Interop;
private void btn_ETexcel_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 10;
for (int i = 1; i < GridView1.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = GridView1.Columns[i - 1].HeaderText;
ExcelApp.Cells.Font.Bold = true;
}
for (int i = 0; i < GridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < GridView1.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = GridView1.Rows.Cells[j].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs ("D:\\reports.xls");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
MessageBox.Show("Excel file created,you can find the file D:\\reports.xls");
}
Monday, November 19, 2012
Friday, August 3, 2012
Convert Dataset to HTML table
public string CreateHtmlTableRows(DataTable targetTable, string strtblName, List<string> strLinkList,List<string> strRejectedColumnList)
{
System.Text.StringBuilder myBuilder = new System.Text.StringBuilder();
if (strtblName != "")
myBuilder.Append("<table Id='" + strtblName + "' border='1px' cellpadding='10px' cellspacing='10px' ");
else
myBuilder.Append("<table border='0px' cellpadding='5px' cellspacing='5px' ");
myBuilder.Append("style='width: 100%;'>");
//Add the headings row.
myBuilder.Append("<tr align='left' valign='top' style=' background-color: #5D7B9D;font-weight: bold;color: White;'>"); //grdHeader class will be in CSS file
foreach (DataColumn myColumn in targetTable.Columns)
{
if (!strRejectedColumnList.Contains(myColumn.ColumnName))
{
myBuilder.Append("<td align='left' valign='top'><label style=\"cursor:pointer;\" onclick=\"clickonheader(" + myColumn.ColumnName + ");\">");
myBuilder.Append(myColumn.ColumnName);
myBuilder.Append("</label></td>");
}
}
myBuilder.Append("</tr>");
//Add the data rows.
int intI = 0;
int totRow = targetTable.Rows.Count - 1;
bool bGetTotalRecs = false;
foreach (DataRow myRow in targetTable.Rows)
{
if (intI % 2 == 0)
myBuilder.Append("<tr align='left' style=' border-right: 2px solid #A7A6AA;border-bottom: 2px solid #A7A6AA;border-left: 2px solid #A7A6AA;border-top: 2px solid #A7A6AA;padding: 4px;'>"); //'grdOddRow'class will be in CSS file
else
myBuilder.Append("<tr align='left' style=' border-right: 2px solid #A7A6AA;border-bottom: 2px solid #A7A6AA;border-left: 2px solid #A7A6AA;border-top: 2px solid #A7A6AA; background-color: #FFFFFF;color: #284775;'>"); //''grdEvenRow''class will be in CSS file
int colcount = 0;
foreach (DataColumn myColumn in targetTable.Columns)
{
if (!strRejectedColumnList.Contains(targetTable.Columns[colcount].ColumnName))
{
if (strLinkList.Contains(targetTable.Columns[colcount].ColumnName))
{
myBuilder.Append("<td align='left' valign='middle'><b><a href='#toShow'><label id='" + targetTable.Columns[colcount].ColumnName + "_" + myRow[myColumn.ColumnName].ToString() + "'");
myBuilder.Append(" onclick=\"clickonlink('" + targetTable.Columns[colcount].ColumnName + "'," + myRow[myColumn.ColumnName].ToString() + ");\" style=\"cursor:pointer;\">");
myBuilder.Append(myRow[myColumn.ColumnName].ToString());
myBuilder.Append("</label></a></b></td>");
}
else
{
myBuilder.Append("<td align='left' valign='top'><b><label id='" + targetTable.Columns[colcount].ColumnName + "_" + myRow[myColumn.ColumnName].ToString() + "'>");
myBuilder.Append(myRow[myColumn.ColumnName].ToString());
myBuilder.Append("</label></b></td>");
}
}
else
{
if (!bGetTotalRecs)
{
if (targetTable.Columns[colcount].ColumnName == "totalrecs")
{
myBuilder.Append("<input type=\"hidden\" id=\"hidTotalRecs\" value=\"" + myRow[myColumn.ColumnName].ToString() + "\" />");
bGetTotalRecs = true;
}
}
}
colcount++;
}
myBuilder.Append("</tr>");
intI += 1;
}
//Close tags.
return myBuilder.Append("</table>").ToString();
}