Chào mừng đến với site của Bee! Chúc các bạn có những giây phút thực sự vui vẻ!!!

Chủ Nhật, 26 tháng 5, 2013

JSTL và các action thường sử dụng c:forEach, c:otherwise, c:choose..

JSTL và các action thường sử dụng c:forEach, c:otherwise, c:choose

JavaServer Pages Standard Tag Library (JSTL)

Vào năm 1997 Sun Microsystems giới thiệu các API Servlet. Servlet đã tạo 1 sự khác biệt rất lớn cho các nhà phát triển Web bằng CGIservlet mạnh mẽ và hiệu quả hơn. Tuy nhiên khi đưa vào áp dụng, các nhà lập trình đã chỉ ra rằng servlet có một thiếu sót hết sức quan trọng đó là các nhà phát triển web tạo ra giao diện về phía client bằng cách xuất ra các đoạn code HTML thông qua câu lệnh print. Điều này gây khó khăn trong việc duy trì mở rộng code. Điều thiếu sót này nhanh chóng được khắc phục bằng JSP cho phép nhúng các đoạn code Java.
Tuy nhiên, như trong hầu hết các trường hợp, giải pháp này lại có một thiếu sót của riêng nó: mã Java nhúng trong HTML sẽ dẫn đến sự phức tạp trong các trang JSP, sự kết hợp code business logicpresentation làm cho trang JSP trở nên khó hiểu và khó duy trì. Hơn nữa, việc chỉ giới hạn trong một số thẻ tiêu chuẩn như <jsp:useBean> hay <jsp:include>, JSP có thể tốt cho những người phát triển Web thông hiểu Java, nhưng sẽ gây khó khăn cho những người chưa có kinh nghiệm nhiều trong Java. Để đối phó với khó khăn này, các nhà phát triển Java lợi dụng một ưu điểm của Java là cho phép tạo ra các custom tag, rất nhiều custom tag được tạo ra ví dụ như Jakarta Taglibs được tạo ra bởi Apache Software Foundation

Từ sự phát triển của Jakatar Taglibs và những phản ứng tiêu cực khi phát triển web trên JSP, JavaServerPages Standard Tag Library (JSTL) được sinh ra. Sự kết hợp giữa Expression language và thư viện tiêu chuẩn toàn diện, JSTL đã tận diệt sự cần thiết phải dùng scriptletexpression trong trang JSP

I. JSTL là gì: JSTL bao gồm các phần sau:
- Expression Language
- Thư viện các hành động tiêu chuẩn
- Thư viện cho validation
- Expression Language được cho là tính năng quan trọng nhất của JSTL. Expression Language cho phép truy xuất vào các implicit object như request, response, các biến liên quan đến scope
- Thư viện các hành động tiêu chuẩn cung cấp một nền tảng vững chắc cho việc lập trình web từ việc lập vòng lập, import URLS đến kết nối database, đọc XML….

II. Các thư viện thẻ của JSTL:
- Thư viện thẻ của JSTL được chia làm 4 loại như sau:
Tên thư viện (prefix) Mô tả
Core (c) Chứa các hành động cơ bản như if, forEach….
Formatting (fmt) Định dạng và quốc tế hóa
SQL (sql) Truy xuất CSDL
XML (x) Phân tích và đọc dữ liệu từ XML


1. Core Action: gồm các chức năng sau
- Send output to the current JspWriter
- Gửi output đến JspWriter hiện tại
- Thao tác trên các thành phần của Java Bean
- Triển khai statement if hay switch
- Xử lý các Exception
- Duyệt qua các mảng giá trị, chuỗi
- Tạo các URLs và import tài nguyên
- Redirect servlet responses
- Chuyển các trả lời của Servlet
- Tạo và hủy các biến trong scope
- Các Action trong Core:

