Thursday, April 7, 2011

CSS plays a major part in designing and developing, Its alot more easier to CSS these days with the free tools and tutorials available online. Here we are presenting the best of CSS tools and tutorials that will cover almost all areas of CSS! Go ahead and Enjoy!

LAYOUTS

  • Layout Galaby Alessandro Fulciniti – a collection of 40 CSS layouts based on the same markup and ready for download!
  • Look Ma, No Tables.CSS Layout Techniques: for Fun and Profit
  • ThreeColumnLayoutscss-discuss – Bob Easton
  • Open Source Web DesignDownload and upload free web designs
  • Open Web DesignDownload and upload free web designs
  • Sample CSS Page LayoutsHere are a range of CSS page layouts, including 2 column and 3 column layouts – free to use and abuse as needed
  • Yet Another Multicolumn LayoutA multi-column layout
  • CSS LayoutsStu Nicholls – Three columns, CSS frame, “Fixed”, Cross browser….
  • CSS TEMPLATESAll templates are XHTML 1.0 and CSS2
  • css Zen Gardenlist of all Zen Garden designs added to date..980+ layouts
  • Flexi-Floats3 Column CSS Layout – Fluid, Multi-Column Stretch – Header, Footer, Fluid Center – Fixed or Fluid widths
  • FirdamaticFirdamatic is an online tableless layout generator that allows you to create and customise layouts easily…
  • Free CSS Template Code GeneratorMaker for 3 Column Layout (tableless)
  • Page Maker – The Generator Form v2.90CSS Source Ordered Variable Border 1-3 Columned Page Maker
  • QrONE CSS DesignerOnline CSS Generator
  • ScriptomizersA CSS stylesheet generator
  • CSS CreatorLive CSS Cascading Style Sheet Layout generator for your web site
  • CSS HTML PHP Website Template MakerThis PHP – HTML – CSS template generator creates a two column layout with both a header and a footer….
  • CSS Rounded Box Generatorgenerates html and css for rounded corner boxes
  • Listamaticnot a tool but very useful! – one list, many options – Using CSS and a simple list to create radically different list
  • Listamatic2nested list options
  • List-O-MaticGenerate CSS-styled navigation menus based on list items
  • List-O-Rama!Dreamweaver MX and UltraDev Zone – List-O-Rama will allow you to generate nice CSS inline menus in seconds
  • CSS Menu GeneratorCSS Menu Generator will generate both the CSS and the HTML code required to produce a text-based yet appealing set of navigation buttons.
  • Strictly CSS – Strictly CSS has an article that provides ten different CSS layouts based on the same HTML code.
  • Max Design – Twenty-three different layouts in several different categories are available from Max Design.
  • Glish.com – Here is an article that includes links to a number of CSS-based layouts.
  • mycelly.com – Twelve different layouts.
  • Little Boxes – Sixteen more layouts.
  • Dynamic Drive’s CSS Library – One of the leading sources of coding and scripts provides 12 CSS-based layouts.
  • Intensivstation – 16 different CSS-based layouts are provided
  • BluePrintCSS – BluePrintCSS “aims to cut down on your CSS development time. It gives you a solid CSS foundation to build your project on top of, with an easy-to-use grid, sensible typography, and even a stylesheet for printing.”
  • CSSeasy – At CSSeasy you’ll find 8 different layouts to choose from.
  • WordPress Theme Generator – Another resource for WordPress designers, the theme generator will let you choose the layout you want and it generates the code.
  • Yahoo! Developer Network – YUI Grids CSS provide a starting point for your layouts for fluid or fixed width.
  • SSI Developer – At SSI Developer there are a variety of two and three column layouts. Each layout indicates the browsers in which it has been tested.
  • Mollio – Mollio offers several attractive layouts, but they give a disclaimer that there may be some rendering problems with IE7.
  • CSS Tinderbox – Here you’ll find four simple but attractive layouts.
  • Mitch Bryson – Mitch provides eight different CSS-based layouts to choose from.

FORMS

NAVIGATION

