천객만래 [千客萬來] (It has an interminable succession of visitors)

Creating GridView Columns Dynamically (Part 1)





http://www.dotnetbips.com/articles/56fadcb9-ee8b-4170-a6ad-cd4f38222bcb.aspx

Creating GridView Columns Dynamically (Part 1)

Introduction

Many months back I wrote three articles - Creating DataGrid ProgrammaticallyCreating DataGrid Templated Columns Dynamically - Part I and Creating DataGrid Templated Columns Dynamically - Part II. Even today these are amongst top viewed articles. This indicates how commonly developers need to create grid controls dynamically. Beginning with this article I am starting a series that will show you how to create data bound controls such as GridView and DetailsView programmatically. To begin with Part 1 shows how to add bound fields and command fields to a GridView. The GridView thus created is fully functional with paging, sorting and editing features.

Creating a sample web site

To begin with create new web site in Visual Studio. Drag and drop a GridView control and an SqlDataSource control on the default web form. Do not set any property of either controls at design time. We will be doing that via code.

Now key in the following code in the Page_Load event handler.

protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.ConnectionString = 
@"data source=.;initial catalog=northwind;integrated security=true";
SqlDataSource1.SelectCommand = 
"select employeeID,FirstName,LastName from employees";
SqlDataSource1.UpdateCommand = 
"update employees set firstname=@FirstName,lastname=@LastName 
where employeeid=@EmployeeID";
SqlDataSource1.UpdateParameters.Add("@FirstName", "");
SqlDataSource1.UpdateParameters.Add("@LastName", "");
SqlDataSource1.UpdateParameters.Add("@EmployeeID", "");

if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.AutoGenerateColumns = false;
GridView1.DataKeyNames = new string[] { "EmployeeID" };
GridView1.AllowPaging = true;
GridView1.AllowSorting = true;
GridView1.PageSize = 5;

BoundField bf1 = new BoundField();
BoundField bf2 = new BoundField();
BoundField bf3 = new BoundField();

bf1.HeaderText = "Employee ID";
bf1.DataField = "EmployeeID";
bf1.ReadOnly = true;
bf1.SortExpression = "EmployeeID";

bf2.HeaderText = "First Name";
bf2.DataField = "FirstName";
bf2.SortExpression = "FirstName";

bf3.HeaderText = "Last Name";
bf3.DataField = "LastName";
bf3.SortExpression = "LastName";

CommandField cf = new CommandField();
cf.ButtonType = ButtonType.Button;
cf.ShowCancelButton = true;
cf.ShowEditButton = true;

GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(cf);
}
}

The code is dissected in the following sections

Configuring the SQL data source control

The code sets the ConnectionString property SQL data source control to required database connection string. In our example we will be using Employees table of Northwind database. Then SelectCommand and UpdateCommand properties are set to corresponding SELECT and UPDATE queries. The UPDATE query is important. Note that the names of the parameters specified in UPDATE statement are matching the table column names. The UPDATE statement contains three parameters - @FirstName, @LastName and @EmployeeID. These parameters are then added to the UpdateParameters collection.

Configuring the GridView control

The GridView control uses SqlDataSource1 as its data source. This is indicated by setting the DataSourceID property of GridView. Further some properties of GridView are set. Note that you need to set these properties only once and hence they come inside the "if" condition. The AutoGenerateColumns property indicates whether to generate GridView columns automatically. We set this property to false as we wish to add them via code. The DataKeyNames property is a string array specifying the primary key columns. The AllowPagng and AllowSorting properties enable paging and sorting feature respectively. The PageSize property sets the page size to 5.

Creating Bound Fields

