1

Fileupload in edit template of Gridview

Code Behind File:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(GridView1.EditIndex == -1) return;
FileUpload fileUpLoad = GridView1.Rows[GridView1.EditIndex].FindControl("FileUpload1") as FileUpload;
string fileName = fileUpLoad.FileName;
string fullPath = Path.GetFullPath(fileName);
fileUpLoad.SaveAs(fullPath);
}

0

Sitemap - Hiding Login/Logout etc

The following code shows to hide "Login" if users are already logged in and hide "Logout" if users are not logged in from the menu.

1   protected void Menu1_DataBound(object sender, EventArgs e)
2 {
3 Menu menu = (System.Web.UI.WebControls.Menu)sender;
4 MenuItem menuToRemove = null;
5
6 if (HttpContext.Current.User.Identity.IsAuthenticated)
7 {
8 foreach (MenuItem smn in menu.Items)
9 {
10 if (smn.Text == "Login")
11 {
12 MenuItem parent = smn.Parent;
13 if (parent != null)
14 {
15 parent.ChildItems.Remove(smn);
16 }
17 else
18 {
19 menuToRemove = smn;
20 }
21
22 }
23 }
24 if (menuToRemove != null)
25 {
26 menu.Items.Remove(menuToRemove);
27 }
28 }
29 else
30 {
31 foreach (MenuItem smn in menu.Items)
32 {
33 if (smn.Text == "Logout")
34 {
35 MenuItem parent = smn.Parent;
36
37 if (parent != null)
38 {
39 parent.ChildItems.Remove(smn);
40 }
41 else
42 {
43 menuToRemove = smn;
44 }
45
46 }
47 }
48
49 if (menuToRemove != null)
50 {
51 menu.Items.Remove(menuToRemove);
52 }
53 }
54
55
56 }

0

Get the control out from the templatefield of Detailsview

The following codes are the examples to get the control out from the templatefield of Detailsview:

TextBox UserNameBox = DetailsView1.FindControl("UserName") as TextBox;

Label ErrorLabel = DetailsView1.FindControl("ErrorLabel") as Label;

0

Check for duplicate records before executing INSERT

The following code may handle the exception when insert the duplicate records

protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
//handle error or display message on label or something here
}
}

0

Use the GridView to insert a new record



This article is written by Fredrik Normen
Source: http://fredrik.nsquared2.com/viewpost.aspx?PostID=155

Category: ASP.Net 2.0


Introduction

By default the GridView control doesn’t have support of inserting records. In this post I’m going to show you an example how you can use the GridView’s FooterTemplate and the SqlDataSourceControl to insert a record.

The FooterTemplate in a GridView is column based (It will not be a separate table at the end of the GridView, instead if will be added at the end of the GridView but into a column). By making the example in this post as simple as possible, I’m going to use the TemplateField to create the GridView. The GridView in the example will not support editing. I will only focus on inserting.

The following code is a GridView where the Customer table located in the Northwind database is used. The GridView will have three columns (CustomerID, CompanyName and ContactTitle). To each column there is a FooterTemplate with editable fields:

<%@ Page Language="C#" ClassName="Default_aspx" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

void Button1_Click(object sender, EventArgs e)

{

TextBox customerID = GridView1.FooterRow.FindControl("CustomerIDTextBox") as TextBox;

TextBox companyName = GridView1.FooterRow.FindControl("CompanyNameTextBox") as TextBox;

DropDownList ContactTitle = GridView1.FooterRow.FindControl("ContactTitleDropDownList") as DropDownList;

SqlDataSource1.InsertParameters["CustomerID"].DefaultValue = customerID.Text;

SqlDataSource1.InsertParameters["CompanyName"].DefaultValue = companyName.Text;

SqlDataSource1.InsertParameters["ContactTitle"].DefaultValue = ContactTitle.SelectedValue;

SqlDataSource1.Insert();

}

script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="GridView1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID"

AutoGenerateColumns="False" ShowFooter="True">

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="CustomerIDLabel" Runat="Server"><%# Eval("CustomerID") %>asp:Label>

ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="CustomerIDTextBox" Runat="server">asp:TextBox>

FooterTemplate>

asp:TemplateField>

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="CompanyNameLabel" Runat="Server"><%# Eval("CompanyName") %>asp:Label>

ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="CompanyNameTextBox" Runat="server">asp:TextBox>

FooterTemplate>

asp:TemplateField>

<asp:TemplateField>

<FooterTemplate>

<asp:DropDownList ID="ContactTitleDropDownList" Runat="server" DataSourceID="SqlDataSource2" DataTextField="ContactTitle" DataValueField="ContactTitle">

asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource2" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]"

ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>">

asp:SqlDataSource>

<asp:Button ID="Button1" Runat="server" Text="Add" OnClick="Button1_Click" />

FooterTemplate>

<ItemTemplate>

<asp:DropDownList ID="ContactTitleDropDown" SelectedValue='<%# Bind("ContactTitle") %>' Runat="Server" DataSourceID="SqlDataSource3" DataTextField="ContactTitle" DataValueField="ContactTitle" >asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource3" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]"

ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>" EnableCaching="True">

asp:SqlDataSource>

ItemTemplate>

asp:TemplateField>

Columns>

asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"

InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactTitle)"

SelectCommand="SELECT [CustomerID], [CompanyName], [ContactTitle] FROM [Customers]"

ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>">

<DeleteParameters>

<asp:Parameter Type="String" Name="CustomerID">asp:Parameter>

DeleteParameters>

<UpdateParameters>

<asp:Parameter Type="String" Name="CompanyName">asp:Parameter>

<asp:Parameter Type="String" Name="ContactTitle">asp:Parameter>

<asp:Parameter Type="String" Name="CustomerID">asp:Parameter>

UpdateParameters>

<InsertParameters>

<asp:Parameter Type="String" Name="CustomerID">asp:Parameter>

<asp:Parameter Type="String" Name="CompanyName">asp:Parameter>

<asp:Parameter Type="String" Name="ContactTitle">asp:Parameter>

InsertParameters>

asp:SqlDataSource>

div>

form>

body>

html>

As I have mentioned before, the GridView do not have support of inserting like the DetailView and FormView etc. So we have to programmatically get the value from the controls located in the FooterTemplate, and set the value of the SqlDataSource insert parameters. When this is done we add the record by calling the SqlDataSource insert method. This method will execute the data source’s InsertCommand (This will be done when the Add button located in the FooterTemplate is pressed):

void Button1_Click(object sender, EventArgs e)

{

TextBox customerID = GridView1.FooterRow.FindControl("CustomerIDTextBox") as TextBox;

TextBox companyName = GridView1.FooterRow.FindControl("CompanyNameTextBox") as TextBox;

DropDownList ContactTitle = GridView1.FooterRow.FindControl("ContactTitleDropDownList") as DropDownList;

SqlDataSource1.InsertParameters["CustomerID"].DefaultValue = customerID.Text;

SqlDataSource1.InsertParameters["CompanyName"].DefaultValue = companyName.Text;

SqlDataSource1.InsertParameters["ContactTitle"].DefaultValue = ContactTitle.SelectedValue;

SqlDataSource1.Insert();

}

To get the Control from the FooterTemplate, we can use the FooterRow property of the GridView control. This property represents a GridViewRow and by using the FindControl method, we can get a control by its Id.

Showing and Hiding footer

By default you maybe want to hide the footer until the user presses a button control for adding a new record. This could be done by setting the ShowFooter property of the GridView control. By default the ShowFooter property is false:

Button ID="AddButton1" runat="Server" Text="Add new Item"

OnClick="AddButton1_Click" />

void AddButton1_Click(object sender, EventArgs e)

{

GridView1.ShowFooter = true;

}

The following is an example where the footer will be displayed if the user presses the “Add Item” button. There is also a Cancel button next to the Add button in the footer to make it possible to cancel the insert (Hide the footer):

<%@ Page Language="C#" ClassName="Default_aspx" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

void Button1_Click(object sender, EventArgs e)

{

TextBox customerID = GridView1.FooterRow.FindControl("CustomerIDTextBox") as TextBox;

TextBox companyName = GridView1.FooterRow.FindControl("CompanyNameTextBox") as TextBox;

DropDownList ContactTitle = GridView1.FooterRow.FindControl("ContactTitleDropDownList") as DropDownList;

SqlDataSource1.InsertParameters["CustomerID"].DefaultValue = customerID.Text;

SqlDataSource1.InsertParameters["CompanyName"].DefaultValue = companyName.Text;

SqlDataSource1.InsertParameters["ContactTitle"].DefaultValue = ContactTitle.SelectedValue;

SqlDataSource1.Insert();

}

void AddButton1_Click(object sender, EventArgs e)

{

GridView1.ShowFooter = true;

}

void CancelButton1_Click(object sender, EventArgs e)

{

GridView1.ShowFooter = false;

}

script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

<form id="form1" runat="server">

<div>

<asp:Button ID="AddButton1" runat="Server" Text="Add new Item" OnClick="AddButton1_Click" />

<asp:GridView ID="GridView1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID"