GALLERIES

  • Style Crunch
    StyleCrunch is a css and standards websites gallery
  • Stylegala – Web Design Publication
    Stylegala is an online resource and inspiration guide for web agencies, designers and developers who take interest in websites that combine the powers of design, web standards and CSS.
  • Submit CSS
    Submit your own css design and view a gallery full of creative design inspiration
  • Unmatched Style
    Unmatched Style is a constantly growing community dedicated to acknowledging those who have made exceptionally gorgeous web sites using Cascading Style Sheets and web standards. By recognizing these exceptionally beautiful designs, other designers and businesses can get inspired and find a direction they may wish to take with their own web sites.
  • W3 Compliant Sites: Sites designed to comply with W3C Web Site Standards
    A collection of web standards compliant web sites and their designers
  • Webdigity
    CSS gallery

  • Awarding web sites that successfully combine form and function
  • Well Designed CSS Sites
    Andy Budds List of well styled sites.
  • Design Shack – Inspirational CSS and Blog Design
    Design Shack offers regular examples of great CSS, standards based design to help inspire and create. We feature any website which shows off some flair, and doesn’t fit into the standard pattern we come to expect from CSS design.
  • Liquid Designs
    Liquid Designs is a gallery of websites designed with liquid layouts using XHTML and CSS
  • Piepmatzel
    collecting best practice web standards design examples
  • csstux – The best dressed sites on the web
    A gallery of inspiring web site design and resources, focused primarily on sites using cascading style sheets.
  • CSS Vault – The Web’s CSS Site
    A repository of sites using cascading style sheets and a list of resources
  • CSS Website
    Gallery of Css Design Website. Submit your site.
  • CSS Zen Garden: The Beauty in CSS Design
    A demonstration of what can be accomplished visually through CSS-based design. Classic!
  • CSS-Mania
    CSSmania, the most updated css showcase all over the globe
  • CSS Princess
    CSS princess is showcase gallery of beautiful css sites. You can find web sites primarily done completly with css , without tables.
  • CSS Reboot
    CSS Gallery – The CSS Reboot is a community event for web professionals and enthusiasts. This November 1st at 18:00 GMT Rebooters from all over the world will launch their web standards-based redesigns
  • CSS Remix
    A Fresh Blend of the Best CSS Web Design
  • CSS smooth operator // Tite site collection
    Tite site collection, conforms to Web Standards and designed with CSS
  • CSS Hazard CSS Inspiration and Gallery
  • CSS Heaven
    CSS Gallery – submit your own css design and view a gallery full of creative design inspiration. The submitted designs can be rated
  • CSS ImportCSS
    The no-frills CSS Gallery
  • CSS Drive- Categorized CSS gallery and examples
    CSS gallery, code samples, tutorials, and moreCSS Collection
  • CeeSeS
    CSS Gallery – We are the BalkaniCSS!
  • CESKO
    CSS Showcase – Slovenia
  • Creative-Pakistan
    Creative-Pakistan.com is a platform to showcase web and CSS designs of creative Pakistani web desginers
  • CSSFill
    CSSFILL provides free CSS based layouts and templates
  • CSS Galaxy
    CSS Gallery with voting and comments.
  • CSS Beauty
    CSS Beauty focuses on providing its audience with a database of well designed CSS based sites, as well as news and happenings on the CSS Design Community. It showcases designers work and serves as inspiration for those looking to build CSS based websites.
  • CSS Blast
    Russian CSS Showcase
  • CSSBloom
    CSS Gallery with Blog’s and Online Portfolio’s
  • CSS Clip
    Web Design Inspiration and Gallery
  • CSS Collection
    CSS collection web sites without tables
  • CSS-Demo
    CSS Showcase
  • CSS Design Yorkshire
    A gallery of CSS web design in Yorkshire UK

FORMATTERS

TUTORIALS

see more: http://www.antsmagazine.com/2009/05/best-css-tools-and-tutorials/

Wednesday, April 6, 2011

ASP.NET data presentation controls, like GridView, Repater, DataList, ListView, DetailsView or FormView, could be used to show data from database fast and easy, even without single line of ASP.NET server side code. But, sometimes raw data from database are not suitable for showing on web form directly. You could need additional formatting for date values, handle NULLs, change 0 and 1 to something more intuitive to your visitors, show warning if value is too high or just change styles like background color.

Conditional formatting of GridView rows and cells using RowDataBound event

Let's say you want to change color of GridView's cell depending of value. For example, if cell value is larger than 10 then background color should be red. Using GridView RowDataBound event this task is simple. Here is the code:

[ C# ]

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Check if row is data row, not header, footer etc.
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get value of third column. Index is zero based, to
// get text of third column we use Cells[2].Text
int CellValue = Convert.ToInt32(e.Row.Cells[2].Text);

// If value is greater of 10, change format
if (CellValue > 10)
{
// Use this syntax to change format of complete row
e.Row.BackColor = System.Drawing.Color.Yellow;
// Use this syntax to change format of single cell
e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
}
}
}

[ VB.NET ]

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
' Check if row is data row
If e.Row.RowType = DataControlRowType.DataRow Then
' Get value of third column. Index is zero based, to
' get text of third column we use Cells[2].Text
Dim CellValue As Integer = Convert.ToInt32(e.Row.Cells(2).Text)

' If value is greater of 10, change format
If CellValue > 10 Then
' Use this syntax to change format of complete row
e.Row.BackColor = System.Drawing.Color.Yellow
' Use this syntax to change format of single cell
e.Row.Cells(2).BackColor = System.Drawing.Color.Red
End If
End If
End Sub