The GridView control can contain many types of columns such as BoundField, HyperLinkField and TemplateField. In this example we will be using BoundField columns. We need three bound fields for EmployeeID, FirstName and LastName respectively. A bound field is represented by a class called BoundField. The HeaderText property of BoundField class indicates the column heading. The DataField property indicates the name of the table column that you wish to display in the bound field. The SortExpression property governs if that bound field will be sortable or not. If you set the SortExpression property to a column name then the bound field will be sortable based on that column. Since EmployeeID bound field represents primary key we set its ReadOnly property to true. This way it won't be editable.

In order to provide editing feature you need to add a CommandField column to the GridView. The ButtonType property of CommandField class indicates the type of button to render. Possible values are Button, LinkButton and ImageButton. The ShowCancelButton and ShowEditButton properties decide if the Edit and Cancel buttons will be displayed.

Once we create the columns they need to be added to the Columns collection of GridView.

That's it! If you run the web form then it should look as shown below:



You can now test GridView features such as paging sorting and editing.






Posted by SB패밀리

ItemIndex 속성을 사용하여 DataGrid, DataList, Repeater 컨트롤의 Items 컬렉션에서 가져온 DataGridItem, DataListItem, Repeateritem 개체의 인덱스 번호를 확인합니다.

<asp:Repeater id="Repeater1" runat="server">
    <ItemTemplate>
            <td><%# Container.ItemIndex+1 %> </td>

    </ItemTemplate>
</asp:Repeater>

 

위에서 1을 더해주는 이유는 ItemIndex0부터 시작하기 때문에 1부터 표시해주기 위해서 이다.

쌈꼬쪼려 소백촌닭

Posted by SB패밀리

현재 페이지에 표시된 DataGrid의 내용을 버튼클릭시 다운로드 하는 소스입니다.
필요해서 한번 해봤는데 되네요..

 

DataListRepeater 등 모든 서버컨트롤이나 HTML컨트롤에도 사용 가능합니다! *^^*

 

private void Button1_Click(object sender, System.EventArgs e)
{   
    System.Web.HttpContext.Current.Response.Buffer = true;
    System.Web.HttpContext.Current.Response.AddHeader
        ("Content-Disposition", "attachment;filename=20050614.xls");
   System.Web.HttpContext.Current.Response.ContentType="application/unknown";

 

    // 이부분은 web.config의 <globalization requestEncoding="utf-8"   
    // responseEncoding="utf-8" /> 인코딩 부분과 같도록 맞춰주시면 됩니다.
   

    // 2005.09.26 추가 : 인코딩 문자열을 자동으로 맞추려면

    // Request.ContentEncoding.HeaderName 로 인코딩 문자열을 받아서 사용한다.

    System.Web.HttpContext.Current.Response.Write       
        ("<meta http-equiv=Content-Type content='text/html; charset=utf-8'>");

 

    System.IO.StringWriter sWriter = new System.IO.StringWriter();   
    System.Web.UI.HtmlTextWriter htmlWriter
           = new System.Web.UI.HtmlTextWriter(sWriter);


    DataGrid1.RenderControl(htmlWriter);   


    System.Web.HttpContext.Current.Response.Write(sWriter.ToString());   
    System.Web.HttpContext.Current.Response.End();
}

참조 : http://blog.naver.com/tear230/100013986512

DataGrid를 이용할줄 안다면 GridView도 응용해서 이용할수 있습니다.
Posted by SB패밀리

Introduction

There are many articles and tutorials around that illustrate the use of GridView control along with the new Data Source Controls. When attached with a Data Source control GridView performs tasks such as paging, sorting and editing automatically i.e. without writing any code. However, at times you require to bind the GridView with a DataView or DataTable directly. Fortunately GridView can also be used without attaching with the Data Source Controls. This calls for some extra coding from developer's end. If you are familiar with DataGrid control of ASP.NET 1.x then you will find the coding similar. In this article we will see how paging, sorting and editing can be implemented in a GridView control that is bound with a DataView (or DataTable) directly.

Example - Employee listing

As an example we are going to use Employees table of the Northwind database. In order to develop a test web form create a new web site in VS.NET 2005. Drag and drop a GridView control on the web form. Add three BoundFields and a CommandField to the GridView with the help of Fields dialog (see below).