AutoGenerateColumns="False">

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="CustomerIDLabel" Runat="Server"><%# Eval("CustomerID") %>asp:Label>

ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="CustomerIDTextBox" Runat="server">asp:TextBox>

FooterTemplate>

asp:TemplateField>

<asp:TemplateField>

<ItemTemplate>

<asp:Label ID="CompanyNameLabel" Runat="Server"><%# Eval("CompanyName") %>asp:Label>

ItemTemplate>

<FooterTemplate>

<asp:TextBox ID="CompanyNameTextBox" Runat="server">asp:TextBox>

FooterTemplate>

asp:TemplateField>

<asp:TemplateField>

<FooterTemplate>

<asp:DropDownList ID="ContactTitleDropDownList" Runat="server" DataSourceID="SqlDataSource2" DataTextField="ContactTitle" DataValueField="ContactTitle">

asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource2" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]"

ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>">

asp:SqlDataSource>

<asp:Button ID="Button1" Runat="server" Text="Add" OnClick="Button1_Click" />

<asp:Button ID="CancelButton1" Runat="server" Text="Cancel" OnClick="CancelButton1_Click" />

FooterTemplate>

<ItemTemplate>

<asp:DropDownList ID="ContactTitleDropDown" SelectedValue='<%# Bind("ContactTitle") %>' Runat="Server" DataSourceID="SqlDataSource3" DataTextField="ContactTitle" DataValueField="ContactTitle" >asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource3" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]"

ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>" EnableCaching="True">

asp:SqlDataSource>

ItemTemplate>

asp:TemplateField>

Columns>

asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"

InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactTitle)"

SelectCommand="SELECT [CustomerID], [CompanyName], [ContactTitle] FROM [Customers]"

ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>">

<DeleteParameters>

<asp:Parameter Type="String" Name="CustomerID">asp:Parameter>

DeleteParameters>

<UpdateParameters>

<asp:Parameter Type="String" Name="CompanyName">asp:Parameter>

<asp:Parameter Type="String" Name="ContactTitle">asp:Parameter>

<asp:Parameter Type="String" Name="CustomerID">asp:Parameter>

UpdateParameters>

<InsertParameters>

<asp:Parameter Type="String" Name="CustomerID">asp:Parameter>

<asp:Parameter Type="String" Name="CompanyName">asp:Parameter>

<asp:Parameter Type="String" Name="ContactTitle">asp:Parameter>

InsertParameters>

asp:SqlDataSource>

div>

form>

body>

html>

In the examples in this post, I don’t focus on performance optimization. One thing you can do to increase the performance, is to enable caching for the data source controls that will be used to fill the DropDownList controls. To enable caching you set the EnableCaching attribute of the data source to true. If you enable caching for the data source controls that is associated to a DropDownList, you maybe want the cache to be discarded if there have bean changes in the table where the data source gets its data from. This can be done by using the Sql cache dependency with the data source control.

Eclipse JFace Tutorial