Like BackColor, on the same way you can change other styles, like BorderColor, BorderWidth, ForeColor, Font etc., or simply change CssClass property to keep styles separated and avoid hard coding.


Formatting data binding output using RowDataBound event

Like changing styles, you can also change data in cells depending of specified condition. Common example for this could be if you have a column that shows "Yes" or "No". But, database architects rarely store these strings directly in database. Common approach is to have only 1 and 0 values in table. So, how to translate 1 and 0 to "Yes" and "No"? One of possible solutions is to employ RowDataBound event, like in previous example. Here is the code:

[ C# ]

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Check if row is data row
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get value of third column. Index is zero based, to
// get text of third column we use Cells[2].Text
int CellValue = Convert.ToInt32(e.Row.Cells[2].Text);

// If value is 1 then change to Yes, otherwise change to No
if (CellValue == 1)
{
e.Row.Cells[2].Text = "Yes";
}
else

{
e.Row.Cells[2].Text = "No";
}
}
}

[ VB.NET ]

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
' Check if row is data row
If e.Row.RowType = DataControlRowType.DataRow Then
' Get value of third column. Index is zero based, to
' get text of third column we use Cells[2].Text
Dim CellValue As Integer = Convert.ToInt32(e.Row.Cells(2).Text)

' If value is 1 then change to Yes, otherwise change to No
If CellValue = 1 Then
e.Row.Cells(2).Text = "Yes"
Else

e.Row.Cells(2).Text = "No"
End If
End If
End Sub

Using RowDataBound event you can change not just text of the cell, but actually anything in the cell. One more common use of this method is if you have column with product images. Let say that some products have image and some not. If you simply bind GridView or Repeater to data source it will show ugly "Image not found" message where image is missing. A little better but not good enough solution is to specify Alt parameter to show some text if product is without image.

Very often, best solution is to place some default image if image is null. Another common use of this method is in discussion boards and social network sites. If use doesn't upload her avatar, then default image is used. You can achieve this using RowDataBound event. I already describe it how, just check Solving "Image Not Found" Problem In GridView tutorial.

Formatting data binding output using inline if condition

Sometime, it is easier to change data directly in markup code. Here is the syntax that changes 1 and 0 to "Yes" and "No" respectively:

[ C# ]

<asp:GridView ID="GridView1" runat="server">
 <Columns>
<asp:TemplateField>
<ItemTemplate>
<img src='<%# (Eval("ImageURL")==DBNull.Value ? "DefaultImage.jpg" : DataBinder.Eval(Container.DataItem, "ImageURL")) %>' />
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>

[ VB.NET ]

<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img src='<%#IIf(Convert.ToString(Eval("ImageURL")) = "", "Default.jpg", Eval("ImageURL"))%>' />
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>

Notice that this way is not recommended if you manipulate with large data. Single property like image name or "Yes" and "No" are just short strings. If you need to manipulate with pile of HTML then it could be very confusing and certainly hard to maintain to keep it in single code line as literals. Unlike classic ASP, ASP.NET data controls don't allow syntax like:

<% If Eval("SomeValue") = 1 Then %>

Some HTML

<% Else %>

Some other HTML

<% End If %>

Instead of this, you could for example place two Panel controls and manipulate their Visible property with condition like shown in previous example.

Formatting data binding output using protected function

One more way to format data output is by using protected function. Let say we have a problem like above and want to show default image if NULL is returned. In server side code, we need a protected function, like this:

[ C# ]

protected string getImageURL(object OriginalImage)
{
// In protected function do needed processing to format or change
// output as needed
if(OriginalImage == null)
{
return "DefaultImage.jpg";
}
else
{
return (string)OriginalImage;
}
}

[ VB.NET ]

Protected Function getImageURL(ByVal OriginalImage As Object) As String
' In protected function do needed processing to format or change
' output as needed
If OriginalImage Is Nothing Then
Return "DefaultImage.jpg"
Else
Return OriginalImage
End If
End Function

Then, call this function from markup code, like this:

<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img src='<%# getImageURL(Eval("ImageURL")) %>' />
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>

Formatting data binding output using SQL

Another level where you can manipulate data is your SQL query to database. Instead of calling ItemDataBound event or coding inside markup, do what you need in SQL either in ad hoc query or stored procedure. We can do this using CASE keyword. T-SQL query that process value from table and returns changed or formatted value executes on SQL Server. In ASP.NET application we do simple data binding. For example, let say we want to list all customer's name, phones and faxes. But, since not every customer has a fax, we want to show message "No Fax" instead of NULLs. T-SQL would look like this:

SELECT
ContactName,
Phone,
CASE
WHEN [Fax] IS NULL THEN
'No Fax'
ELSE
Fax
END
FROM Customers

Formatting output in dependence of row position

Sometimes you want to add advertisement in the middle of list, or some other content to specific position. In this case, formatting of data binding output does not depend of data, but only of their position in row collection. You can solve this problem with RowDataBound event, with code like this:

[ C# ]

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Check if current row is data row
if(e.Row.RowType = DataControlRowType.DataRow)
{
// Check position of the row in grid
if (e.Row.RowIndex == 4)
{
// Show advertisement only in single row
pnlAdvertisement.Visible = true;
}
}
}

[ VB.NET ]

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
' Check if current row is data row
If e.Row.RowType = DataControlRowType.DataRow Then

' Check position of the row in grid
If e.Row.RowIndex = 4 Then
' Show advertisement only in single row
pnlAdvertisement.Visible = True
End If
End If
End Sub

Remarks

Whenever format data, try to avoid hard coding as much as possible. For example, method with T-SQL query is suitable for very small data, but it is not recommended to put large HTML chunks in SQL query. That makes application harder to test and maintain. In case that formatting demands big changes consider placing this code in two Panel controls and then manipulate only their Visible property. DataList and Repeater don't have RowDataBound event, but they have ItemDataBound which can be used on similar way

see more: http://www.beansoftware.com/ASP.NET-Tutorials/Conditional-Values-Styles-GridView.aspx

The GridView in ASP.NET seems to give the programmer few configurable options at first, but when you start using the DataBound events, then it starts to become surprisingly versatile.

Manipulate the GridView control in ASP.NET to display your data the right way

The GridView in ASP.NET is a very powerful control that provides an easy interface to add, update, delete, and display data. The GridView also lets you perform other tasks very easily, such as paging and sorting your data, but not everything is as straightforward as it seems. Most of the time, we would display the data exactly as it comes out of our datasources, but sometimes we may need to manipulate the text, cells, and rows to fit our needs. In this article I will explain how to use the events and properties of the GridView to allow us to customise the way the data appears.

Taking advantage of the GridView events and properties

GridView is great for very simple tables, but the real world is not always as straightforward as we would like it to be. Sometimes we need to specify the format of the data, and the way it is rendered in the table, more exactly. Many people will tell you to use other type of controls such as the DataList for this, because it gives the user more choices in the way that the grid is rendered. Unfortunately the DataList, unlike the Gridview, does not have all the features such as paging and sorting that are commonly required. So if you still need or want to use the GridView, but also need more control on the way that the table is rendered, you can use the GridView events and properties.

The most used event of the GridView is the RowDataBound. This event is fired every time a row is bound to data. What does this mean to us, the developers? This means that, whenever this event is fired, we will have access to the current row and all of its data, so we can manipulate the table, row, cells, and or controls of the table accordingly. I will come back to this later.

Other important events are the DataBound and the Load event. The Load event fires when the GridView is loaded and has not been attached to any data yet. In this event the user can set properties such as the color of the border, themes, or any other rendering options that are not dependent on the data itself. The DataBound is similar to the RowDataBound in that both are fired after a bound event has happened. The difference is that DataBound is fired once after the entire Grid has been bound; while the RowDataBound is fired every time a row is bound, meaning it will almost always be fired more than once. So you can use the DataBound to manipulate the table based on the data contained in it.

image


FIGURE 4: Events of the GridView

The RowDataBound is your friend.

Let’s look at the parameters needed for the RowDataBound event. Like every .NET event it has two parameters: sender of type object and e of type GridViewRowEventArgs. The sender parameter contains a reference of the GridView that is firing the event and e contains a very important property named Row which references the row that is being bound. The Row property is very important. Table 1 contains the most used properties of the GridViewRow taken from the MSDN documentation.

Property Description
Attributes Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.(inherited from WebControl)
Cells Gets a collection of TableCell objects that represent the cells of a row in a Table control.(inherited from TableRow)
DataItem Gets the underlying data object to which the GridViewRow object is bound.
RowIndex Gets the index of the GridViewRow object in the Rows collection of a GridView control.
RowType Gets the row type of the GridViewRow object.

Table 1: Most used properties of the Row

Imagine that your boss asks you to create a table of all the products with their price and Units in Stock and Units on Order. So you would simply create a GridView with a SqlDataSource with the following query: select ProductName, UnitPrice, UnitsInStock, UnitsOnOrder from Products. This is a very easy and straightforward task. Figure 5 displays the end result.

image

FIGURE 5: End result of the GridView displaying the products.

Your boss sees the page and says he would love to be able to quickly distinguish all the products that need to be reordered, and also the products that have already been reordered. So you could then simply tell him that not only will you display the numbers as they are, but also display the products that need to be reordered in red and the ones that have been reordered in blue. Your boss loves the idea, but you have no clue how to do that with a GridView. The way to do this is to use the RowDataBound event. The code on Figure 6 shows how to accomplish this simple, but not intuitive task.


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

//We're only interested in Rows that contain data

//get a reference to the data used to databound the row
DataRowView drv = (DataRowView)e.Row.DataItem;
if (Convert.ToInt32(drv["UnitsInStock"]) == 0)

{

//The current product has 0 items in stock
e.Row.Font.Bold = true; //Make the font bold
e.Row.ForeColor = System.Drawing.Color.Red; //Set the text color red
if (Convert.ToInt32(drv["UnitsOnOrder"]) > 0)

{

//The current out of stock item has already been ordered
//Make it blue
e.Row.ForeColor = System.Drawing.Color.Blue;

}

}

}

}