Tên Action Ý nghĩa
<c:catch> Catch những exception xảy ra trong code body
<c:choose> Chọn 1 trong nhiều đoạn mã để thi hành khi thỏa mãn điều kiện nào đó
<c:forEach> Vòng lặp quét hết tập hợp nào đó
<c:forToken> Vòng lặp quét hết 1 chuỗi nào đó theo chuỗi phân cách
<c:if> Thi hành đoạn code khi thỏa mãn điều kiện
<c:import> Import một URL nào đó
<c:otherwise> Xác định giá trị mặc định cho <c:choose>
<c:out> Gửi output cho JspWriter hiện hành
<c:param> Xác định 1 tham số URL cho <c:import> hay <c:url>
<c:redirect> Điều hướng request sang URL mới
<c:remove> Xóa 1 đối tượng trong 1 scope nào đó
<c:set> Tạo 1 đối tượng trong 1 scope nào đó
<c:url> Tạo 1 URL
<c:when> Khai báo điều kiện trong <c:choose>


2.
Formatting Action:
JSTL formatting Action cho phép người lập trình quốc tế hóa trang web của mình. Người lập trình có thể:
- Xác định resource bundle cho các thông báo với nhiều ngôn ngữ
- Xác định khu vực để định dạng ngày tháng, tiền tệ, phần trăm
- Các Action trong Formatting
Tên Action Ý nghĩa
<fmt:bundle> Xác định resoure bundle cho các messge đi kèm trong thẻ fmt:bundle
<fmt:setBundle> Xác định resoure bundle và gán vào 1 biến để dùng sau này
<fmt:formatDate> Định dạng ngày theo 1 vùng địa lý nào đó
<fmt:formatNumber> Định dạng số theo 1 vùng địa lý nào đó
<fmt:message> Truy xuất vào 1 message trong bundle


III.
Nguyên tắc thiết kế:
Để tận dụng tốt nhất của JSTL, bạn nên tìm hiểu những nguyên tắc thiết kế của JSTL, các nguyên tắc này áp dụng đối với nhiều thẻ trong JSTL nhưng không phải tất cả. Các nguyên tắc thiết kế thảo luận trongphần này là:
- Qui ước đặt tên
- Phạm vi của biến
- Các thuộc tính động
- Xử lý lỗi
1. Qui ước đặt tên:
- Tên thẻ và tên thuộc tính của thẻ được đặt tên theo qui ước đặt tên của Java: qui tắc Lạc Đà, từ đầu tiên là chữ thường, các từ tiếp theo được viết hoa đầu từ. Ví dụ:
<c:out value='${param.amount}'/>
<c:forEach var='item' items='${names}' varStatus='status'>
2. Scoped Variables vs. Scripting Variables
- Các thẻ JSTL như là một ống dẫn giữa trang JSP và mã code của Java. Thông qua ống dẫn này, thông tin được truyền từ trang JSP vào code Java và ngược lại. Hãy xem xét ví dụ sau đây:

<c:forEach var='item' begin='1' end='10'>
value = <c:out value='${item}'/><br>
</c:forEach>- Trong đoạn mã trên, trang JSP sử dụng thẻ <c:forEach> để gửi thông tin qua giá trị của biến “var” cho class tag handler. Class tag handler tạo ra 1 đối tượng “item” như là một biến cục bộ cho thẻ <c:forEach>
3. Các thuộc tính động:
- Giá trị của các thuộc tính trong JSTL có thể tĩnh hoặc động. Giá trị của thuộc tính động có thể được xác định thông qua các Expression Language (EL)
4. Xử lý lỗi:
- JSTL làm tất cả để tránh xảy ra các lỗi trong quá trình thi hành. Trong nhiều trường hợp nếu bạn khai báo giá trị null hay chuỗi rỗng cho thuộc tính, giá trị đó sẽ được chuyển đổi thành các hằng số vô hại ( như “0” chẳng hạn)
IV. Thẻ General-Purpose and Conditional:
- Một số nhiệm vụ cơ bản của các nhà phát triển JSP bao gồm tạo ra output, truy xuất và thay đổi giá trị các biến trên các scope, các thuộc tính của JavaBean, thực các biểu thức điều kiện và xử lý exceptions
- Các thẻ General-purpose:
- JSTL cung cấp 4 thẻ sau cho General Purpose:
<c:out>
<c:set>
<c:remove>
<c:catch>
- Ví dụ: chúng ta làm một ví dụ đơn giản về các thẻ general purpose như sau:
- Trong ví dụ trên chúng ta dùng EL để truy xuất vào parameter của request lấy giá trị của “buttonText”, và dùng <c:out> để xuất giá trị. Khi thi hành chúng ta có kết quả như hình sau:
Trước khi Submit
Sau khi submit
V. Thẻ Conditional:
- JSTL cung cấp 4 thẻ cho Conditional:
<c:if>
<c:choose>
<c:when>
<c:otherwise>
- Ngoài ra JSTL còn cung cấp thêm 2 thẻ cho vòng lặp là <c:forEach> và <c:forToken>
- Ví dụ: chúng ta làm ví dụ kết hợp các thẻ trên với nhau như sau:
- Đầu tiên chúng ta hiển thị kết quả từ vòng lặp:
- Khi trang web chạy lần đầu chúng ta cho phép người dùng nhập vào các giá trị cần thiết cho vòng lặp
- Trong trường hợp người dùng nhập vào các giá trị không đúng, chúng ta xuất thông báo lỗi như sau:
- Khi thi hành chúng ta có kết quả sau:
- Khi nhập liệu sai định dạng chúng ta có thông báo sau:
Đũa Cùi
bodua.com
Tham khảo từ nguồn:
Core JSTL: Mastering the JSP™ Standard Tag Library
By David M. Geary

Thứ Bảy, 25 tháng 5, 2013

C# DataTable

DataTable
Data is read from a database. It is generated in memory from input. DataTable is ideal for storing data from any source. With it we take objects from memory and display the results in controls such as DataGridView.

Example

NoteThe DataTable type is a convenient and powerful way to store data in memory. You may have fetched this data from a database, or dynamically generated it. We get a DataTable with four columns of type int, string and DateTime.
Int String DateTime
Then: This DataTable could be persisted or displayed, stored in memory as any other object, or with helper methods manipulated.
Program that uses DataTable: C#

using System;
using System.Data;

class Program
{
    static void Main()
    {
 //
 // Get the DataTable.
 //
 DataTable table = GetTable();
 //
 // Use DataTable here with SQL.
 //
    }

    /// <summary>
    /// This example method generates a DataTable.
    /// </summary>
    static DataTable GetTable()
    {
 //
 // Here we create a DataTable with four columns.
 //
 DataTable table = new DataTable();
 table.Columns.Add("Dosage", typeof(int));
 table.Columns.Add("Drug", typeof(string));
 table.Columns.Add("Patient", typeof(string));
 table.Columns.Add("Date", typeof(DateTime));

 //
 // Here we add five DataRows.
 //
 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;
    }
}
GetTable instantiates a new DataTable reference, adds four column collections to it, and then adds five drug and patient records. The next step to using this code could be to assign the DataSource to a Windows Forms control.

Example 2

The next example here shows how to insert data from object collections such as List into a DataTable. We then render that table onto the screen with Windows Forms. DataTable helps with the visual display of data.
DataTable example screenshotQuestion and answerWhy use DataTable here? It makes your DataGridView simpler and easier. You could manually add data to the DataGridView using the Add method. It is better to put the logic in a separate class.
Caution: DataGridView has performance problems with manually adding rows. Using DataTable instead alleviates these.
How to use a DataGridView. Make a new Windows Forms project and add a DataGridView to it. The control will be named dataGridView1 automatically. Its purpose will be rendering the DataTable you will make.
Steps
And: You need some actual data for the example. You will have something important—just use that.
Getting started. We want to make a new class and a method that returns DataTable. This method will return the full DataTable. In testing, the application handled one million numbers with only moderate slowdowns.
Program that uses DataTable with DataGridView: C#

