'method'에 해당되는 글 1건

  1. 2009.04.30 DataTable DataSet DataView Method
2009. 4. 30. 19:31

DataTable DataSet DataView Method


DataSet 으로 가져온 데이터를 기반으로 추가로 데이터를 가공할 경우가 필요해서 정리함.

http://www.codeguru.com/forum/showthread.php?t=332574

    DataSet ds = RepeaterProductInfo.DataSource as DataSet;
    DataRow [] row = ds.Tables[0].Select("Sum(ItemPrice)");
    strReturnValue = row[0][0].ToString();
    DataSet ds = RepeaterProductInfo.DataSource as DataSet;
    DataRow [] row = ds.Tables[0].Select("ItemPrice = Sum(ItemPrice)");
    strReturnValue = row[0][0].ToString();

DataTable.Compute Method
private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable.
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}


Repeater Control and Data Binding - ASP .Net and C#

Introduction:

 Data Binding is the process of creating a link between the data source and the presentation UI to display the data. ASP .Net provides rich and wide variety of controls which can be bound to the data. This model of binding data with the data source reduces a lot of code complexity and increases the ease of maintenance of code. This article looks at how to use this data binding feature for a Repeater control in ASP .Net with C# code.

Repeater Control in ASP .Net:

   A Repeater control is a light weight control which can be used for simple reporting purposes. It supports basic event-handling like Init, Load, Unload etc., This also supports some basic formatting of data and can be presented to the user. A Repeater control offers limited level of data editing or selecting capabilities. For such editing and updates ASP .Net offers DataList and DataGrid controls.

   A Repeater control can be used to build small and Flexible reports with the templates for the items. It supports the following five templates.

  • HeaderTemplate : Can be used to create the Header Rows of the Table data being presented by Repeater control.
  • FooterTemplate : Can be used to create the Footer Rows of the Table data being presented by Repeater control.
  • ItemTemplate : Used for formatting the Items and rows to be displayed.
  • AlternatingItemTemplate : Alternating items formatting.
  • SeparatorTemplate : Styles for separating rows and columns.

   There are many ways in which a control in ASP .Net can be formatted. It is up to the imagination of the programmer to come up with nice formats. For example the Footer rows can be manipulated in such a way that, it can show the summary values or totals etc.,

Repeater Syntax:

<asp:Repeater id="idrepeater" runat="server" Datasource="<%# dataset %>" DataMember="table-inside-dataset">
<HeaderTemplate>..Header Format ..</HeaderTemplate>
<ItemTemplate> .. Item formats .. </ItemTemplate> 
</asp:Repeater>

    As given above, the syntax is simply the Repeater tag with the Template types. These templates can be formatted with ItemStyle tags also.

Using DataBinder.Eval method:

   The System.Web.UI.DataBinder class provides a useful static method DataBinder.Eval, which can be used to evaluate the data at run time using late binding. This function can be used with the Visual Studio IDE or can be manually coded as

 

<%#  DataBinder.Eval(Container.DataItem,"FieldName","Format") %>

   This evaluates and returns the data at run time. This can be used with Repeater, DataList and DataGrid controls though there will be a performance penalty because of the late binding mechanism used.

Creating a Sample Program with Repeater Control:

   Let's create a small sample program with the Repeater control. 

  1. Add a new Webform in an Visual Studio  Asp .net application.
  2. Add a Repeater control to the application. Let us assume that the id of the control is Repeater1.
  3. Insert the following lines of formatting code in between the opening and closing tags of the <asp:Repeater> control.
  4. <HeaderTemplate>
    <table cellpadding="5" cellspacing="2" >
    <tr bgcolor=Gray>
    <td><b>CustomerName</b></td>
    <td><b>Country</b></td>
    </tr>
    </HeaderTemplate>
    <ItemTemplate>
    <tr>
    <td><%# DataBinder.Eval(Container.DataItem,"CustomerName") %></td>
    <td><%# DataBinder.Eval(Container.DataItem,"Country") %></td>
    </tr>
    </ItemTemplate>
    <AlternatingItemTemplate>
    <tr bgcolor="#ccccff">
    <td><%# DataBinder.Eval(Container.DataItem,"CustomerName") %></td>
    <td><%# DataBinder.Eval(Container.DataItem,"Country") %></td>
    </tr>
    </AlternatingItemTemplate>
    <FooterTemplate>
    </table>
    </FooterTemplate>
  5. The above code just adds the repeater control with formatting for the header rows, data rows and the footer rows. The HeaderTemplate starts the <table> tag with the table heading and the FooterTemplate closes it.
  6. Now, Add the following code inside the Webform1.aspx.cs, Page_Load event.
    DataSet ds = new DataSet();
    DataTable dt = ds.Tables.Add("Customer");
    dt.Columns.Add("CustomerName",Type.GetType("System.String"));
    dt.Columns.Add("Country",Type.GetType("System.String"));

    DataRow dr = dt.NewRow();
    dr[0]="Testcustomer1";
    dr[1]="USA";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0]="Testcustomer2";
    dr[1]="UK";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0]="Testcustomer3";
    dr[1]="GERMANY";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr[0]="Testcustomer4";
    dr[1]="FRANCE";
    dt.Rows.Add(dr);

    //Bind the data to the Repeater
    Repeater1.DataSource = ds;
    Repeater1.DataMember = "Customer";
    Repeater1.DataBind();
  7. The above code creates a dataset to be used with the Repeater control. The repeater's datasource is the Dataset created and the Data member is mentioned as the Table which is created along with the dataset. This enables the Repeater to create the list of items from this customer table.
  8. Now build the application in Visual Studio .Net and load this page. The data will be shown in a tabular format.

   The above sample shows data binding from a statically created data set only. This can be very easily extended to a DataSet generated from database tables, xml files or even DataView s.

   Ultimately, this Repeater control can be used for light weight and simple report generation. This has only a very simple level event handling capabilities. Also there is a performance penalty because of using the DataBinder.Eval methods, this can be considered for data which are not modified frequently. If it is a large amount of data, then caching may be considered to improve the performance, though there are some other factors may have to be considered and not discussed here.