FIGURE 6: Code for setting fore color of each row.

The GridView fires the RowDataBound event on every row, including the header and footer. Therefore we need to make sure, when the event is fired, that it is fired on a DataRow. If it is, then we get a reference to the DataRowView, which represents the row of the datasource to which the row of the GridView was tied to. In our case this represents a row from the database result set. Please note that the e.Row.DataItem returns an object. The reason for that is that you can bind a GridView to any item that implements the ICollection interface: DataTable, DataSet, List, Array, etc. The type of the DataItem will vary with the DataSource used. Once we get a reference to the DataRowView, we then check to see if that Product is out of stock or if it is in the process of restocking and set the ForeColor of the row equal to the correct color. Figure 7 shows the end result.

image

Figure 7: The new GridView with the color change

Your boss is now in a good mood, and knows that you can do a lot for him: He therefore wants a new report. This new report will include all the products by Category. He does not want to see the category repeated every time. Your data comes in the format displayed in Figure 8.

image

FIGURE 8: Data from datasource

The idea is the same as in the previous example. We need to implement the RowDataBound event and check when the CategoryName changes. If it does, then we will display it, if it does not, then we hide it. But to make it more complicated, not only are we going to hide it, but we are going merge the rows together. Figure 9 displays the code needed to make this happened and Figure 10 displays the end result.


string previousCat = "";

int firstRow = -1;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

//We're only interested in Rows that contain data
//get a reference to the data used to databound the row
DataRowView drv = ((DataRowView)e.Row.DataItem);



if (previousCat == drv["CategoryName"].ToString())

{

//If it's the same category as the previous one
//Increment the rowspan
if (GridView1.Rows[firstRow].Cells[0].RowSpan == 0)

GridView1.Rows[firstRow].Cells[0].RowSpan = 2;

else
GridView1.Rows[firstRow].Cells[0].RowSpan += 1;

//Remove the cell
e.Row.Cells.RemoveAt(0);

}

else //It's a new category
{

//Set the vertical alignment to top
e.Row.VerticalAlign = VerticalAlign.Top;

//Maintain the category in memory
previousCat = drv["CategoryName"].ToString();

firstRow = e.Row.RowIndex;

}

}

}

FIGURE 9: Code to get rid of the repeated category

image

FIGURE 10: Products by Category

The code is very similar to the previous example. This time we are using the help of two global variables: previousCat and firstRow. The variable previousCat is used to save the category of the previous row, so if the category is the same we increment the row span of the row containing the category and then delete the first cell of the current row. Whenever a new category arrives we leave the row intact and save the previousCat and firstRow to their corresponding values. Please note that this code will only work correctly if the data is sorted by the category name.

Your boss is now ecstatic; he knows he had made a great investment by hiring you. He knows you are on a roll and that is why he wants to change the first report by adding an image right next to the discontinued products. Figure 11 shows the code to accomplish the task and Figure 12 shows the end result.


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

//We're only interested in Rows that contain data

//get a reference to the data used to databound the row
DataRowView drv = (DataRowView)e.Row.DataItem;
if (Convert.ToInt32(drv["UnitsInStock"]) == 0)

{

//The current product has 0 items in stock
e.Row.Font.Bold = true; //Make the font bold
e.Row.ForeColor = System.Drawing.Color.Red; //Set the text color red
if (Convert.ToInt32(drv["UnitsOnOrder"]) > 0)

{

//The current out of stock item has already been ordered
//Make it blue
e.Row.ForeColor = System.Drawing.Color.Blue;

}

}

if ((bool)drv["Discontinued"])

{

//Discontinued product

//Add the image
Image img = new Image();

img.AlternateText = "Discontinued Product";

img.ImageAlign = ImageAlign.AbsMiddle;

img.ImageUrl = "arrow_down.gif";

img.Width = Unit.Pixel(10);

img.Height = Unit.Pixel(11);

e.Row.Cells[0].Controls.Add(img);



//Add the text as a control
e.Row.Cells[0].Controls.Add(new LiteralControl(" " + e.Row.Cells[0].Text));

}

}

}

FIGURE 11: Code for setting fore color and discontinued image.

image

FIGURE 12: End result of the discontinued product