using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
 /// <summary>
 /// Contains column names.
 /// </summary>
 List<string> _names = new List<string>();

 /// <summary>
 /// Contains column data arrays.
 /// </summary>
 List<double[]> _dataArray = new List<double[]>();

 public Form1()
 {
     InitializeComponent();

     // Example column.
     _names.Add("Cat");
     // Three numbers of cat data
     _dataArray.Add(new double[]
     {
  1.0,
  2.2,
  3.4
     });

     // Another example column
     _names.Add("Dog");
     // Add three numbers of dog data
     _dataArray.Add(new double[]
     {
  3.3,
  5.0,
  7.0
     });
     // Render the DataGridView.
     dataGridView1.DataSource = GetResultsTable();
 }

 /// <summary>
 /// This method builds a DataTable of the data.
 /// </summary>
 public DataTable GetResultsTable()
 {
     // Create the output table.
     DataTable d = new DataTable();

     // Loop through all process names.
     for (int i = 0; i < this._dataArray.Count; i++)
     {
  // The current process name.
  string name = this._names[i];

  // Add the program name to our columns.
  d.Columns.Add(name);

  // Add all of the memory numbers to an object list.
  List<object> objectNumbers = new List<object>();

  // Put every column's numbers in this List.
  foreach (double number in this._dataArray[i])
  {
      objectNumbers.Add((object)number);
  }

  // Keep adding rows until we have enough.
  while (d.Rows.Count < objectNumbers.Count)
  {
      d.Rows.Add();
  }

  // Add each item to the cells in the column.
  for (int a = 0; a < objectNumbers.Count; a++)
  {
      d.Rows[a][i] = objectNumbers[a];
  }
     }
     return d;
 }
    }
}

Description

SquaresThe above code is an entire Form and can be dropped into a Windows Forms application with a DataGridView in the designer. The two arrays are initialized in the class and in the constructor. They contain column information.
In the above code, we create a new DataTable. This is populated with data and put into the DataGrid. There are more efficient ways of modifying existing DataTables. By changing an existing one, you could avoid excess allocations.
Loop through columns. We have a collection that contains many arrays. Each of those arrays needs to be a new column. So the main for-loop in the above code goes through the data we want to put in each column.
Tip: This site has more information about looping through the rows and cells in the DataTable type.
DataTable Foreach LoopNoteAdd columns by name. We add the column names to the DataTable. This can be the data series type, such as "name", "number" or "id". These are the column headers, which must be added with Columns.Add.
Tip: DataTable requires object arrays to assign to the cells. Object arrays hold any derived type.
Warning: exclamation markWe keep adding rows until we have enough to contain all the data points in our array. If we don't add empty rows, the runtime will throw an exception. Right after this step, we assign the cells.
We set each cell in this column to its data value. Please be careful with the indexer syntax on the DataTable—make sure there are enough rows. We directly use our object list that we converted.

DataSource

Framework: NETHere we assign the DataSource of a DataGridView directly to the result value. We use the built-in display logic. For Windows Forms, DataSource provides better display performance than trying to individually add elements.
Example code that sets DataSource: C#

//
// Draw new cells on DataGridView.
//
dataGridView1.DataSource = null;
dataGridView1.DataSource = GetResultsTable();

Convert List

Convert or changeThe List type is often useful. The DataTable type is better for when you are interacting with controls such as the DataGridView or with SQL databases. It is sometimes a good idea to convert your List into a DataTable.
Convert List, DataTable

DataRow, DataColumn

Programming tipThe two most important parts of DataTable are its Rows collection and its Columns collection. Use the instance Add method to add to either of these collections. We look also into the types' internal representations.
Tip: There is more information, including many examples, of using DataRow and DataColumn collections on this site.
DataRow DataColumn
DataSet: You can combine multiple DataTable instances into one collection by using the DataSet type. This provides useful functionality.
DataSet Examples
DataView: One useful way to manipulate your DataTable's representation is to sort it using DataView. The DataView has a Sort property.
DataView Examples