Set various properties of the BoundFields as shown in the following table:

BoundField HeaderText DataField ReadOnly
Employee ID Employee ID EmployeeID true
First Name First Name FirstName false
Last Name Last Name LastName false

Go in the code behind of the web form and add the following code in the Page_Load event:

protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}

Here, we call BindGrid() method if the web form is being served as a result of first request. The BindGrid() method is our own function that we will create later on. The method essentially binds the GridView with a DataView. The DataView supplies all the records from the Employees table.

Implementing Paging

In order to implement paging you need to set AllowPaging property of the GridView control to True. Then set PageSize property to 3. There are two events of GridView that are related to paging. They are:

  • PageIndexChanging
  • PageIndexChanged

The former event is raised before the current page changes and the later is raised after the page has changed. The former allows you to cancel the operation.

Write the following code in the PageIndexChanging event of the GridView.

protected void GridView1_PageIndexChanging
(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}

The PageIndexChanging event handler receives an event argument of type GridViewPageEventArgs. This argument provides the new page number that the user has selected via a property called NewPageIndex. We set PageIndex property of the GridView to this new page number and call the BindGrid() method again. This will display the corresponding records in the GridView. The following figure shows the GridView after implementing paging.

Implement Sorting

Implementing sorting requires a bit of more work. First of all, you need to set AllowSorting property of the GridView to True. Further, you need to set SortExpression property of the BoundFields to the name of the column on which you would like to sort the grid. Once you set these properties you will find that the column headers of all the columns for  which you specified SortExpression property appear as clickable link buttons. Clicking on the link buttons raise two events:

  • Sorting
  • Sorted

Just like paging events these events follow pre and post pattern. The Sorting event allows you to cancel the operation also.

The Sorting event handler receives an event argument of type GridViewSortEventArgs. The GridViewSortEventArgs class has three important properties. The SortExpression property supplies the sort expression that you specified earlier for the column being sorted. The SortDirection property specifies the direction of sorting i.e. ascending or descending. This property is not of much when you are sorting the grid on your own. However, when coupled with data source controls the GridView can toggle the sorting direction automatically for you and you can get/set the direction using this property. The Cancel property allows you to cancel the sorting operation.

Since we are not using data source controls we need to handle the toggling of the sort direction on our own. We do this by storing a ViewState variable. Add the following code in the Sorting event handler.

protected void GridView1_Sorting(object sender, 
GridViewSortEventArgs e)
{
ViewState["sortexpression"] = e.SortExpression;

if (ViewState["sortdirection"] == null)
{
ViewState["sortdirection"] = "asc";
}
else
{
if (ViewState["sortdirection"].ToString() == "asc")
{
ViewState["sortdirection"] = "desc";
}
else
{
ViewState["sortdirection"] = "asc";
}
}
BindGrid();
}

Here, we store the value of SortExpression property into a VeiwState variable called sortexpression. We need to access this variable from BindGrid() method so that our sorting will work correctly under all the circumstances. Similarly we set a ViewState variable called sortdirection. This variable stores the direction of sorting i.e. asc or desc. Note how we are toggling the direction. Finally, we call BindGrid() method which will bind sorted version of the DataView with the grid.

The following figure shows the GridView after implementing sorting.

Implement Editing

In order to edit records displayed in the GridView, we need to add a CommandField to the GridView. By default this field renders a link button titled Edit. Once we click on edit the GridView raises an event called RowEditing and the Edit link button changes to Update and Cancel link buttons. Clicking on Update link button raises RowUpdating event whereas clicking on the Cancel link button raises RowCancelingEdit event. We need to write our own code to update the new values back to the database in the RowUpdating event.

Add the following code in the RowEditing event handler:

protected void GridView1_RowEditing
(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}