The code is the same code as in the first example with the addition of the discontinued part. We first have to check whether the current product is discontinued. If it is, then we create a new image and add it to the controls collection of the cell. Since we are adding a control to the collection, the GridView gives priority to the controls and ignores the text property, which is why we need to add the text as a control. This makes the GridView render the cell as an image with text right next to it.

Conclusion

From design time to run time formatting, from declarative programming to imperative programming, the GridView is one of the most complex and simple controls in the ASP.NET arsenal. It allows you to create simple tables with very little programming and also allows you to have full control of its formatting to create very complicated grids. Not only is the GridView a very powerful control for normal day to day functions such as displaying, adding, updating, and deleting data or for nice features such as paging and sorting, but also is a very powerful control in that it enables you to have full control of how it renders itself. I hope the next time you are creating a grid for your boss you can play around with the GridView Events and properties to come up with a neat solution.

Happy Programming!

http://www.simple-talk.com/dotnet/asp.net/take-row-level-control-of-your-gridview/

Tuesday, April 5, 2011

A piece of code today broke that didn't make sense at first. It was so ridiculous that I had to post about it. This isn't a C# is better than VB.NET entry. It's a legitimate "I thought I was supposed to be able to accomplish the same thing in VB.NET as I can in C# and vice-versa" entry. No flame-wars here!

The code was similar to this:

<ItemTemplate>
<%# IIf(IsDBNull(Eval("foo")), String.Empty, Eval("foo")) %>
ItemTemplate>

This is something that I do all the time in my C# UI. The C# conditional syntax lends itself nicely to this sort of deal.

<ItemTemplate>
<%# Eval("foo") == null ? String.Empty : Eval("foo") %>
ItemTemplate>

I used to get code where developers would literally have a TextBox or Label in the ItemTemplate and on RowDataBound or ItemDataBound cast the DataItem to T, analyze the value of a certain property or properties, and set the property of the TextBox, Label, etc... accordingly. Not cool with me. I opt for one-lining it whenever humanly possibly; which is what I tried to do earlier today. Only thing is, today I failed miserably.

I knew the code was broken because everything up until this column rendered as it should have. From this column-on everthing stopped. The results set consisted of at least 30 rows. Sweet. Since the code was in my presentation layer I couldn't really breakpoint it so I moved it to my code-behind. I found that there was a NullReferenceException. Really? I resorted to a different method of accomplishing this task via .aspx page.

<%#IIf(String.IsNullOrEmpty(Eval("foo").ToString), "A", Eval("foo"))%>

Wow. This failed miserably. Let's try something else.

<%#IIf(Eval("foo").ToString.Length = 0, "A", Eval("foo"))%>

This worked... NOT! In case you're curious, I resorted to using "A", "B", "C" for the 3 columns so I know which conditional broke. The first one broke every time.

I know that some of you are thinking that this problem shouldn't even filter down to the UI. By this I mean others have suggested that I take care of this problem in SQL. I already tried this using COALESCE and then with ISNULL.

ISNULL(FooColumn, '') AS FooColumn

There's a problem with this. What if FooColumn is of type money or integer? The example above wouldn't work (I tried) when the column is of type money or some type of numeric. AFAIK, there is no way to return an empty money value aside from 0.00 (if there is PLEASE let me know!). One of the requirements for this project was that NULL are valid for fields and nothing else should be displayed. That means the following wouldn't work.

ISNULL(FooColumn, 0) AS FooColumn

This would be misleading when the data is displayed because when the customer looked at the data they would think that FooColumn's value was actually 0 when in fact the zero is nothing more than an arbitrary value.

Another "fix" would be to just call ToString in the false part of my IIf statement. That works, to an extent. As soon as you introduce string formatting it won't work as it should.

I could, if I was absolutely desperate; enumerate the rows in the DataSet, check each column for NULL and replace with an empty string. Although it is a very nasty suggestion it would work.

Time for another test scenario. I created 2 console apps: 1 VB, 1 C#. Each does nothing more than declare an object that happens to be null as well as a SqlParameter that sets the value depending on the null'ity of said object.

First with the VB.

Dim foo As Object = Nothing

Dim parameter As SqlParameter = New SqlParameter()
parameter.ParameterName = "foo"
parameter.Value = IIf(foo Is Nothing, "NULL", "NOT NULL")

Console.WriteLine(IIf(foo Is Nothing, "NULL", foo.ToString))Console.WriteLine(parameter.Value)

C# equivalent.

object foo = null;

SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "foo";
parameter.Value = foo == null ? "NULL" : "NOT NULL";

Console.WriteLine(foo == null ? "NULL" : foo.ToString());
Console.WriteLine(parameter.Value);