Select

Select method callYou can use the Select method on the DataTable itself to filter elements based on some criteria. You receive an array of DataRow instances that match your filter. The filter is specified in string format.
DataTable Select

Using

Using keywordDataTable can be placed in a using statement. But is this worthwhile? Often the using block construct helps improve resource management in programs. We show the using statement wrapping a DataTable.
Tip: You can add Columns and Rows to the DataTable instance inside, but not outside, the using block.
Program that uses using statement: C#

using System;
using System.Data;

class Program
{
    static void Main()
    {
 using (DataTable table = new DataTable())
 {
     table.Columns.Add("Name", typeof(string));
     table.Columns.Add("Date", typeof(DateTime));

     table.Rows.Add("cat", DateTime.Now);
     table.Rows.Add("dog", DateTime.Today);
 }
    }
}
In this example, the Dispose method is invoked. After the using statement, the Dispose method on DataTable is called. This method is implemented on the base class for DataTable: MarshalValueByComponent.
UsingWorthwhile? Is enclosing the DataTable inside a using statement worthwhile? When Dispose is called, native resources from MarshalValueByComponent (a base class of DataTable) are released. This may be helpful.
Therefore: It is possible that the using statement could alleviate some resource usage problems.
Also, it is probably not important, but the using statement is good coding hygiene for DataTables. It is recommended if your program has any possible memory or resource usage issues. Some resources may be abandoned without it.

Summary

SummaryWe used DataTable in several C# programs. To it we added data, in the form of columns and rows. This code is effective when storing more than one million data points and rendering them every three seconds. It is efficient.
Tip: DataTable is faster in Windows Forms than manually adding rows. It reduces complexity.

Source: dotnetperls.com

Use DropDownList in ASP.NET GridView Control


In this article, I am going to demonstrate how to bind drop down list to a grid view control in edit mode.  I am not going to cover any basics in this article. If you are new to using grid view or if you would like know more about grid view, I would recommend you to reach following tutorials:
Using GridView in ASP.NET & C# —PART 1
Using GridView in ASP.NET & C# —PART 2
How to Insert, Update & Delete rows in ASP.NET GridView Control
Overview:
I am using Adventure Works as the data source. When page is initially loaded, We fetch products from Production.Product table and bind them to the grid. We display some product attributes such as Product ID, Product Number, Product Name, Product Subcategory Name and List Price. When user clicks on edit, grid enters into edit mode. We mark Product Name, Product Sub Category & List price as editable fields in the design. In case of Product Sub Category, we load the list of all product categories available in the Production.ProductionSubcategory table into a drop down list and are available for user selection.
Database Connection
Create a new ASP.NET Web Application project. Open web.config and add following entry to connection strings element.
<add name="Sql" connectionString="Data Source=(local);
     Initial Catalog=AdventureWorks;User=testuser;Password=testuser;"
     providerName="System.Data.SqlClient"/>
Page Design
Create a new ASP.NET web page. Rename Default.aspx to EditProductsView.aspx and update any references. We don’t want a fancy grid, so just applying some basic formatting. As you can see we are tapping into four events of grid view to satisfy this requirement. I will discuss about these events later.
<asp:gridview id="gvProducts"         
autogeneratecolumns="False"
BorderColor="White" BorderStyle="Ridge"
CellSpacing="1" CellPadding="3" GridLines="None"
BackColor="White" BorderWidth="2px"
emptydatatext="No data available."              
runat="server" DataKeyNames="ProductID"
OnRowEditing="gvProducts_RowEditing"
OnRowCancelingEdit="gvProducts_RowCancelingEdit"        
onrowupdating="gvProducts_RowUpdating"
onrowdatabound="gvProducts_RowDataBound">
We are not going to allow user to edit ProductID & Product Number, so we use BoundColumns to display them.
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="Product ID"
                  ReadOnly="true">
    </asp:BoundField>
