반응형
DB에 저장된 데이터를 이용하여 Wizard Control 내에 위치한 DropDownList의 데이터를 Binding하는데 문제가 있었다.

Step1의 있는 DDL의 데이터는 정상적으로 Binding을 하는데 Step2의 있는 녀석들은 --- Select --- 라는 Default 값만

내내 표시하고 있었다.

XMLDataSource를 통해서 Item들을 가져오면서 어디선까 꼬인 것 같았다.

- ASPX
<asp:DropDownList ID="ddlState" runat="server"  DataSourceID="XmlDataSource1" DataTextField="Text" DataValueField="Value" AppendDataBoundItems="true">
         <asp:ListItem Value="">Select</asp:ListItem>
</asp:DropDownList>

- CS
ddlState.SelectedValue = dr["State"].ToString();

뭐냐 너는..ㅡㅡ;;;

답은 간단했다..

- CS
ddlState.DataBind();
ddlState.SelectedValue = dr["State"].ToString();


아무래도 ddlState Item들이 반영되기 전에 DropDownList의 값을 Binding시키는 것 같다.

그러니 Binding 후 세팅되는 값이 없으니 Default값을 계속 나타냈던 것이였다..ㅠㅠ

사실 다른 프로젝트에 내가 작업 했던 부분에서 찾은 것이다ㅋㅋ 이제는 어디다 적어놓지 않으면

기억이 나지 않네. 큰일이다 정말.크~~~~

오메가 3를 먹자!!!
반응형
반응형

This is another walkthrough, like my last post, demonstrating how to use some new Visual Studio 2010 features available in the October VS2010 CTP. It provides steps to follow in the CTP build; however, you may find that you are able to give feedback on the descriptions below without actually downloading and executing the steps yourself. Please leave your feedback on this feature set at the end of this post, or at the following forum:

http://social.msdn.microsoft.com/Forums/en-US/vs2010ctpvbcs/thread/6172efc9-3075-4426-a773-cf2504f51dca

Thanks!
Lisa

Walkthrough: Office Programmability in Visual Basic and C#

This walkthrough demonstrates several new features in Visual Basic and C#. This walkthrough focuses on how the new features, when used in conjunction, can greatly simplify Office development, although most of these new features are useful in other contexts.

In this walkthrough, you will create a class that represents a bank account. You will then create collections of objects of that class. Next, you will create an Office Excel worksheet, populate it with data from a collection, and embed the worksheet into an Office Word document. Finally, you will modify the build process so that end users can run your program without having the Office primary interop assembly (PIA) installed on their computers.

This walkthrough demonstrates the following new language features:

New features in Visual Basic:

  • Auto-implemented properties
  • Statement lambdas
  • Collection initializers
  • Implicit line continuation

New features in Visual C#:

  • Optional and named parameters
  • Optional ref parameter modifier
  • Dynamic dispatch on COM calls returning Object

New feature in both languages:

  • No-PIA deployment

Prerequisites: You must have Excel 2007 and Word 2007 installed on your computer to complete this walkthrough.

To create a new console application

1. On the File menu, point to New and then click Project. In the New Project dialog box, in the Project types pane, expand Visual Basic or Visual C#, and then click Windows. In the upper right-hand corner, make sure that .NET Framework 4.0 is selected. Then click Console Application and click OK.

2. In Solution Explorer, right-click the project node and then click Add Reference. On the .NET tab, select Microsoft.Office.Interop.Excel, version 12.0. Hold down CTRL and click Microsoft.Office.Interop.Word, version 12.0.

3. Click OK to close the Add Reference dialog box.

To create the bank account class

In this section, you will create a simple class that represents a bank account.