I usually have the parameter name and value taken care of in the constructor as I am a self-confessed one-liner but opted for a more blog-friendly version (i.e. no text-wrapping). Anyway, the results surprised me. Surprised in a "are you f**king kidding me?" and not "This is f**king awesome!" way. To prove that there is no bias, I created the C# version first and used Reflector to disassemble and pasted the VB.NET version into my VB.NET console app.

I ran the C# version first to make sure I wasn't getting frustrated over nothing. As expected the console output was 2 NULL's. Now time for the VB version; unhandled exception (NullReference) at line 12. Line 12 is this gem right here:

Console.WriteLine(IIf(foo Is Nothing, "NULL", foo.ToString))

Hmmm. WTF would I get an exception when I am checking for NULL? Why is foo.ToString even being interpreted? In other words, how can foo NOT be null? At least that's how I looked at this.

After doing a little bit of research I have found that the IIf function will actually analyze the true and the false part of the expression. In other words, it doesn't behave anything like a conditional in C# and is merely a throwback to the VB language.

Further reading of WHY this doesn't work resulted in the fact that if IIf functioned like a C# conditional then code that was ported from VB to VB.NET would break. This is an example of how an explanation can make sense and at the same time not make any sense at all. On the one hand I can see the possible need to make code portable. On the otherhand why would you switch to VB.NET if you expect to write classic VB code? I thought the purpose of going .NET was to embrace the .NET framework, not rely on backwards compatibility.

Again I'll pose the question: Is there a way to accomplish what I am trying to do without abstracting out the functionality to a helper method consisting of a full-blown IF THEN ELSE statement? Is there a way to one-line this functionality?

As it stands now I have created a RetrieveFooValue function that takes my object, interprets, and returns an appropriate value. This is the best I could come up with. Again, if there's a more efficient way to do this PLEASE let me know.

<ItemTemplate>
<%# RetrieveFooValue(Eval("foo")) %>
ItemTemplate>

RetrieveFooValue contains a full-blown IF THEN ELSE statment.

Monday, April 4, 2011

In this PHP MySQL tutorial I will show you how to use basic database manipulation features in PHP.

Inserting data into the database

In this topic we will create a code to insert new records into our MySQL database. This is very similar to the select version. Also in this case we need to build up a database connection and we will use the mysql_query() function again. However in this case we will use it with an insert sql statement. Now let's try to insert a new user to our table. The sql statement is the following:

INSERT INTO users (name,city,web,age) VALUES ('Tom','Vegas','www.tom.com',44);

Now store this SQL statements in a variable and pass this as parameter of mysql_query like this:

Code:
  1. $sql = "INSERT INTO users (name,city,web,age) VALUES ('Tom','Vegas','www.tom.com',5)";
  2. $result = mysql_query($sql);

Besides this we need to check the result and inform the user if an error was occurred. A complete insert code is the following:

Updating a record
The update is almost the same as the insert. You only need to change the sql statement and use it as before:
  1. $sql = "UPDATE users SET age=45 WHERE name='Tom'";
  2. $result = mysql_query($sql);
Deleting a record
As you may know it is again the same as before. Only the sql needs to be changed like this:

Code:
  1. $sql = "DELETE FROM users WHERE name='Tom'";
  2. $result = mysql_query($sql);

Bạn muốn lập trình cho phép Export dữ liệu từ Datatable, Gridview ra Excel, Word hay PDF? Trong bài viết này mình sẽ giới thiệu với các bạn cách thực hiện điều đó bằng cách sử dụng thư viện itextsharp.dll.

Trước tiên bạn cần download thư viện itextsharp.dll về tại đây.
Sau khi down về giải nén và Add vào thư mục bin của ứng dụng. Sau đó khi cần thực hiện việc Export dữ liệu ra các định dạng khác nhau bạn thực hiện như bài minh họa sau. Trong bài này mình chỉ minh họa cách Export dữ liệu ra các định dạng word, Excel, PDF. Bạn có thể tìm hiểu thêm về thư viện itextsharp.dll để có thể export ra nhiều định dạng khác cùng như tìm hiểu các component khác của thư viện này.

Trước tiên bạn cần tạo một Form gồm một Gridview, và các Button (ExportToRord, ExportToExcelm ExportToPDF) như sau:

Trong code bạn thực hiện như sau: (Minh họa này mình lấy Database Northwind làm ví dụ và dữ liệu Export là các trường CustomerID, CompanyName, ContactName, ContactTitle)

1. Hàm GetDataToTable
private DataTable GetDataToTable(SqlCommand cmd)
{
DataTable dt = new DataTable();
// Khai báo chuỗi kết nối
String strConnString = @"Server =.SQL2005;Initial Catalog=Northwind;User SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
// Mở kết nối và đổ dữ liệu vào bảng
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//Đóng kết nối
con.Close();
sda.Dispose();
con.Dispose();
}
}

Trong hàm Page_Load bạn thực hiện truy vấn và Bind dữ liệu như sau