<asp:BoundField DataField="ProductNumber" HeaderText="Product Number"
                    ReadOnly="true">
</asp:BoundField>    
……………
…………..
User is allowed to update Product Name, Product Number, Price and the sub category mapping. When the grid is in view mode, we wrap these attributes in ITEM TEMPLATE.  When user grid is in edit mode, user can actually change the product name & its price, so we render those two items in text fields However he cannot change the sub category name, he can only choose a sub category from the existing list meaning he can change the mapping. We load sub categories in a drop down list and user can select an item from it.
….
……………….
<asp:TemplateField headertext="Product Name">
    <HeaderStyle HorizontalAlign="Left" Width="200px" />
    <ItemStyle HorizontalAlign="Left" Width="200px"/>
    <ItemTemplate> <%#Eval("ProductName")%></ItemTemplate>
    <EditItemTemplate>
      <asp:TextBox id="txtProductName" text='<%#Eval("ProductName")%>'
        runat="server"/>                                            
    </EditItemTemplate>                   
</asp:TemplateField>    
<asp:TemplateField headertext="Sub Category">
    <HeaderStyle HorizontalAlign="Left" Width="150px" />
    <ItemStyle HorizontalAlign="Left" />
    <ItemTemplate> <%#Eval("SubCategoryName")%></ItemTemplate>
    <EditItemTemplate>
     <asp:DropDownList ID="ddlSubCategories" runat="server" >               
        </asp:DropDownList>                               
    </EditItemTemplate>                   
</asp:TemplateField>    
 <asp:TemplateField headertext="Price">
    <HeaderStyle HorizontalAlign="Right" Width="80" />
    <ItemStyle HorizontalAlign="Right" Width="80" />
     <ItemTemplate> <%#Eval("ListPrice","{0:c}")%></ItemTemplate>
     <EditItemTemplate>
      <asp:TextBox id="txtListPrice" text='<%#Eval("ListPrice")%>'
             Width="80" runat="server"/>                                                                        
    </EditItemTemplate>                  
</asp:TemplateField>      
</Columns>
User has to click on “Edit” button to enter into edit mode. While in edit mode, he can choose to perform two actions. He can change product attributes and click on “Update” to persist his changes to database or he can click on “Cancel” to go back to normal mode.
<asp:TemplateField>
<ItemTemplate>
   <asp:LinkButton ID="btnedit" runat="server" CommandName="Edit"
                  Text="Edit"/>       
</ItemTemplate>
<EditItemTemplate>
   <asp:LinkButton ID="btnupdate" runat="server"
                        CommandName="Update" Text="Update" />
   <asp:LinkButton ID="btncancel" runat="server"
                CommandName="Cancel" Text="Cancel"/>       
</EditItemTemplate>             
</asp:TemplateField>     
</asp:gridview>
Implementation:
When page is first requested, Page_Load event is one of the events that get fired on the server side. If the load is not because of any web control event, we fetch products from database and will save it in the Viewstate for subsequent page refreshes.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        BindData();
}
private void BindData()
{
    //Bind the grid view
    gvProducts.DataSource = RetrieveProducts();
    gvProducts.DataBind();
}
private DataSet RetrieveProducts()
{
    if (ViewState["Products"] != null)
        return (DataSet)ViewState["Products"];
    //fetch the connection string from web.config
    string connString =
      ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;
    //SQL statement to fetch entries from products
    string sql = @"Select top 10  P.ProductID, P.Name as ProductName,
                    P.ProductNumber, ListPrice, PS.ProductSubCategoryID,
                    ps.Name as SubCategoryName 
                    from Production.Product P
                    INNER JOIN Production.ProductSubcategory PS
                    ON P.ProductSubcategoryID = PS.ProductSubcategoryID";
    DataSet dsProducts = new DataSet();
    //Open SQL Connection
    using (SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();
        //Initialize command object
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            //Fill the result set
            adapter.Fill(dsProducts);
        }
    }
    ViewState["Products"] = dsProducts;
    return dsProducts;
}