The RowEditing event handler receives an event argument of type GridViewEditEventArgs. The GridViewEditEventArgs class has a property called NewEditIndex that tells us the row number being edited. We need to set the EditIndex property of the GridView to this new edit index. This will cause the GridView to enter in edit mode (see below).

Note that the EmployeeID column is not editable because we have marked it as ReadOnly.

Now add the following code in the RowCancelingEdit event handler.

protected void GridView1_RowCancelingEdit
(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}

Here, we set the EditIndex property of GridView to -1 indicating that we intend to cancel the edit operation.

Finally, we will write code for handling the RowUpdating event.

protected void GridView1_RowUpdating
(object sender, GridViewUpdateEventArgs e)
{
int empid;
string fname, lname;
empid = int.Parse(GridView1.Rows[e.RowIndex].
Cells[0].Text);
fname = ((TextBox)GridView1.Rows[e.RowIndex].
Cells[1].Controls[0]).Text;
lname = ((TextBox)GridView1.Rows[e.RowIndex].
Cells[2].Controls[0]).Text;

SqlConnection cnn = new SqlConnection(@"data source=
.\sqlexpress;initial catalog=northwind;integrated 
security=true");
cnn.Open();
SqlCommand cmd = new SqlCommand("update employees set 
firstname=@fname,lastname=@lname where employeeid=@empid",
 cnn);
cmd.Parameters.Add(new SqlParameter("@fname",fname));
cmd.Parameters.Add(new SqlParameter("@lname", lname));
cmd.Parameters.Add(new SqlParameter("@empid", empid));
cmd.ExecuteNonQuery();
cnn.Close();

GridView1.EditIndex = -1;
BindGrid();
}

Here, we first retrieve the new values entered in the textboxes. The RowUpdating event handler receives an event argument of type GridViewUpdateEventArgs. The GridViewUpdateEventArgs class has a property called RowIndex that tells us the row number being updated. We retrieve the new values using the Rows collection of the GridView. Note how the Cells and Controls collections are used. The Cells collection contains all the columns of the current row whereas Controls collection contains all the controls from a specific column. The Controls collection stores all the controls as generic Control type. Hence we need to type cast the controls to TextBox class. Then we create a connection, command and parameters and execute an UPDATE query against the database. Once the updating operation is over we set EditIndex property of the GridView to -1 and bind the grid again.

The BindGrid() method

Throughout our code we have used a method called BindGrid(). It's time to unveil the BindGrid() method now.

private void BindGrid()
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter
("select * from employees", @"data source=
.\sqlexpress;initial catalog=northwind;
integrated security=true");
da.Fill(ds,"employees");
DataView dv = ds.Tables[0].DefaultView;

if (ViewState["sortexpression"] != null)
{
dv.Sort = ViewState["sortexpression"].ToString() 
+ " " + ViewState["sortdirection"].ToString();
}

GridView1.DataSource=dv;
GridView1.DataBind();
}

Here, we fill a DataSet with all the records from Employees table. Then we create a DataView based on the employees DataTable. Then we sort the DataView using the Sort property. The column on which we wish to sort the DataView is obtained from the  sortexpression ViewState variable. While sorting we also make use of sortdirection ViewState variable. Recollect that we set these two ViewState variables in the Sorting event handler. Finally, we set the DataSource property of the GridView to the DataView and then call its DataBind() method.

Summary

GridView can be bound with a DataView (or DataTable) directly without using data source controls. We can implement the same paging, sorting and editing features. However, we need to handle various events ourselves and do some extra work so that all the features work as expected.

 
 
Related Articles
Persistant and Bidirectional Sorting In DataGrid
Downloadable DataGrid samples for beginners
Downloadable DataList samples for beginners
Creating DataGrid Programmatically
Building a Master/Detail DataGrid for Database Inserts
Recalculating Column Values in DataGrid
HOW TO: Display DataGrid in small screen area without using Paging
Creating DataGrid Templated Columns Dynamically - Part I
Creating DataGrid Templated Columns Dynamically - Part II
Displaying Two DataTables In One DatGrid
Displaying Images from SQL Server database in DataGrid
Display Conditional Data In DataGrid Column
Confirming Deletes in ASP.NET DataGrid
Adding Paging Functionality To DataList
Alphabetical Paging in DataGrid
Quickly Adding A New Row In DataGrid
Custom Paging In DataGrid
Sorting Template Columns of ASP.NET DataGrid
Using Radio Buttons To Select DataGrid Row
Creating Master-Detail Listings using ASP.NET controls
Creating GridView Columns Dynamically (Part 1)

Creating GridView Columns Dynamically (Part 2)



출처: http://www.dotnetbips.com/default.aspx

Posted by SB패밀리

GridView에서 DataFormatString 을 적용했는데... 반영이 안되는 문제가 발생한다.
이런 경우 HtmlEncode 의 속성값(default: true)을 False로 해주면 해결된다. 

예를 들면...


<간단하게 GridView로 데이터를 표시... DataFormatString 적용전 화면>



<DataFormatString 적용 후 화면>

두 그림을 보면 달라진 점은 ModifiedDate 필드에 날짜 형식이 바뀐것을 확인 할 수 있다.

DateTime type인 ModifiedDate에 DataFormatString을 적용했다.
아래 소스 10줄에 굵은 부분을 확인...
 

    1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="AddressID" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" PageSize="5">

    2   <Columns>

    3      <asp:BoundField DataField="AddressID" HeaderText="AddressID" InsertVisible="False" ReadOnly="True" SortExpression="AddressID" />

    4      <asp:BoundField DataField="AddressLine1" HeaderText="AddressLine1" SortExpression="AddressLine1" />

    5      <asp:BoundField DataField="AddressLine2" HeaderText="AddressLine2" SortExpression="AddressLine2" />

    6      <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />

    7      <asp:BoundField DataField="StateProvinceID" HeaderText="StateProvinceID" SortExpression="StateProvinceID" />

    8      <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />

   9       <asp:BoundField DataField="rowguid" HeaderText="rowguid" SortExpression="rowguid" />

   10     <asp:BoundField DataField="ModifiedDate" HeaderText="ModifiedDate" SortExpression="ModifiedDate" DataFormatString="{0:d}" HtmlEncode="false" />

   11  </Columns>

   12 </asp:GridView>

Posted by SB패밀리

GridView에 스크롤기능을 넣기위해 Div 태그를 사용했다.

문제가 Div 태그의 Width 값을 100% 로 주었을경우 Div내에 있는 GridView의 Width값에 따라 늘어나는 것이었다.

GridView의 Width값과 상관없이 모니터의 해상도에 맞게 Div 태그의 Width값을 설정해주기 위한 방법입니다.

 

1. Div 태그내에 width=2000 인 GridView 추가

   <div name="SAMPLE_DIV" id="SAMPLE_DIV">

   <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowHeader="False" width="2000" >

   .. 생략

   </asp:GridView>

   </div>

 

2. 태그 마지막 부분에 Div 태그의 Width값을 설정해주는 script function 추가

 .. 상위소스 생략

 </form>
 </body>
 <script language=javascript>setDivAutoSize();</script>
</html>

3. Div 태그 Width값 설정 script function 추가

<script language=javascript>

// DIV Auto Size 설정

function setDivAutoSize()

{
        var obj = document.getElementById("SAMPLE_DIV");
        var screenX = screen.Width;
        var screenH = screen.Height;
        obj.style.width = screenX-90;
        obj.style.height = screenH-200;//Top 메뉴 Height값 200 빼주기;
        obj.style.overflow = "scroll";

}

</script>

 

4. 완료.

 

이렇게하면 Div내에 위치한 GridView의 Width값에 상관없이 해상도에 맞게 Div태그의 Width값을 설정해줄수 있습니다.

Posted by SB패밀리