protected void Page_Load(object sender, EventArgs e)
{
// Truy vấn và đổ dữ liệu vào Gridview
string TruyVan = @"SELECT c.CustomerID, c.CompanyName,
c.ContactName, c.ContactTitle FROM Customers c";
SqlCommand cmd = new SqlCommand(TruyVan);
DataTable dt = GetDataToTable(cmd);
grvExport.DataSource = dt;
grvExport.DataBind();
}
2. Hàm xuất dữ liệu từ 1 gridview ra word
/// 
/// Xuất dữ liệu từ GridView ra word
///

private void XuatDuLieuRaWord(GridView MyGridview)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
// Bỏ phân trang - Nếu chỉ muỗn Export Trang hiện hành thì chọn =true
MyGridview.AllowPaging = false;
MyGridview.DataBind();
MyGridview.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
3. Hàm xuất dữ liệu từ một gridview ra Excel
/// 
/// Xuất dữ liệu từ GridView ra Excel
///

private void XuatDuLieuRaExcel(GridView MyGridview)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
// Bỏ phân trang - Nếu chỉ muỗn Export Trang hiện hành thì chọn =true
MyGridview.AllowPaging = false;
MyGridview.DataBind();
MyGridview.RenderControl(hw);
//Thay đổi Style
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
4. Hàm xuất dữ liệu từ gridview ra PDF
/// 
/// Hàm xuất dữ liệu từ gridview ra pdf
///

private void XuatDuLieuGridRaPDF(GridView MyGridview)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
MyGridview.AllowPaging = false;
MyGridview.DataBind();
MyGridview.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}

Trong các sự kiện click của các nut button bạn thực hiện như sau:

protected void btnExportWord_Click(object sender, EventArgs e)
{
XuatDuLieuRaWord(grvExport);
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
XuatDuLieuRaExcel(grvExport);
}
protected void btnExportPDF_Click(object sender, EventArgs e)
{
XuatDuLieuGridRaPDF(grvExport);
}

Bạn chú ý trong code của bạn cần có hàm sau để chứng thực việc sử dụng HtmlForm. Nếu không sẽ có lỗi "Control 'grvExport' of type 'GridView' must be placed inside a form tag with runat=server" khi thực hiện Export.

public override void VerifyRenderingInServerForm(Control control)
{
//Xác nhận điều khiển HtmlForm tại thời gian chạy ASP.NET
}

Sunday, April 3, 2011

Originally published on DataDeveloper.net

In this tutorial, you will create a new Entity Data Model inside an Class Library Project. The data model will be built from the AdventureWorksLT database.

The project can be used in (Windows, Console, Web, other class libraries etc) by referencing this project.

Create a new Class Library Project

  1. Select New Project from File Menu option
  2. Select your preferred project base: e.g. Visual Basic or C#
  3. Select Class Library
  4. Change the name of the application in the Name text box to DataDevEDM
  5. Click OK

Add an Entity Data Model Item

  1. In Solution Explorer, right click the project name.
  2. Click Add on the context menu that opens.
  3. Click New Item.
  4. In the Add New Item dialog, click ADO.NET Entity Data Model.
  5. Change the name from Model1.edmx to AWModel.edmx
    addnewitem
  6. Click the Add button
  7. In the Entity Data Model Wizard click Generate from Database, then click the Next button

Create a database connection for the Entity Data Model

If you have a database connection already created in Visual Studio, skip to Define Contents of an Entity Data Model

  1. On the Choose Your Data Connection page of the wizard, click the New Connection button.
  2. At the top of the connection properties window, click the Change button next to the Data Source
    clip_image004
  3. Select Microsoft SQL Server Database File from the Data source list, then click OK
  4. Click the Browse button to the right of Database file name
  5. Browse to the folder where you have saved the AdventureWorksLT database*.
  6. Select AdventureWorksLT.mdf then click Open.
    clip_image006
  7. At the bottom of the Connection Properties window, click OK

Define the contents of an Entity Data Model

  1. Select the database connection from the drop down.
  2. At the bottom of the Entity Data Model Wizard window, change the value of Entity connection settings to AWEntities then click Next.
    clip_image008

  3. On the next page, change the Model Namespace to AWModel.
  4. Check Tables, Views and Stored Procedures.
    This will include all of the items. You can expand these nodes to select only the specific tables, views and stored procedures that you want.
    clip_image010

  5. Click Finish.
  6. Note that in the solution explorer, a new file, AWModel.edmx has been created.
    explorer

View the model

  1. Double click the AWModel.emx file to open the model in the Entity Data Model designer.

model

ASP.NET MVC, Entity Framework, Modifying One-to-Many and Many-to-Many Relationships

see link: http://www.mikesdotnetting.com/Article/110/ASP.NET-MVC-Entity-Framework-Modifying-One-to-Many-and-Many-to-Many-Relationships