When user clicks on “Edit” button, OnRowEditing event is raised and gvProducts_RowEditing event handler routine is called. In this routine, we set the edit index of the grid to the row you trying to edit. Since it is a post back, we have to re-bind the grid control.  Whenever we try to bind data to the grid RowDataBound fires once for each row as its databound. If you want to handle any data binding related special cases, you do it here. We load subcategories into a dropdownlist. We get the list of available sub categories from Production.ProductSubcategory and will bind it to drop down list.
protected void gvProducts_RowEditing(object sender,
                                        GridViewEditEventArgs e)
{
    gvProducts.EditIndex = e.NewEditIndex;
    BindData();
}
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //check if is in edit mode
        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
            DropDownList ddlSubCategories =
                      (DropDownList)e.Row.FindControl("ddlSubCategories");
            //Bind subcategories data to dropdownlist
            ddlSubCategories.DataTextField = "SubCategoryName";
            ddlSubCategories.DataValueField = "ProductSubcategoryID";
            ddlSubCategories.DataSource = RetrieveSubCategories();                   
            ddlSubCategories.DataBind();
            DataRowView dr = e.Row.DataItem as DataRowView;
            ddlSubCategories.SelectedValue =
                         dr["ProductSubCategoryID"].ToString();
        }
    }
}
private DataTable RetrieveSubCategories()
{
   //fetch the connection string from web.config
    string connString =
            ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;
    //SQL statement to fetch entries from products
    string sql = @"Select ProductSubcategoryID, Name as SubCategoryName
                from Production.ProductSubcategory";
    DataTable dtSubCategories = new DataTable();
    //Open SQL Connection
    using (SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();
        //Initialize command object
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            //Fill the result set
            adapter.Fill(dtSubCategories);
        }
    }
    return dtSubCategories;
}

Change sub category to “Chains” & price to $50. Click on “Update” link button and gvProducts_RowUpdating event is called. We get the values entered/changed by the user and will persist them into database.
protected void gvProducts_RowUpdating(Object sender,
                                        GridViewUpdateEventArgs e)
{
    // Get the product id of the selected product   
    string productID = gvProducts.DataKeys[e.RowIndex].Value.ToString();
    // Get the GridViewRow object that represents the row being edited
    // from the Rows collection of the GridView control.           
    GridViewRow row = gvProducts.Rows[e.RowIndex];
    // Get the controls that contain the updated values. In this
    // example, the updated values are contained in the TextBox
    // controls declared in the edit item templates of each TemplateField
    // column fields in the GridView control.
    TextBox txtProductNumber = (TextBox)row.FindControl("txtProductNumber");
    TextBox txtProductName = (TextBox)row.FindControl("txtProductName");
    DropDownList ddlSubCategories =
                      (DropDownList)row.FindControl("ddlSubCategories");
    TextBox txtListPrice = (TextBox)row.FindControl("txtListPrice");
    //update the product
    UpdateProduct(productID, txtProductName.Text,
                                ddlSubCategories.SelectedValue,
                                txtListPrice.Text);
    gvProducts.EditIndex = -1;
    ViewState["Products"] = null;
    BindData();
}
Private void UpdateProduct(string productID,
                string productName, string subCategoryID, string listPrice)
{
//fetch the connection string from web.config
string connString =
       ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;
//SQL statement to update a product
string sql = String.Format(@"Update Production.Product set Name='{0}'                                   
                        ,ProductSubcategoryID={1}
                        ,ListPrice ={2}
                        where ProductID = {3}",
                                productName,
                                subCategoryID,
                                listPrice, productID);
using (SqlConnection conn = new SqlConnection(connString))
{
    conn.Open();
    //Initialize command object
    using (SqlCommand cmd = new SqlCommand(sql, conn))
    {
        cmd.ExecuteNonQuery();
    }
}

 

Source: technico.qnownow.com