1. In Solution Explorer, right-click the project node, point to Add, and then click Class to open the Add New Item dialog box. Name the file Account.vb (for Visual Basic) or Account.cs (for C#) and click Add.

2. Add the following code to the new class. Note that when you declare a property, it is no longer necessary to also create an explicit backing field because the compiler will add one automatically. This is called an auto-implemented property, and it is new to Visual Basic 10.0:

Visual Basic code

image

Visual C# code

Note: Be sure to delete any namespace declarations before pasting in this code. To simplify the rest of the walkthrough, the Account class should be outside of any namespace.

image

To import the Office namespaces:

There is nothing new in this step. You are just adding Imports statements or using directives so that you do not have to fully qualify the names of the Excel and Word objects each time you reference them.

At the top of the Module1.vb or Program.cs file, add the following code:

Visual Basic code

image

Visual C# code

image

To add data to the account class

This step demonstrates collection initializers, which provide a convenient and expressive way to populate a collection like a list or array with elements when you first create the object. This feature was introduced in C# in Visual Studio 2008 and is introduced in Visual Basic in Visual Studio 2010.

In the Main method of your application, add the following code:

image

To display the account data in Excel

This step demonstrates how to create a new Excel workbook and populate it with data from the List<Account> or List (Of Account) that was initialized in the previous step. Action is a delegate type; several Action delegates are defined that have differing numbers of input parameters, but they all return void. In a later step, you will use a statement lambda when calling DisplayInExcel to supply the inline method that matches the Action delegate signature.

1. Declare the DisplayInExcel method, as shown in the following code:

image

2. At the bottom of the Main method, call the DisplayInExcel method by using the following code. Note the use of the statement lambda, which colors the Excel cell red if the balance is negative.

image

3. To automatically adjust the width of these columns to fit their contents, insert the following code at the end of the DisplayInExcel method:

image

Notice that the AutoFit method is being called on the result of the indexed call to Columns, which has a type of Object. Return values of type Object from COM hosts such as Office are automatically treated as Dynamic in C# 4.0, which allows dynamic dispatch (late binding) and avoids the casts that would be required in C# 3.0:

Visual C# code

image

To embed the Excel spreadsheet into a Word document

In this step, you will create an instance of Word and paste a link to the Excel worksheet into the document. There is nothing new in the Visual Basic code, because Visual Basic has supported named and optional parameters for a long time. Note, however, that C# 4.0 now supports this feature. The PasteSpecial method actually has seven parameters, but they are all optional, so in C# it is no longer necessary to supply arguments for all parameters.

Insert the following code at the end of the Main method:

image

Finally, in the definition for PasteSpecial, note that all of its parameters are ByRef (ref in C#). C# 4.0 allows you to make calls to COM components without having to specify ref in front of each parameter. What can now be done in one line of code used to take about 15 (for this particular function) in C# 3.0:

image

To run the application

  • Press F5 to run the application. First, Excel will open and display a worksheet. Next, Word will open and display a document that contains an embedded link to the Excel worksheet. It should look something like this:

clip_image002[9]

To remove the PIA dependency

1. Start a Visual Studio command prompt (from the Visual Studio Tools folder on the Start menu). Type ildasm and press ENTER. Open your assembly. (It will be in your project’s bin directory, by default: My Documents\Visual Studio 10\Projects\project name\bin)

2. Double-click Manifest. You should see the following entry for Excel in the list. (There will also be a similar entry for Word.)

image

This is an assembly reference to the Excel primary interop assembly (PIA). Because this assembly is referenced by your application, it needs to exist on the end user's computer.

3. The No-PIA feature enables you to compile your application in such a way that references to a PIA are no longer required; the compiler will import whatever types you use from the PIA into your own assembly. This results in a much smaller assembly and easier deployment; the PIAs no longer have to be present on the user's computer. Also, this application can now work with multiple versions of Office (because it does not require a specific version of a PIA).

4. In Solution Explorer, click the Show All References button. Expand the References folder and select Microsoft.Office.Interop.Excel. Press F4 to display the Properties window.

clip_image004[5]

5. Change the Embed Interop Types property from False to True.

6. Repeat step 5 for Microsoft.Office.Interop.Word.

7. Be sure to close Ildasm. Press F5 to rebuild the project. Verify that everything still runs correctly.

8. Repeat steps 1 and 2. Notice that this time the entries for Excel and Word are gone. You no longer need to distribute these PIA DLLs to the user’s computer.


http://blogs.msdn.com/b/vbteam/archive/2008/12/15/walkthrough-office-programmability-in-visual-basic-and-c-in-vs-2010-lisa-feigenbaum.aspx


반응형
반응형

Column names

If a column name contains any of these special characters ~ ( ) # \ / = > < + - * % & | ^ ' " [ ], you must enclose the column name within square brackets [ ]. If a column name contains right bracket ] or backslash \, escape it with backslash (\] or \\).

[C#]

dataView.RowFilter = "id = 10";      // no special character in column name "id"
dataView.RowFilter = "$id = 10";     // no special character in column name "$id"
dataView.RowFilter = "[#id] = 10";   // special character "#" in column name "#id"
dataView.RowFilter = "[[id\]] = 10"; // special characters in column name "[id]"

Literals

String values are enclosed within single quotes ' '. If the string contains single quote ', the quote must be doubled.

[C#]

dataView.RowFilter = "Name = 'John'"        // string value
dataView.RowFilter = "Name = 'John ''A'''"  // string with single quotes "John 'A'"

dataView.RowFilter = String.Format("Name = '{0}'", "John 'A'".Replace("'", "''"));

Number values are not enclosed within any characters. The values should be the same as is the result of int.ToString() or float.ToString() method for invariant or English culture.

[C#]

dataView.RowFilter = "Year = 2008"          // integer value
dataView.RowFilter = "Price = 1199.9"       // float value

dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.NumberFormat,
                     "Price = {0}", 1199.9f);

Date values are enclosed within sharp characters # #. The date format is the same as is the result of DateTime.ToString() method for invariant or English culture.

[C#]

dataView.RowFilter = "Date = #12/31/2008#"          // date value (time is 00:00:00)
dataView.RowFilter = "Date = #2008-12-31#"          // also this format is supported
dataView.RowFilter = "Date = #12/31/2008 16:44:58#" // date and time value

dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.DateTimeFormat,
                     "Date = #{0}#", new DateTime(2008, 12, 31, 16, 44, 58));

Alternatively you can enclose all values within single quotes ' '. It means you can use string values for numbers or date time values. In this case the current culture is used to convert the string to the specific value.

[C#]

dataView.RowFilter = "Date = '12/31/2008 16:44:58'" // if current culture is English
dataView.RowFilter = "Date = '31.12.2008 16:44:58'" // if current culture is German

dataView.RowFilter = "Price = '1199.90'"            // if current culture is English
dataView.RowFilter = "Price = '1199,90'"            // if current culture is German

Comparison operators

Equal, not equal, less, greater operators are used to include only values that suit to a comparison expression. You can use these operators = <> < <= > >=.

Note: String comparison is culture-sensitive, it uses CultureInfo from DataTable.Localeproperty of related table (dataView.Table.Locale). If the property is not explicitly set, its default value is DataSet.Locale (and its default value is current system culture Thread.Curren­tThread.Curren tCulture).

[C#]

dataView.RowFilter = "Num = 10"             // number is equal to 10
dataView.RowFilter = "Date < #1/1/2008#"    // date is less than 1/1/2008
dataView.RowFilter = "Name <> 'John'"       // string is not equal to 'John'
dataView.RowFilter = "Name >= 'Jo'"         // string comparison

Operator IN is used to include only values from the list. You can use the operator for all data types, such as numbers or strings.

[C#]

dataView.RowFilter = "Id IN (1, 2, 3)"                    // integer values
dataView.RowFilter = "Price IN (1.0, 9.9, 11.5)"          // float values
dataView.RowFilter = "Name IN ('John', 'Jim', 'Tom')"     // string values
dataView.RowFilter = "Date IN (#12/31/2008#, #1/1/2009#)" // date time values

dataView.RowFilter = "Id NOT IN (1, 2, 3)"  // values not from the list

Operator LIKE is used to include only values that match a pattern with wildcards. Wildcardcharacter is * or %, it can be at the beginning of a pattern '*value', at the end 'value*', or at both '*value*'. Wildcard in the middle of a patern 'va*lue' is not allowed.

[C#]

dataView.RowFilter = "Name LIKE 'j*'"       // values that start with 'j'
dataView.RowFilter = "Name LIKE '%jo%'"     // values that contain 'jo'

dataView.RowFilter = "Name NOT LIKE 'j*'"   // values that don't start with 'j'

If a pattern in a LIKE clause contains any of these special characters * % [ ], those characters must be escaped in brackets [ ] like this [*], [%], [[] or []].

[C#]

dataView.RowFilter = "Name LIKE '[*]*'"     // values that starts with '*'
dataView.RowFilter = "Name LIKE '[[]*'"     // values that starts with '['

The following method escapes a text value for usage in a LIKE clause.

[C#]

public static string EscapeLikeValue(string valueWithoutWildcards)
{
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < valueWithoutWildcards.Length; i++)
  {
    char c = valueWithoutWildcards[i];
    if (c == '*' || c == '%' || c == '[' || c == ']')
      sb.Append("[").Append(c).Append("]");
    else if (c == '\'')
      sb.Append("''");
    else
      sb.Append(c);
  }
  return sb.ToString();
}

[C#]

// select all that starts with the value string (in this case with "*")
string value = "*";
// the dataView.RowFilter will be: "Name LIKE '[*]*'"
dataView.RowFilter = String.Format("Name LIKE '{0}*'", EscapeLikeValue(value));

Boolean operators

Boolean operators AND, OR and NOT are used to concatenate expressions. Operator NOT has precedence over AND operator and it has precedence over OR operator.

[C#]

// operator AND has precedence over OR operator, parenthesis are needed
dataView.RowFilter = "City = 'Tokyo' AND (Age < 20 OR Age > 60)";

// following examples do the same
dataView.RowFilter = "City <> 'Tokyo' AND City <> 'Paris'";
dataView.RowFilter = "NOT City = 'Tokyo' AND NOT City = 'Paris'";
dataView.RowFilter = "NOT (City = 'Tokyo' OR City = 'Paris')";
dataView.RowFilter = "City NOT IN ('Tokyo', 'Paris')";

Arithmetic and string operators

Arithmetic operators are addition +, subtraction -, multiplication *, division / and modulus %.

[C#]

dataView.RowFilter = "MotherAge - Age < 20";   // people with young mother
dataView.RowFilter = "Age % 10 = 0";           // people with decennial birthday

There is also one string operator concatenation +.

Parent-Child Relation Referencing

parent table can be referenced in an expression using parent column name with Parent.prefix. A column in a child table can be referenced using child column name with Child. prefix.

The reference to the child column must be in an aggregate function because child relationships may return multiple rows. For example expression SUM(Child.Price) returns sum of all prices in child table related to the row in parent table.

If a table has more than one child relation, the prefix must contain relation name. For example expression Child(OrdersToItemsRelation).Price references to column Price in child table using relation named OrdersToItemsRe lation.

Aggregate Functions

There are supported following aggregate functions SUM, COUNT, MIN, MAX, AVG (average), STDEV(statistical standard deviation) and VAR (statistical variance).

This example shows aggregate function performed on a single table.

[C#]

// select people with above-average salary
dataView.RowFilter = "Salary > AVG(Salary)";

Following example shows aggregate functions performed on two tables which have parent-child relation. Suppose there are tables Orders and Items with the parent-child relation.

[C#]

// select orders which have more than 5 items
dataView.RowFilter = "COUNT(Child.IdOrder) > 5";

// select orders which total price (sum of items prices) is greater or equal $500
dataView.RowFilter = "SUM(Child.Price) >= 500";

 


By  http://dotnet.fibo.us/?p=331

반응형
반응형
SqlDataSource를 사용하지 않고 .cs에서 페이징으로 구성할때는
아래와 같이 PagePropertiesChanging 이벤트를 추가해줘야한다.

protected void Listview_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
     DataPager dp;
     dp = ((ListView)sender).FindControl("DataPager1") as DataPager;
     dp.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);

     ListView.DataSource = GetDataSet();
     ListView.DataBind();
}


GetDataSet()은 사용하시는 분의 취향에 따라 사용해주세용.~~
반응형
반응형

-- Aspx
<%@ Register TagPrefix="cc1" Namespace="RashidPager" %>   // 네임스페이스 등록


<cc1:Pager ID="PagerMyCase"
                  runat="server"
                  OnPageChange="PagerMyCase_PageChange"
                  SliderSize="5"
                  ShowFirstAndLast="false"
                  ShowPreviousAndNext="true" 
                  ShowInfo="True"
                  RowPerPage="10" 
                  CurrentPageCssClass="paging_current"
                  OtherPageCssClass="paging_other"
                  ShowTip="false"
                  HideOnSinglePage="false"
                  NextText="&gt"
                  PreviousText="&lt"  />


-- CS
using RashidPager;

<Data Bind>
// 페이지당 행의 수
db.AddInParameter(dbCmd, "@PageSize", DbType.Int16, PagerSubmittedCase.RowPerPage);  
// 현재 페이지 Number
db.AddInParameter(dbCmd, "@CurrentPage", DbType.Int16, PagerSubmittedCase.CurrentPageNo);
// 총 데이터 수(return value)
db.AddOutParameter(dbCmd, "@TotalCount", DbType.String, 5);

// 총 데이터 수를 Pager 클래스의 TotalRow의 변수에 값을 배정한다
PagerSubmittedCase.TotalRow = Convert.ToInt32(db.GetParameterValue(dbCmd, "@TotalCount"));


// 페이지 Change 이벤트 설정
// 페이지 번호나 Next, Previous가 클릭될때 이벤트가 발생한다.
protected void PagerSubmittedCase_PageChange(object sender, PageChangeEventArgs e)
{
     ((Pager)sender).CurrentPageNo = e.PageNo;
     Submitted_DataBind();
}


-- Database
CREATE PROC ProcName
    @PageSize        tinyint    = 10,
    @CurrentPage    int    = 1,
    @TotalCount        int output
AS
BEGIN
    SET NOCOUNT ON
   
    DECLARE    @UpperBand    int
    DECLARE    @LowerBand    int
   
    SET @UpperBand = ((@CurrentPage - 1) * @PageSize) + 1
    SET @LowerBand = @CurrentPage * @PageSize

    -- Row Number가 추가된 임시 테이블 생성
     ;WITH tempTable AS (
        SELECT        컬럼들,  Row_Number() OVER (ORDER BY 정렬기준 컬럼 DESC) AS RowNum
        FROM           테이블명
        WHERE         조건절
    )

    -- 데이터 Select
    SELECT    컬럼들
    FROM       tempTable
    WHERE     RowNum BETWEEN     @UpperBand AND @LowerBand
   
    -- Total Count
    SELECT        @TotalCount = Count(*)
    FROM           테이블명
    WHERE         조건절
END

반응형
반응형
 foreach (Control c in Page.Form.Controls)
      {
          switch (c.GetType().ToString())
          {
              case ("System.Web.UI.WebControls.TextBox"):
                  paramters.Add(c.ID, ((TextBox)c).Text.ToString());
                  break;

반응형
반응형

IE8에 의해서 간간히 발생하는 오류로써

처음에는 무슨 오류가 싶어서 하루 종일 소스만 보면서 파고 들었는데

결국 "..WebResource.axd?d=XXXXXXX" d 파라미터 뒤에 QueryString이 중간에 짤려있었다..ㅠㅠ

간단한 해결 방안은!!!!!!!!!!!!!

head안에 정의 되어 있는 <meta http-equiv="content-type" content="text/html; charset=utf-8" />

메타태그를 Page_Load 함수로 옮겨놓는 것이다.ㅋ

Response.ContentType = "text/html";
Response.Charset = "utf-8";

요렇게 말이다.!!

브라우저의 문제였단 말인가..ㅜㅜ

아..머리아포~~

참고 사이트
http://blog.soft-cor.com/?tag=/scriptresource.axd
http://alterprocedure.net/articles/alterprocedure/aspnet-causing-corrupted-html-with-webresourceaxd-and-scriptresourceaxd.aspx
반응형
반응형

[Page.GetPostBackEventReference()를 이용한 doPostBack]

 

자바스크립트로 behind code의 메서드를 실행하고 싶은 경우가 있다.


이럴 경우 보통은 스크립트에서 __doPostBack() 메서드를 정의해서 사용하곤 한다. 하지만, 이는 좋지 못한 방법이다.

 

__doPostBack() 메서드는 .net에서 자동 생성하는 부분으로, 개발자가 별도로 작성하여도 바뀔 가능성이 있다. 또한, .net에서 자동으로 생성하지 않는 경우도 발생한다.

 

스크립트로 behind code의 메서드를 실행하고 싶을 때는 아래와 같은 방법을 권한다.

 

<%= Page.GetPostBackEventReference( WebFormButton ) %>

 

이는 postback이 발생하는 WebForm Control을 매개변수로 넘겨주면, 자동으로 __doPostBack()을 생성해 준다.


ex)
[Page.aspx]
btnOne -> HTML Input 컨트롤 - visible

<script language="javascript">
    function btnOneClick()
    {
        <%= Page.GetPostBackEventReference( btnTwo ) %>
    }
</script>

 

<input type="button" onclick="btnOneClick()">

 

[Page.aspx.cs]
btnTwo -> WebForm Button 컨트롤 - invisible

private void btnTwo_Click(...)
{
    ...
}

 


반응형

+ Recent posts