(FROM: http://www.eclipsepluginsite.com/jface.html)

Working With JFace Viewers

We have already seen SWT in action. It helps in rapid application development by providing ready made widgets like Tree, Table etc. However, there is a severe limitation in using these widgets directly. Let me explain it with an example. Consider the table example in SWT chapter. Following lines of code were used to populate Table with one row of data.

TableItem tableItem1 = new TableItem(myTable, SWT.NULL);
tableItem1.setText(new String[] {"A1", "A2"});

You can see that we have used String Literals "A1" and "A2" respectively while creating a row in table. If you think from object oriented perspective it is a severe limitation. In object oriented world we talk in terms of Objects. In order to build above table we will have to get Strings out of those objects and then supply it to Table to form every single row. Isn’t there a way in which we can simply map objects to tables so that table can itself use those objects and populate itself? This is where JFace viewers step in to provide OO wrappers around their associated SWT widgets. JFace provides two types of Viewers, Text Viewers and List Viewers. First we will discuss about list viewers.

List Viewers

JFace list viewers, such as TableViewer and TreeViewer, allow you to directly use your business objects (Employee, Customer, User, Business etc.) without. The trick is to provide adapters for things such as retrieving an item's name/label OR for retrieving an Tree parent's children (tree widget). So we will talk about these adaptors first before moving onto implementing Table/Tree Viewers.

1. Label Providers

A label provider maps an element of the viewer's model to an optional image and optional text string used to display the element in the viewer's control.

The two most frequently used label providers are ILabelProvider and ITableLabelProvider In order to display elements name and label we can use getImage and getText methods provided by ILabelProvider Similarly in case of ITableLabelProvider, in order to display label image and label text for any column in a table we can use getColumnImage and getColumnText. We can use setLabelProvider() method to attach/associate provider with the viewer.

2. Content Providers

A content provider is another common adapter type used in list viewers. This provider is used to feed the actual content to the viewer. Viewer then uses its internal logic to display these input elements with its internal controls.

The two most frequently used content providers are IStructuredContentProvider and ITreeContentProvider. These adapters provide convienient methods to retrive child elements for a given element. We can use setContentProvider() method to attach/associate provider with the viewer. A intial domain/business model of the application can be associated with the viewer with the help of setInput() method.

3. Viewer Sorters

A viewer sorter is a adapter which is called by viewer before the elements/contents are displayed to the user. We can use this provider to sort the elements which are provided by the content provider. We can use setSorter() method on the viewer to attach sorter.

4. Viewer Filters Providers

As the name suggests a viewer filter is used to filter out some of the elements from original list of elements provided by the content provider. For example: Original list of Employees consist of employees with two type of roles Admin, Non admin. We can use filters to display only admin role users. We can attach viewer filter by using the setFilter() method on the viwer itself.

Table Viewers

The TableViewer class acts as a OO wrapper around the Table widget. Table Viewer is capable of displaying data in rows and cloumns with the help of adapters like label provider and content provider.

Table Viewer provides many useful APIs, Please refer to online Eclipse Platform API Specification

Following example creates a table viewer

   public static void main(String[] args) {
Display exampleDisplay = new Display();
Shell exampleShell = new Shell(exampleDisplay);

exampleShell.setBounds(120, 120, 345, 220);
exampleShell.setLayout(new FillLayout());

final TableViewer myTableViewer = new TableViewer(
exampleShell, SWT.SINGLE);

final Table myTable = myTableViewer.getTable();

String[] myColumns = new String[] {
"Hello", "Bye"};

for (int i = 0; i < tablecolumn =" new">

In Above listing we are creating table viewer Then we are creating two columns namely "Hello" and "Bye" The header of each column is set using setText() method. There after label provider and content providers are being attached with the viewer. Following listing shows how the label provider looks like

public class PersonTableLabelProvider
extends LabelProvider
implements ITableLabelProvider {
public Image getColumnImage(
Object element, int) {
return null;
}

public String getColumnText(Object element, int index) {
Example ex = (Example) element;
switch (index) {
case 0 :
return ex.hello;
case 1 :
return ex.bye;
}
}
}


public class Example{
String hello;

String bye;

Example(String hello, String bye){
this.hello = hello;
this.bye=bye;
}

public static Example[] getInput(){
return new Example[]{
new Example("FirstHello","FirstBye"),new Example("SecondHello","SecondBye")
};
}
}

Tree Viewers

The treeViewer class acts as a OO wrapper around the Tree widget. Tree Viewer is capable of displaying data in hierarchical manner with the help of adapters like label provider and content provider.

Tree Viewer provides many useful APIs, Please refer to online Eclipse Platform API Specification

The following listing creates a tree viewer

   public static void main(String[] args) {
Display exampleDisplay = new Display();
Shell exampleShell = new Shell(exampleDisplay);

exampleShell.setBounds(120, 120, 220, 220);
exampleShell.setLayout(new FillLayout());

final TreeViewer myTreeViewer =
new TreeViewer(exampleShell, SWT.SINGLE);

myTreeViewer.setLabelProvider(
new MyTreeLabelProvider());

myTreeViewer.setContentProvider(
new MyTreeContentProvider());

myTreeViewer.setInput(Example1.getInput());

exampleShell.open();

while (!exampleShell.isDisposed()) {
if (!exampleDisplay.readAndDispatch()) exampleDisplay.sleep();
}
exampleDisplay.dispose();
}

In above code listing we are creating the tree viewer. There after we are configuring label and content adapters. Following listing shows the rest of code:

public class MyTreeContentProvider
extends ArrayContentProvider
implements ITreeContentProvider {


public Object[] getChildren(Object parent) {
Example1 ex1 = (Example1) parent;
return ex1.children;
}

public Object getParent(Object element) {
Example1 ex1 = (Example1) element;
return ex1.parent;
}


public boolean hasChildren(Object element) {
Example1 ex1 = (Example1) element;
return ex1.children.length > 0;
}
}


public class MyTreeLabelProvider extends LabelProvider {
public Image getImage(Object element) {
return null;
}
public String getText(Object element) {
Example1 ex1 = (Example1) element;
return ex1.name;
}
}


public class Example1{
String name;

Example1[] children = new Example1[0];

Example1 parent = null;

Example1(String name){
this.name = name;
}


Example1(String name,Example1[] children){
this.name = name;
this.children = children;
for (int i = 0; i < parent =" this;">