Attachments:

  Project Files : RepeaterSample.zip


Repeater Class


리피터 컨트롤 (Repeater Contorl) 사용시 빈 데이터 핸들링

강력하고 우아한 리피터 컨트롤을 가지고 빈데이터가 왔을경우 어떻게 표시할 수 있는지 그 처리를 위한 기본 메커니즘을 알아봅시다. 예를 들어 다른 컨트롤인 그리드 뷰 같은 경우, 바인드 되는 데이터가 비어있을 경우를 대비해서 그에 관한 속성을 지원합니다. (EmptyDataTemplate)
그렇지만 리피터 컨트롤에는 그와 같은 속성을 지원하지 않습니다. 다만, 리피터 컨트롤의 고유한 유연성으로 이 기능을 추가 시키기 쉽게 되어있습니다. 그럼 데이터가 비었을때 그와 관련된 메시지를 어떻게 나타내주는지 알아보도록 하겠습니다.

아래 예제는 리피터 컨트롤을 사용하여 테이블을 만들어 내는 코드 입니다.

<asp:Repeater runat="server" ID="Repeater1">
    <HeaderTemplate>
        <table width="80%">
    </HeaderTemplate>
    
    <ItemTemplate>
        <tr>
            <td><asp:Label runat="server" Text='<%# Eval("Model") %>' /></td>
        </tr>
    </ItemTemplate>
    
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>
 
if (!IsPostBack)
{
    List<Car> cars = new List<Car>();

    Repeater1.DataSource = cars;
    Repeater1.DataBind();
}

만약 위 코드에서 바인딩한 cars 에 빈값이 들어있다면 위 ItemTemplate는 사용되지 않고 리피터 컨트롤은 빈값을 나타내게 됩니다.  아래 코드는 그 결과입니다. Header와 Footer Template만 랜더링 되어있습니다.

<table width="80%">
            
</table>

위에서 보았듣이 Header나 Footer의 경우 데이터의 유/무와 상관없이 랜더링이 됩니다. 이를 이용하여 데이터를 기반으로 하여 빈 데이터시에 그 내용을 나타내 줄 수 있습니다.

아래 코드를 살펴 보겠습니다.

<table width="80%">
    <tr runat="server" 
        visible='<%# ((ICollection)Repeater1.DataSource).Count == 0 ? true : false %>'>
        <td>
            There is no data to display
        </td>
    </tr>

There are a couple of items that should be noted in the above example.

  • The Repeater has been referenced by it's  ID.
  • The DataSource property of the Repeater has been cast to an ICollection object. DataSource is defined as type object, but when data is bound to it, it must be of type ICollection. We are using the Count property from this interface to determine if the "Empty Data" message should display.

When there are several controls where the Visible property needs to be set, the logic can be moved to the code-behind for the page. This is shown in the following IsDataEmpty property.

protected bool IsDataEmpty
{
    get
    {
        ICollection list = Repeater1.DataSource as ICollection;

        return list.Count == 0 ? true : false;
    }
}

The ASPX will change to reference this property as follows:

<table width="80%">
    <tr runat="server" 
        visible='<%# IsDataEmpty %>'>
        <td>
            There is no data to display
        </td>
    </tr>

Regardless of which approach you use, the resulting HTML will now look like:

<table width="80%">
    <tr>
        <td>
            There is no data to display
        </td>
    </tr>   
</table>

As shown in the above examples, it is fairly simple to add HTML that will conditionally render based on the presence (or lack) of data bound to a Repeater.

출처 : http://devcenter.auburnrandall.com/Default.aspx?c=Tech&type=post&id=72


C# DataTable Group by Example

http://programming.top54u.com/post/C-sharp-DataTable-Group-by-Example.aspx

DataTable tbl1 = dset.Tables[0];

DataTable tbl2 = dset.Tables[1];

GridView1.DataSource = tbl2;
GridView1.DataBind();


int counter = 0;

// for each loop to group the records by categoryid
foreach (DataRow dr in tbl2.Rows)
{
    DataView dv = tbl1.DefaultView;
    dv.RowFilter = "categoryid=" + dr["categoryid"];

    GridView grd = (GridView)GridView1.Rows[counter].Cells[0].FindControl("GridView2");

    grd.DataSource = tbl1;
    grd.DataBind();

    counter++;
}