'프로그래밍'에 해당되는 글 98건

  1. 2013.03.09 ASP.NET gridview에 데이터 입력하기
  2. 2013.03.01 dateTimePicker 포맷 변경
  3. 2013.03.01 C# String.format
  4. 2013.02.28 해당 월의 마지막 날자 구하기
  5. 2013.02.28 파일 업로드 소스

detailsview에는 추가 하는 옵션이 있는데, gridview에는 그 기능이 없었다.

구글 검색을 했는데, 기막힌 방법이 있어서 잊어버리기 전에 포스팅한다.

이 한줄이 시간을 세이브 시켰다.


Protected Sub btnAddProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddProduct.Click
   'Add the new product!
   AddProductDataSource.Insert()
End Sub
 




출처: http://www.4guysfromrolla.com/articles/050207-1.aspx

Accessing and Updating Data in ASP.NET: Inserting Data

By Scott Mitchell

An Overview of Inserting Data Using the Data Source Controls


The AccessDataSource, SqlDataSource, and ObjectDataSource controls all support inserting, updating, and deleting capabilities. In a nutshell, all three have an Insert method that, when invoked, kicks off the following inserting workflow:
  1. The data source's Inserting event is fired
  2. The inserting "action" occurs
  3. The data source's Inserted event is fired
The inserting "action" differs between the data source controls. For the AccessDataSource and SqlDataSource, the action involves connecting to the specified database and executing the INSERT statement specified by the control's InsertCommand property. For the ObjectDataSource, the inserting "action" involves creating an instance of the data source's underlying object and invoking the specified InsertMethod. This article focuses on the SqlDataSource control; for a detailed look at inserting with the ObjectDataSource, refer to the "Editing, Inserting, and Deleting" tutorials in my Working with Data in ASP.NET 2.0 tutorial series.

Let's explore the inserting "action" for the AccessDataSource and SqlDataSource controls in more detail. The INSERT statement or stored procedure specified by the control's InsertCommand uses a parameterized query. That is, if you use an ad-hoc SQL statement for the InsertCommand, that INSERT statement will use parameters like so:

INSERT INTO TableName (ColumnName1, ColumnName2, ..., ColumnNameN)
VALUES (@Parameter1, @Parameter2, ..., @ParameterN)

In the Filtering Database Data with Parameters article, we looked at using parameters in the SelectCommand to filter the results, such as SELECT * FROM Products WHERE Price < @UnitPrice. The parameter - @UnitPrice, in this instance - has its value specified via the data source control's SelectParameters, which can specify a source for the parameter value. The source may be: a hard-coded value like "3.95", which would return all products less than $3.95; the value of a Web control on the page, allowing the user to enter a price bound in a TextBox; from the querystring; from session state; and so on.

Likewise, the parameter values in the INSERT statement are assigned based on the parameters in the data source control's InsertParameters collection, and these parameters can use the same sources as the SelectParameters.

The AccessDataSource and SqlDataSource controls, behind the scenes, use the standard ADO.NET classes to perform their data access. That is, they connect to the database using a SqlConnection or OleDbConnection object and specify the command text and parameters via a SqlCommand or OleDbCommand object.

Given this information, the inserting workflow for the AccessDataSource and SqlDataSource can be more specifically expressed as:

  1. The data source's Inserting event is fired
  2. SqlConnection and SqlCommand (or OleDbConnection and OleDbCommand) objects are created
  3. The command object's CommandText property is assigned the data source control's InsertCommand property
  4. The parameters in the data source control's InsertParameters collection are added the command object's Parameters collection
  5. A connection to the database is established and the command is executed, thereby inserting the data
  6. The data source's Inserted event is fired
The remainder of this article examines three inserting scenarios using the SqlDataSource control: inserting data through a manually-created Web form; inserting data using the DetailsView control; and retrieving the value of the just-inserted record's IDENTITY column. The full code for these demos is available in the download at the end of this article.

Inserting Data Using a Manually-Created Web Form


The demos available at the end of this article illustrate different techniques for inserting data into the Products table of the Northwind database. The Products table contains a number of columns. Each product record is uniquely identified by its ProductID, which is an AutoNumber/IDENTITY column. When inserting a record into this table, the only two columns that are required are ProductName and Discontinued; all other columns can accept a value of NULL.

Imagine that we were tasked with creating a page that allowed users to add new records to the Products table by specifying the new item's name, category, price, and discontinued status. We could create a simple Web Form that included TextBoxes, a DropDownList, and a CheckBox control to collect these input fields, along with an "Add Product" Button control that, when clicked, would insert the new product into the database.

In addition to these user input controls we could also add a SqlDataSource control to handle the actual insertion. We could set this control's InsertCommand to the following INSERT statement:

INSERT INTO Products(ProductName, CategoryID, UnitPrice, Discontinued)
VALUES (@ProductName, @CategoryID, @UnitPrice, @Discontinued)

Note the use of the parameters following the VALUES keyword. These sources for these parameters' values would simply be the user input Web controls on the page. Map these parameters' values in the InsertParameters collection using ControlParameters that point to the appropriate Web controls on that page. There are a variety of ways to accomplish this. From the Designer, click on the SqlDataSource and go to the Properties window. There you will see an InsertQuery option that, if clicked, displays the Command and Parameter Editor shown below. Here you can specify the InsertCommand, the parameters, and their source. Note that each of the four parameters uses a Control as its Parameter source, with the ControlID drop-down list set to the appropriate Web control on the page.

Alternatively, these parameters can be specified via the SqlDataSource control's declarative syntax:

<asp:SqlDataSource ID="AddProductDataSource" runat="server" ConnectionString="..."
      InsertCommand="INSERT INTO Products(ProductName, CategoryID, UnitPrice, Discontinued) VALUES (@ProductName, @CategoryID, @UnitPrice, @Discontinued)"
      ProviderName="...">
   <InsertParameters>
      <asp:ControlParameter ControlID="ProductName" Name="ProductName" PropertyName="Text" />
      <asp:ControlParameter ControlID="Categories" Name="CategoryID" PropertyName="SelectedValue" />
      <asp:ControlParameter ControlID="UnitPrice" Name="UnitPrice" PropertyName="Text" />
      <asp:ControlParameter ControlID="Discontinued" Name="Discontinued" PropertyName="Checked" />
   </InsertParameters>
</asp:SqlDataSource>

Once the Web controls have been added to the page and the SqlDataSource's InsertCommand and InsertParameters properties have been correctly configured, inserting a new record is as simple as calling the data source control's Insert() method. That is, the only code you need to write is the following line of code (which would be placed in the "Add Product" Button's Click event handler):

Protected Sub btnAddProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddProduct.Click
   'Add the new product!
   AddProductDataSource.Insert()
End Sub

Inserting Data Using a DetailsView Control


A number of new data Web controls were introduced with ASP.NET 2.0. These include the GridView, DetailsView, and FormView, among others. The DetailsView and FormView controls display information about one record at a time (unlike the GridView, which displays information about a set of records). The DetailsView and FormView controls can also be configured to display an inserting interface. In short, you can use the DetailsView or FormView controls to create an interface for inserting data into the database without having to write a line of code!

The DetailsView vs. the FormView Control
The DetailsView and FormView controls have a lot in common - they both display one record at a time and can display interfaces for inserting and updating data. The difference between the two is that the DetailsView control is composed of DataFields (BoundFields, CheckBoxFields, TemplateFields, and so on), just like the GridView. This results in a very boxy appearance. The FormView, on the other hand, uses templates instead of DataFields; consequently, it allows for a much more flexible layout of its display, inserting, and updating interfaces.

Start by adding a SqlDataSource control to the page and use the same InsertCommand as in the previous example:

INSERT INTO Products(ProductName, CategoryID, UnitPrice, Discontinued)
VALUES (@ProductName, @CategoryID, @UnitPrice, @Discontinued)

Next, add the parameters to the control's InsertParameters collection. Rather than using ControlParameters, use the default Parameter object. Also, the DetailsView we will create for this demo will not include an interface for the user to specify the category. Therefore, set the corresponding Parameter object's DefaultValue to "1". This will assign every product added through this page to the Beverages category.

<asp:SqlDataSource ID="AddProductDataSource" runat="server" ConnectionString="..."
      InsertCommand="INSERT INTO Products(ProductName, CategoryID, UnitPrice, Discontinued) VALUES (@ProductName, @CategoryID, @UnitPrice, @Discontinued)"
      ProviderName="...">
   <InsertParameters>
      <asp:Parameter Name="ProductName" Type="String" />
      <asp:Parameter Name="CategoryID" DefaultValue="1" />
      <asp:Parameter Name="UnitPrice" Type="Decimal" />
      <asp:Parameter Name="Discontinued" Type="Boolean" />
   </InsertParameters>
</asp:SqlDataSource>

Next, add a DetailsView to the page and set its DataSourceID property to the ID of the SqlDataSource control (AddProductDataSource). From the DetailsView's smart tag, check the "Enable Inserting" checkbox. This adds a CommandField to the DetailsView and sets its ShowInsertButton property to True. A CommandField with this configuration displays a "New" Button when the DetailsView control is in its ReadOnly mode. When the "New" Button is clicked, a postback ensues and the DetailsView is shifted into its Insert mode, causing the CommandField to display "Insert" and "Cancel" Buttons.

The SqlDataSource control does not contain a value for its SelectCommand, so no data will be displayed in the DetailsView. In fact, for this example we want the DetailsView to always be in an insertable mode (that is, we don't want to make the user have to click "New" to start adding a new record). Set the DetailsView's DefaultMode property to Insert to indicate that the DetailsView control should display just its inserting interface.

Next, add two BoundFields and a CheckBoxField to the DetailsView, setting the HeaderText and DataField properties so that they are bound to the ProductName, UnitPrice, and Discontinued columns used by the SqlDataSource. Finally, set the AutoGenerateRows property to False.

You can accomplish these two tasks from the Fields dialog box or by manually entering the control's declarative markup. To use the Fields dialog box, click the Edit Fields link from the DetailsView's smart tag. Add the two BoundFields and CheckBoxField and set their properties from the list on the right. To set the AutoGenerateRows property to False, simply uncheck the "Auto-generate fields" checkbox in the lower left corner.

Alternatively, you can specify the DetailsView's fields and set the AutoGenerateRows property to False through the declarative syntax:

<asp:DetailsView ID="DetailsView1" runat="server"

AutoGenerateRows="False" DataSourceID="AddProductDataSource"


      DefaultMode="Insert" CellPadding="4" ForeColor="#333333" GridLines="None">
   <Fields>
      <asp:BoundField DataField="ProductName" HeaderText="Product Name:" />
      <asp:BoundField DataField="UnitPrice" HeaderText="Unit Price:" />
      <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued:" />
      <asp:CommandField ShowInsertButton="True" />
   </Fields>
</asp:DetailsView>

That's all there is to it! When a user visits this page and enters the name, price, and discontinued status of a product and clicks Insert, a postback occurs. The DetailsView automatically assigns the values assigned to its input controls to the SqlDataSource's corresponding InsertParameters before starting the inserting workflow. The net result is that a new record is inserted into the database without writing a lick of code and without having to manually map the SqlDataSource's InsertParameters to their sources (since the DetailsView does this for us automatically when Insert is clicked).

This example illustrates only the simplest facilities of the DetailsView and omits important steps in a real-world application, such as input validation and customizing the inserting interface. For example, since the ProductName column is required, the insert will fail if the user leaves this textbox empty. Likewise, if the user puts in an invalid unit price value (like "expensive!"), an error will occur when attempting to insert the illegal value into the database. The download at the end of this article includes another DetailsView example that illusrated adding validation controls and customizing the inserting interface to prompt the user for the new product's category via a drop-down list of available category choices. For more information on customizing the DetailsView's inserting interface, see Customizing the Data Modification Interface (VB Version) (C# version).

Inserting and Returning the Value of the Just-Inserted Record's IDENTITY Column


Most database tables provide some mechanism to uniquely identify each record. There are a variety of approaches, but a very common one is the use of an IDENTITY column, which is also referred to as an AutoNumber. An IDENTITY column is one whose value is automatically assigned by the database system when a new record is added to the table. These values start at some seed (usually 1) and increment by some specified amount with each new record (usually incremented by 1). Therefore, if you add three new records to the table, the IDENTITY column values for those first three records will be 1, 2, and 3, respectively.

When using IDENTITY columns a common requirement is to be able to retrieve the value of the just-inserted record's IDENTITY column. Perhaps after inserting a new record you want to automatically whisk the user to a details page where you need to pass along the IDENTITY column value through the querystring, or maybe you want to add additional records in a child table and need the just-inserted parent record's IDENTITY column value to properly link the child records to the parent. In either case, in Microsoft SQL Server you can use the SCOPE_IDENTITY() keyword to get the IDENTITY column value of the just-insert record.

In order to pull back this information when using the SqlDataSource we need to do the following:

  1. Create a stored procedure that returns the just-inserted record's IDENTITY column value using an OUTPUT parameter. See Retrieving Scalar Data from a Stored Procedure for more information on this topic.
  2. Configure the SqlDataSource to use this stored procedure. This involves updating the InsertCommand to the name of the stored procedure created from step 1, setting the data source control's InsertCommandType to StoredProcedure, and adding an output parameter to the InsertParameters collection.
  3. To access the resulting output parameter's value we need to create an event handler for the SqlDataSource's Inserted event. Recall that this event fires after the insert "action" has been performed. Once we have the IDENTITY value of the just-inserted record we can use it as needed.
In the database included in the download at the end of this article you will find a stored procedure named AddProductAndReturnNewProductIDValue that accepts four input parameters and has an OUTPUT parameter (@NewProductID). As the following T-SQL syntax shows, this stored procedure inserts a new record into Products and then assigns the value returned by SCOPE_IDENTITY() to @NewProductID:
ALTER PROCEDURE dbo.AddProductAndReturnNewProductIDValue (
    @ProductName nvarchar(40),
    @CategoryID int,
    @UnitPrice money,
    @Discontinued bit,

    @NewProductID int OUTPUT


)
AS

-- Insert the record into the database
INSERT INTO Products(ProductName, CategoryID, UnitPrice, Discontinued)
VALUES (@ProductName, @CategoryID, @UnitPrice, @Discontinued)

-- Read the just-inserted ProductID into @NewProductID
SET @NewProductID = SCOPE_IDENTITY()

Next, update the SqlDataSource to use the AddProductAndReturnNewProductIDValue as its InsertCommand instead of an ad-hoc SQL statement. Also, add an ouput parameter to the InsertParameters collection. Note that the output parameter in the InsertParameters collection is a Parameter object whose Direction property is set to Output:

<asp:SqlDataSource ID="AddProductDataSource" runat="server" ConnectionString="..."
      InsertCommand="AddProductAndReturnNewProductIDValue"
      ProviderName="..." InsertCommandType="StoredProcedure">
   <InsertParameters>
      <asp:ControlParameter ControlID="ProductName" Name="ProductName" PropertyName="Text" />
      <asp:ControlParameter ControlID="Categories" Name="CategoryID" PropertyName="SelectedValue" />
      <asp:ControlParameter ControlID="UnitPrice" Name="UnitPrice" PropertyName="Text" />
      <asp:ControlParameter ControlID="Discontinued" Name="Discontinued" PropertyName="Checked" />
      

<asp:Parameter Direction="Output" Name="NewProductID" Type="Int32" />


   </InsertParameters>
</asp:SqlDataSource>

Adding an output parameter to the SqlDataSource's InsertParameters collection adds an output parameter to the Parameters collection of the internal SqlCommand object used by the data source control during the inserting "action." The value of this parameter can be examined in the Inserted event handler. As the following event handler code shows, the internal SqlCommand object is accessible through the e.Command property in the event handler. Here we can grab the specific parameter instance and insepct its Value property to determine the IDENTITY column value of the just-inserted record:

Protected Sub AddProductDataSource_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles AddProductDataSource.Inserted
   'Read the value of the @NewProductID OUTPUT parameter
   Dim newProductID As Integer = Convert.ToInt32(e.Command.Parameters("@NewProductID").Value)

   'Display confirmation message
   NewProductAddedMsg.Text = String.Format("Product {0} has been added to the database... This new product's ProductID value is {1}...", ProductName.Text, newProductID)
End Sub

Conclusion


In this article we looked at how to use the SqlDataSource to insert data into a database. We worked through three examples: inserting using a manually-created Web Form; inserting from a DetailsView control; and retrieving the IDENTITY column value of the just-inserted record. In all three cases, the SqlDataSource control encapsulates many of the data access tasks, such as connecting to the database, creating the command object, and executing the parameterized query. In future installments of this article series we will take a similar in-depth look at updating and deleting.

Until then... Happy Programming!

By Scott Mitchell


Posted by 노을지기

출처: http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.customformat.aspx

dateTimePicker 포맷을 변경할 경우가 필요할때 사용한다..ㅋㅋ

public void SetMyCustomFormat()
{
   // Set the Format type and the CustomFormat string.
   dateTimePicker1.Format = DateTimePickerFormat.Custom;
   dateTimePicker1.CustomFormat = "MMMM dd, yyyy - dddd";
}


Posted by 노을지기

출처: http://msdn.microsoft.com/ko-kr/library/dd260048%28v=vs.95%29.aspx 

출처: http://pullthelever.tistory.com/339

숫자 앞에 채우기 예제이다.

결론은 텍스트 박스에 넣을때

int intNextOrderNo = 343;

string strFormatOrderNo = String.Format("{0:D8}", intNextOrderNo);

결과는 00000343 이다.

모두 감사합니다.

{0:G}"

0은 문자열 옆의 인수들 중 몇 번째 인수(0부터 시작)를 가리킬건지 말한다.

 

ex)

Console.WriteLine("첫 번째 인수 {0:G}, 두 번째 인수 {1:G}, 세 번째 인수 {2:G}",10, 20, 30);

//결과->  첫 번째 인수 10, 두 번째 인수 20, 세 번째 인수 30

//WriteLine 메서드는 출력하고나서 항상 한 줄 내려간다.

 

"{0}","{1}" 

 위와 같이 숫자 뒤에 :X 를 생략하면 문자열을 가리킬 수 있다. 문자형 char도 가능하다.

 int, long, double, float, byte 등 정수형, 실수형도 가능하다.

 Size,Point 같은 것도 가능하다

 Console.WriteLine(string.Format("{0}, {1}, {2}","냠냠",'냔',123456789));

 //결과-> 냠냠, 냔, 123456789
//String.Format에서도 사용한다. 

 

                                           

시스템에 따라 \ 또는 $ 를 붙임, 소수점을 가질 수 있음

 "{0:C}"

10진법 (D뒤의 숫자만큼 자리수를 맞춘다. 값이 없는 앞 자리들은 0으로 채운다)

ex) ("{0:D5}", 123);   //->   00123

 "{0:D5}"

 E(지수표시)를 이용한 소수표시 (E뒤의 숫자는소수점자리수)

ex)("{0:E1}",12345);  //->  1.2E+004

 "{0:E}"

 고정 소수점 (F뒤의 숫자만큼)으로 표시

ex)  ("{0:D5}", 12.3);  //-> 12.300

 "{0:F5}"

 E, F, D를 적절히 선택

 "{0:G}"

 ','를 정수부분의 3자리마다 넣어 표시 (소수도 표시가능)

 ex) 100,000,000

 "{0:N}"

 백분율 (소수를 X100해서 표시하고 %를 붙임)

 "{0:P}"

 16진법

 "{0:X}






전체 자릿수 지정자와 함께 "D" 표준 숫자 형식 문자열을 사용하여 정수 앞에 0을 채울 수 있습니다. 사용자 지정 숫자 형식 문자열을 사용하면 정수와 부동 소수점 숫자 앞에 0을 채울 수 있습니다. 이 항목에서는 두 메서드를 사용하여 숫자 앞에 0을 채우는 방법을 보여 줍니다.

특정 길이까지 정수 앞에 0을 채우려면

  1. 정수 값에서 표시할 자릿수를 결정합니다. 이 수에 선행 자릿수를 포함합니다.

  2. 정수를 10진수 값으로 표시할지 또는 16진수 값으로 표시할지를 결정합니다.

    1. 정수를 10진수 값으로 표시하려면 ToString(String) 메서드를 호출하고 문자열 "Dn"을 format 매개 변수의 값으로 전달합니다. 여기서 n은 최소 문자열 길이를 나타냅니다.

    2. 정수를 16진수 값으로 표시하려면 ToString(String) 메서드를 호출하고 문자열 "Xn"을 format 매개 변수의 값으로 전달합니다. 여기서 n은 최소 문자열 길이를 나타냅니다.

    합성 서식 지정을 사용하는 메서드(예: Format 또는 WriteLine)에 형식 문자열을 사용할 수도 있습니다.

다음 예제에서는 형식이 지정된 숫자의 총 길이가 8자 이상이 되도록 선행 0을 사용하여 여러 정수 값의 형식을 지정합니다.

C#
byte byteValue = 254;
short shortValue = 10342;
int intValue = 1023983;
long lngValue = 6985321;
ulong ulngValue = UInt64.MaxValue;

outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");

// Display integer values by caling the ToString method.
outputBlock.Text += String.Format("{0,22} {1,22}", byteValue.ToString("D8"), byteValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", shortValue.ToString("D8"), shortValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", intValue.ToString("D8"), intValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", lngValue.ToString("D8"), lngValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", ulngValue.ToString("D8"), ulngValue.ToString("X8")) + "\n";
outputBlock.Text += "\n";

// Display the same integer values by using composite formatting.
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", byteValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", shortValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", intValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", lngValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", ulngValue) + "\n";
// The example displays the following output:
//                     00000254               000000FE
//                     00010342               00002866
//                     01023983               000F9FEF
//                     06985321               006A9669
//         18446744073709551615       FFFFFFFFFFFFFFFF
//       
//                     00000254               000000FE
//                     00010342               00002866
//                     01023983               000F9FEF
//                     06985321               006A9669
//         18446744073709551615       FFFFFFFFFFFFFFFF
//         18446744073709551615       FFFFFFFFFFFFFFFF


정수 앞에 특정 개수의 0을 채우려면

  1. 정수 값에서 표시할 선행 0의 개수를 결정합니다.

  2. 정수를 10진수 값으로 표시할지 또는 16진수 값으로 표시할지를 결정합니다. 10진수 값으로 형식을 지정하려면 "D" 표준 형식 지정자를 사용해야 합니다. 16진수 값으로 형식을 지정하려면 "X" 표준 형식 지정자를 사용해야 합니다.

  3. 정수 값의 ToString("D").Length 또는 ToString("X").Length 메서드를 호출하여 채워지지 않은 숫자 문자열의 길이를 확인합니다.

  4. 서식이 지정된 문자열에 포함하려는 선행 0의 개수를 0이 채워지지 않은 숫자 문자열의 길이에 더합니다. 이 값은 0이 채워진 문자열의 총 길이를 정의합니다.

  5. 정수 값의 ToString(String) 메서드를 호출하고 문자열 "Dn"(10진수 문자열의 경우) 및 "Xn"(16진수 문자열의 경우)을 전달합니다. 여기서 n은 0이 채워진 문자열의 총 길이를 나타냅니다. 합성 서식 지정을 지원하는 메서드에 "Dn" 또는 "Xn" 형식 문자열을 사용할 수도 있습니다.

다음 예제에서는 정수 값 앞에 5개의 0을 채웁니다.

C#
int value = 160934;
int decimalLength = value.ToString("D").Length + 5;
int hexLength = value.ToString("X").Length + 5;

outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");

outputBlock.Text += value.ToString("D" + decimalLength.ToString()) + "\n";
outputBlock.Text += value.ToString("X" + hexLength.ToString()) + "\n";
// The example displays the following output:
//       00000160934
//       00000274A6      


특정 길이까지 숫자 값 앞에 0을 채우려면

  1. 숫자의 문자열 표현에 사용할 소수점 왼쪽 자릿수를 결정합니다. 이 전체 자릿수에 선행 0을 포함합니다.

  2. 0 자리 표시자("0")를 사용하여 0의 최소 개수를 나타내는 사용자 지정 숫자 형식 문자열을 정의합니다.

  3. 숫자의 ToString(String) 메서드를 호출하고 사용자 지정 형식 문자열을 전달합니다. 합성 서식 지정을 지원하는 메서드에 사용자 지정 형식 문자열을 사용할 수도 있습니다.

다음 예제에서는 형식이 지정된 숫자의 총 길이에서 소수점 왼쪽 자릿수가 8 이상이 되도록 선행 0을 사용하여 여러 숫자 값의 형식을 지정합니다.

C#
string fmt = "00000000.##";
int intValue = 1053240;
decimal decValue = 103932.52m;
float sngValue = 1549230.10873992f;
double dblValue = 9034521202.93217412;

outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");

// Display the numbers using the ToString method.
outputBlock.Text += intValue.ToString(fmt) + "\n";
outputBlock.Text += decValue.ToString(fmt) + "\n";
outputBlock.Text += sngValue.ToString(fmt) + "\n";
outputBlock.Text += sngValue.ToString(fmt) + "\n";
outputBlock.Text += "\n";

// Display the numbers using composite formatting.
string formatString = " {0,15:" + fmt + "}\n";
outputBlock.Text += String.Format(formatString, intValue);
outputBlock.Text += String.Format(formatString, decValue);
outputBlock.Text += String.Format(formatString, sngValue);
outputBlock.Text += String.Format(formatString, dblValue);
// The example displays the following output:
//       01053240
//       00103932.52
//       01549230
//       01549230
//       
//               01053240
//            00103932.52
//               01549230
//          9034521202.93      


숫자 값 앞에 특정 개수의 0을 채우려면

  1. 숫자 값에 포함할 선행 0의 개수를 결정합니다.

  2. 0이 채워지지 않은 숫자 문자열의 소수점 왼쪽 자릿수를 확인합니다. 이를 위해 다음을 수행합니다.

    1. 숫자의 문자열 표현에 소수점 기호가 포함되어 있는지 여부를 확인합니다.

    2. 소수점 기호가 포함되어 있는 경우 소수점 왼쪽의 문자 수를 확인합니다.

      - 또는 -

      소수점 기호가 포함되어 있지 않은 경우 문자열의 길이를 확인합니다.

  3. 문자열에 표시할 각 선행 0에 대해 0 자리 표시자("0")를 사용하며, 0 자리 표시자나 자릿수 자리 표시자("#")를 사용하여 기본 문자열의 각 자릿수를 나타내는 사용자 지정 형식 문자열을 만듭니다.

  4. 숫자의 ToString(String) 메서드나 합성 서식 지정을 지원하는 메서드에 사용자 지정 형식 문자열을 매개 변수로 제공합니다.

다음 예제에서는 두 개의 Double 값 앞에 5개의 0을 채웁니다.

C#
outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");


double[] dblValues = { 9034521202.93217412, 9034521202 };
foreach (double dblValue in dblValues)
{
   string decSeparator = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
   string fmt, formatString;

   if (dblValue.ToString().Contains(decSeparator))
   {
      int digits = dblValue.ToString().IndexOf(decSeparator);
      fmt = new String('0', 5) + new String('#', digits) + ".##";
   }
   else
   {
      fmt = new String('0', dblValue.ToString().Length);
   }
   formatString = "{0,20:" + fmt + "}\n";

   outputBlock.Text += dblValue.ToString(fmt) + "\n";
   outputBlock.Text += String.Format(formatString, dblValue);
}
// The example displays the following output:
//       000009034521202.93
//         000009034521202.93
//       9034521202
//                 9034521202            



Posted by 노을지기

출처: http://www.devpia.com/Maeul/Contents/Detail.aspx?BoardID=6127&MAEULNO=769&no=26308&page=12


일반적으로 시스템의 해당월 첫째날과 마지막날 등의 날짜를 구할 경우...

DB와 웹서버가 같은 경우엔 아래의 경우처럼 시스템에서 뽑아오면 쉽겠죠.

 

   DateTime startYMD = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);


   //이번달시작일
  
string fYMD = startYMD .ToString("yyyyMMdd"); 

 

   //이번달 마지막날
  
string lYMD = startYMD .AddMonths(1).AddDays(-1).ToString("yyyyMMdd");


Posted by 노을지기

출처: http://www.progtalk.com/viewarticle.aspx?articleid=39


What is the FileUpload Web User control?


This is a web control written in Visual Studio 2005 using C#.  It will allows users to have a quick way to upload, delete, and launch documents.  It has two properties which are:

A.  Save Path
B.  Vitual Path
 

Screenshots

====================================================

====================================================


The Source Code:

using System;

using System.Web;

using System.Web.UI.WebControls;

using System.ComponentModel;

using System.IO;

 

public partial class Controls_FileUpload : System.Web.UI.UserControl

{

    private string SaveToPath = "";

    private string VirtualPath = "";

 

    #region File Upload Control Properties

    /// <summary>

    /// Save Location of File. Example "C:\TEMP\"

    /// </summary>

    [Browsable(true), Category("Properties"), Description("Save Location of File")]

    public string File_Save_Path

    {

        get

        {

            return SaveToPath;

        }

        set

        {

            SaveToPath = value;

        }

    }

 

    /// <summary>

    /// Virtual Path of document.  Example: "http://servername/filedirpath/"

    /// </summary>

    [Browsable(true), Category("Properties"), Description("Virtual Path of document")]

    public string Virtual_Path

    {

        get

        {

            return VirtualPath;

        }

        set

        {

            VirtualPath = value;

        }

 

    }

 

    #endregion

 

    protected void Page_Load(object sender, EventArgs e)

    {

        this.lblError.Text = "";

 

        if (!Page.IsPostBack)

        {

            if (this.VirtualPath.Length == 0)

            {

                this.lblError.Text = "Virtual Path Property has not been set.";

                this.Panel_Control.Enabled = false;

                return;

            }

            else if (this.SaveToPath.Length == 0)

            {

                this.lblError.Text = "Save To Path Property has not been set.";

                this.Panel_Control.Enabled = false;

                return;

            }

            else

            {

                if (ValidatePath() == true)

                {

                    if (ShowAllFiles() == false)

                    {

                        //An error occured.

                        this.Panel_Control.Enabled = false;

                        return;

                    }

                }

                else

                {

                    this.Panel_Control.Enabled = false;

                    return;

                }

            }

        }

    }

  

    /// <summary>

    /// Validates if the Path exists.  If it doesn't we try to create it.

    /// </summary>

    private bool ValidatePath()

    {

        try

        {

            if (System.IO.Directory.Exists(SaveToPath) == false)

            {

                System.IO.Directory.CreateDirectory(SaveToPath);

                return true;

            }

            else

            {

                return true;

            }

        }

        catch (Exception ex)

        {

            lblError.Text = "Error: " + ex.Message.ToString();

            return false;

        }

    }

 

    /// <summary>

    /// Shows all the files in this directory.

    /// </summary>

    private bool ShowAllFiles()

    {

        try

        {

            //Clear the list box

            lstDocs.Items.Clear();

          

            //Get all the directory files

            string[] subfiles = Directory.GetFiles(SaveToPath);

            foreach (string file_obj in subfiles)

            {

                string doc_name = System.IO.Path.GetFileName(file_obj);

 

                //text is document name

                //value is full path to document

                ListItem tempItem = new ListItem(doc_name, file_obj);

 

                //add to list box

                lstDocs.Items.Add(tempItem);

            }

 

            return true;

        }

        catch (Exception ex)

        {

            this.lblError.Text = "Error: " + ex.Message.ToString();

            return false;

        }

    }

 

    /// <summary>

    /// Upload File

    /// </summary>

    protected void btnUpload_Click(object sender, EventArgs e)

    {

        try

        {

            if (filePSE.PostedFile.FileName == "" || filePSE.PostedFile.ContentLength == 0)

            {

                return;

            }

          

            string path = filePSE.PostedFile.FileName;

            string doc_name = System.IO.Path.GetFileName(path);

            string err = "";

 

            bool isSafeFile = CheckExtensions(doc_name);

            if (isSafeFile == false)

            {

                return;

            }

 

            if (System.IO.File.Exists(SaveToPath + doc_name))

            {

                this.lblError.Text = "A file with this name already exists.";

                return;

            }

 

            filePSE.PostedFile.SaveAs(SaveToPath + doc_name);

          

            //Create list item with text as document name

            //and value as full path

            ListItem item = new ListItem(doc_name, SaveToPath + doc_name);

 

            //add to list box

            lstDocs.Items.Add(item);

 

            this.lblError.Text = "File uploaded successfully.";

 

        }

        catch (Exception ex)

        {

            Response.Write("Error Uploading File: " + ex.Message.ToString());

            Response.End();

        }

    }

 

    /// <summary>

    /// Delete File

    /// </summary>

    protected void btnDelete_Click(object sender, EventArgs e)

    {

        try

        {

            if (this.lstDocs.Items.Count == 0)

            {

                lblError.Text = "No items to delete";

                return;

            }

            else if (this.lstDocs.SelectedIndex == -1)

            {

                lblError.Text = "Please select an item to delete";

                return;

            }

            else

            {

                //get temp of selected item

                string path = lstDocs.SelectedItem.Value;

 

                //delete the file

                System.IO.File.Delete(path);

 

                //Remove list item

                lstDocs.Items.Remove(lstDocs.SelectedItem);

 

                this.lblError.Text = "File deleted successfully.";

            }

        }

        catch(Exception ex)

        {

            Response.Write("Error Deleting File: " + ex.Message.ToString());

            Response.End();

        }

    }

 

    /// <summary>

    /// Check if it part of allowed extensions

    /// </summary>

    private bool CheckExtensions(string filename)

    {

        try

        {

            /*

            if ( (filename.ToLower().LastIndexOf(".doc") == -1) &&

                 (filename.ToLower().LastIndexOf(".pdf") == -1) &&

                 (filename.ToLower().LastIndexOf(".ppt") == -1) &&

                 (filename.ToLower().LastIndexOf(".txt") == -1) &&

                 (filename.ToLower().LastIndexOf(".xls") == -1)      )

            */

            if ((filename.ToLower().LastIndexOf(".exe") != -1))

            {

                this.lblError.Text = "This type of file cannot be uploaded.";

                return false;

            }

            else

            {

                return true;

            }

        }

        catch (Exception ex)

        {

            Response.Write("Error: " + ex.Message.ToString());

            Response.End();

            //The line below will never execute.

            return false;

        }

    }

 

    /// <summary>

    /// Checks if we have any items, and if so generates javascript for double click.

    /// </summary>

    protected override void OnPreRender(EventArgs e)

    {

        if (lstDocs.Items.Count > 0)

        {

            /*

            if you want to alert the value for error checking, use the following:

            this.lstDocs.Attributes["ondblclick"] = "alert(this.options[this.selectedIndex].text); window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";

            instead of

            */

            this.lstDocs.Attributes["ondblclick"] = "window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";

        }

        else

        {

            this.lstDocs.Attributes.Remove("ondblclick");

        }

        base.OnPreRender(e);

    }

}

 


Setting up Control

If you do not setup the control, you will get this error message:

====================================================


====================================================


Steps To Set Up The Control

Go to the page where you have the control.  Right click the control and select Properties, and you will see the following:

====================================================



====================================================

Modify to your settings, and set to the current default values to demo it:



Run the application.
You will get the following screen, where you can now upload a document.  (Try uploading a document)

====================================================


====================================================

Doube click the document and it will Launch in a new window.

Next try to delete the document:

====================================================

 

You all Set.
Now you can upload, delete, and view documents specified to a directory.

 

How Can This Control Be Userful to You?

This is a very simple control, which you can expand to keep file information in your database for your projects.  You can track files, who its uploaded by, etc....  This way, with little modification, they can see documents that they only uploaded.

The same idea can be applied to different roles, and various different requirements.  This control can server as a template which can be resused for different projects.

 

Good luck.
- See more at: http://www.progtalk.com/viewarticle.aspx?articleid=39#sthash.DfJJ7S5e.dpuf

Web User control written in C# using VS2005 to allow file upload, delete, and view option. Easy property settings, makes it easier for developers to use. - See more at: http://www.progtalk.com/viewarticle.aspx?articleid=39#sthash.DfJJ7S5e.dpuf  



What is the FileUpload Web User control?


This is a web control written in Visual Studio 2005 using C#.  It will allows users to have a quick way to upload, delete, and launch documents.  It has two properties which are:

A.  Save Path
B.  Vitual Path
 



Screenshots


====================================================

====================================================


The Source Code:

using System;

using System.Web;

using System.Web.UI.WebControls;

using System.ComponentModel;

using System.IO;

 

public partial class Controls_FileUpload : System.Web.UI.UserControl

{

    private string SaveToPath = "";

    private string VirtualPath = "";

 

    #region File Upload Control Properties

    /// <summary>

    /// Save Location of File. Example "C:\TEMP\"

    /// </summary>

    [Browsable(true), Category("Properties"), Description("Save Location of File")]

    public string File_Save_Path

    {

        get

        {

            return SaveToPath;

        }

        set

        {

            SaveToPath = value;

        }

    }

 

    /// <summary>

    /// Virtual Path of document.  Example: "http://servername/filedirpath/"

    /// </summary>

    [Browsable(true), Category("Properties"), Description("Virtual Path of document")]

    public string Virtual_Path

    {

        get

        {

            return VirtualPath;

        }

        set

        {

            VirtualPath = value;

        }

 

    }

  

    #endregion

 

    protected void Page_Load(object sender, EventArgs e)

    {

        this.lblError.Text = "";

 

        if (!Page.IsPostBack)

        {

            if (this.VirtualPath.Length == 0)

            {

                this.lblError.Text = "Virtual Path Property has not been set.";

                this.Panel_Control.Enabled = false;

                return;

            }

            else if (this.SaveToPath.Length == 0)

            {

                this.lblError.Text = "Save To Path Property has not been set.";

                this.Panel_Control.Enabled = false;

                return;

            }

            else

            {

                if (ValidatePath() == true)

                {

                    if (ShowAllFiles() == false)

                    {

                        //An error occured.

                        this.Panel_Control.Enabled = false;

                        return;

                    }

                }

                else

                {

                    this.Panel_Control.Enabled = false;

                    return;

                }

            }

        }

    }

   

    /// <summary>

    /// Validates if the Path exists.  If it doesn't we try to create it.

    /// </summary>

    private bool ValidatePath()

    {

        try

        {

            if (System.IO.Directory.Exists(SaveToPath) == false)

            {

                System.IO.Directory.CreateDirectory(SaveToPath);

                return true;

            }

            else

            {

                return true;

            }

        }

        catch (Exception ex)

        {

            lblError.Text = "Error: " + ex.Message.ToString();

            return false;

        }

    }

 

    /// <summary>

    /// Shows all the files in this directory.

    /// </summary>

    private bool ShowAllFiles()

    {

        try

        {

            //Clear the list box

            lstDocs.Items.Clear();

           

            //Get all the directory files

            string[] subfiles = Directory.GetFiles(SaveToPath);

            foreach (string file_obj in subfiles)

            {

                string doc_name = System.IO.Path.GetFileName(file_obj);

 

                //text is document name

                //value is full path to document

                ListItem tempItem = new ListItem(doc_name, file_obj);

 

                //add to list box

                lstDocs.Items.Add(tempItem);

            }

 

            return true;

        }

        catch (Exception ex)

        {

            this.lblError.Text = "Error: " + ex.Message.ToString();

            return false;

        }

    }

 

    /// <summary>

    /// Upload File

    /// </summary>

    protected void btnUpload_Click(object sender, EventArgs e)

    {

        try

        {

            if (filePSE.PostedFile.FileName == "" || filePSE.PostedFile.ContentLength == 0)

            {

                return;

            }

           

            string path = filePSE.PostedFile.FileName;

            string doc_name = System.IO.Path.GetFileName(path);

            string err = "";

 

            bool isSafeFile = CheckExtensions(doc_name);

            if (isSafeFile == false)

            {

                return;

            }

 

            if (System.IO.File.Exists(SaveToPath + doc_name))

            {

                this.lblError.Text = "A file with this name already exists.";

                return;

            }

 

            filePSE.PostedFile.SaveAs(SaveToPath + doc_name);

           

            //Create list item with text as document name

            //and value as full path

            ListItem item = new ListItem(doc_name, SaveToPath + doc_name);

 

            //add to list box

            lstDocs.Items.Add(item);

 

            this.lblError.Text = "File uploaded successfully.";

 

        }

        catch (Exception ex)

        {

            Response.Write("Error Uploading File: " + ex.Message.ToString());

            Response.End();

        }

    }

 

    /// <summary>

    /// Delete File

    /// </summary>

    protected void btnDelete_Click(object sender, EventArgs e)

    {

        try

        {

            if (this.lstDocs.Items.Count == 0)

            {

                lblError.Text = "No items to delete";

                return;

            }

            else if (this.lstDocs.SelectedIndex == -1)

            {

                lblError.Text = "Please select an item to delete";

                return;

            }

            else

            {

                //get temp of selected item

                string path = lstDocs.SelectedItem.Value;

 

                //delete the file

                System.IO.File.Delete(path);

 

                //Remove list item

                lstDocs.Items.Remove(lstDocs.SelectedItem);

 

                this.lblError.Text = "File deleted successfully.";

            }

        }

        catch(Exception ex)

        {

            Response.Write("Error Deleting File: " + ex.Message.ToString());

            Response.End();

        }

    }

 

    /// <summary>

    /// Check if it part of allowed extensions

    /// </summary>

    private bool CheckExtensions(string filename)

    {

        try

        {

            /*

            if ( (filename.ToLower().LastIndexOf(".doc") == -1) &&

                 (filename.ToLower().LastIndexOf(".pdf") == -1) &&

                 (filename.ToLower().LastIndexOf(".ppt") == -1) &&

                 (filename.ToLower().LastIndexOf(".txt") == -1) &&

                 (filename.ToLower().LastIndexOf(".xls") == -1)      )

            */

            if ((filename.ToLower().LastIndexOf(".exe") != -1))

            {

                this.lblError.Text = "This type of file cannot be uploaded.";

                return false;

            }

            else

            {

                return true;

            }

        }

        catch (Exception ex)

        {

            Response.Write("Error: " + ex.Message.ToString());

            Response.End();

            //The line below will never execute.

            return false;

        }

    }

 

    /// <summary>

    /// Checks if we have any items, and if so generates javascript for double click.

    /// </summary>

    protected override void OnPreRender(EventArgs e)

    {

        if (lstDocs.Items.Count > 0)

        {

            /*

            if you want to alert the value for error checking, use the following:

            this.lstDocs.Attributes["ondblclick"] = "alert(this.options[this.selectedIndex].text); window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";

            instead of

            */

            this.lstDocs.Attributes["ondblclick"] = "window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";

        }

        else

        {

            this.lstDocs.Attributes.Remove("ondblclick");

        }

        base.OnPreRender(e);

    }

}

 


Setting up Control

If you do not setup the control, you will get this error message:

====================================================


====================================================


Steps To Set Up The Control

Go to the page where you have the control.  Right click the control and select Properties, and you will see the following:

====================================================



====================================================

Modify to your settings, and set to the current default values to demo it:



Run the application. 
You will get the following screen, where you can now upload a document.  (Try uploading a document)

====================================================


====================================================

Doube click the document and it will Launch in a new window.

Next try to delete the document:

====================================================

 

You all Set. 
Now you can upload, delete, and view documents specified to a directory.

 

How Can This Control Be Userful to You?

This is a very simple control, which you can expand to keep file information in your database for your projects.  You can track files, who its uploaded by, etc....  This way, with little modification, they can see documents that they only uploaded.

The same idea can be applied to different roles, and various different requirements.  This control can server as a template which can be resused for different projects.

 

Good luck.

- See more at: http://www.progtalk.com/viewarticle.aspx?articleid=39#sthash.DfJJ7S5e.dpuf

What is the FileUpload Web User control?


This is a web control written in Visual Studio 2005 using C#.  It will allows users to have a quick way to upload, delete, and launch documents.  It has two properties which are:

A.  Save Path
B.  Vitual Path
 



Screenshots


====================================================

====================================================


The Source Code:

using System;

using System.Web;

using System.Web.UI.WebControls;

using System.ComponentModel;

using System.IO;

 

public partial class Controls_FileUpload : System.Web.UI.UserControl

{

    private string SaveToPath = "";

    private string VirtualPath = "";

 

    #region File Upload Control Properties

    /// <summary>

    /// Save Location of File. Example "C:\TEMP\"

    /// </summary>

    [Browsable(true), Category("Properties"), Description("Save Location of File")]

    public string File_Save_Path

    {

        get

        {

            return SaveToPath;

        }

        set

        {

            SaveToPath = value;

        }

    }

 

    /// <summary>

    /// Virtual Path of document.  Example: "http://servername/filedirpath/"

    /// </summary>

    [Browsable(true), Category("Properties"), Description("Virtual Path of document")]

    public string Virtual_Path

    {

        get

        {

            return VirtualPath;

        }

        set

        {

            VirtualPath = value;

        }

 

    }

  

    #endregion

 

    protected void Page_Load(object sender, EventArgs e)

    {

        this.lblError.Text = "";

 

        if (!Page.IsPostBack)

        {

            if (this.VirtualPath.Length == 0)

            {

                this.lblError.Text = "Virtual Path Property has not been set.";

                this.Panel_Control.Enabled = false;

                return;

            }

            else if (this.SaveToPath.Length == 0)

            {

                this.lblError.Text = "Save To Path Property has not been set.";

                this.Panel_Control.Enabled = false;

                return;

            }

            else

            {

                if (ValidatePath() == true)

                {

                    if (ShowAllFiles() == false)

                    {

                        //An error occured.

                        this.Panel_Control.Enabled = false;

                        return;

                    }

                }

                else

                {

                    this.Panel_Control.Enabled = false;

                    return;

                }

            }

        }

    }

   

    /// <summary>

    /// Validates if the Path exists.  If it doesn't we try to create it.

    /// </summary>

    private bool ValidatePath()

    {

        try

        {

            if (System.IO.Directory.Exists(SaveToPath) == false)

            {

                System.IO.Directory.CreateDirectory(SaveToPath);

                return true;

            }

            else

            {

                return true;

            }

        }

        catch (Exception ex)

        {

            lblError.Text = "Error: " + ex.Message.ToString();

            return false;

        }

    }

 

    /// <summary>

    /// Shows all the files in this directory.

    /// </summary>

    private bool ShowAllFiles()

    {

        try

        {

            //Clear the list box

            lstDocs.Items.Clear();

           

            //Get all the directory files

            string[] subfiles = Directory.GetFiles(SaveToPath);

            foreach (string file_obj in subfiles)

            {

                string doc_name = System.IO.Path.GetFileName(file_obj);

 

                //text is document name

                //value is full path to document

                ListItem tempItem = new ListItem(doc_name, file_obj);

 

                //add to list box

                lstDocs.Items.Add(tempItem);

            }

 

            return true;

        }

        catch (Exception ex)

        {

            this.lblError.Text = "Error: " + ex.Message.ToString();

            return false;

        }

    }

 

    /// <summary>

    /// Upload File

    /// </summary>

    protected void btnUpload_Click(object sender, EventArgs e)

    {

        try

        {

            if (filePSE.PostedFile.FileName == "" || filePSE.PostedFile.ContentLength == 0)

            {

                return;

            }

           

            string path = filePSE.PostedFile.FileName;

            string doc_name = System.IO.Path.GetFileName(path);

            string err = "";

 

            bool isSafeFile = CheckExtensions(doc_name);

            if (isSafeFile == false)

            {

                return;

            }

 

            if (System.IO.File.Exists(SaveToPath + doc_name))

            {

                this.lblError.Text = "A file with this name already exists.";

                return;

            }

 

            filePSE.PostedFile.SaveAs(SaveToPath + doc_name);

           

            //Create list item with text as document name

            //and value as full path

            ListItem item = new ListItem(doc_name, SaveToPath + doc_name);

 

            //add to list box

            lstDocs.Items.Add(item);

 

            this.lblError.Text = "File uploaded successfully.";

 

        }

        catch (Exception ex)

        {

            Response.Write("Error Uploading File: " + ex.Message.ToString());

            Response.End();

        }

    }

 

    /// <summary>

    /// Delete File

    /// </summary>

    protected void btnDelete_Click(object sender, EventArgs e)

    {

        try

        {

            if (this.lstDocs.Items.Count == 0)

            {

                lblError.Text = "No items to delete";

                return;

            }

            else if (this.lstDocs.SelectedIndex == -1)

            {

                lblError.Text = "Please select an item to delete";

                return;

            }

            else

            {

                //get temp of selected item

                string path = lstDocs.SelectedItem.Value;

 

                //delete the file

                System.IO.File.Delete(path);

 

                //Remove list item

                lstDocs.Items.Remove(lstDocs.SelectedItem);

 

                this.lblError.Text = "File deleted successfully.";

            }

        }

        catch(Exception ex)

        {

            Response.Write("Error Deleting File: " + ex.Message.ToString());

            Response.End();

        }

    }

 

    /// <summary>

    /// Check if it part of allowed extensions

    /// </summary>

    private bool CheckExtensions(string filename)

    {

        try

        {

            /*

            if ( (filename.ToLower().LastIndexOf(".doc") == -1) &&

                 (filename.ToLower().LastIndexOf(".pdf") == -1) &&

                 (filename.ToLower().LastIndexOf(".ppt") == -1) &&

                 (filename.ToLower().LastIndexOf(".txt") == -1) &&

                 (filename.ToLower().LastIndexOf(".xls") == -1)      )

            */

            if ((filename.ToLower().LastIndexOf(".exe") != -1))

            {

                this.lblError.Text = "This type of file cannot be uploaded.";

                return false;

            }

            else

            {

                return true;

            }

        }

        catch (Exception ex)

        {

            Response.Write("Error: " + ex.Message.ToString());

            Response.End();

            //The line below will never execute.

            return false;

        }

    }

 

    /// <summary>

    /// Checks if we have any items, and if so generates javascript for double click.

    /// </summary>

    protected override void OnPreRender(EventArgs e)

    {

        if (lstDocs.Items.Count > 0)

        {

            /*

            if you want to alert the value for error checking, use the following:

            this.lstDocs.Attributes["ondblclick"] = "alert(this.options[this.selectedIndex].text); window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";

            instead of

            */

            this.lstDocs.Attributes["ondblclick"] = "window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";

        }

        else

        {

            this.lstDocs.Attributes.Remove("ondblclick");

        }

        base.OnPreRender(e);

    }

}

 


Setting up Control

If you do not setup the control, you will get this error message:

====================================================


====================================================


Steps To Set Up The Control

Go to the page where you have the control.  Right click the control and select Properties, and you will see the following:

====================================================



====================================================

Modify to your settings, and set to the current default values to demo it:



Run the application. 
You will get the following screen, where you can now upload a document.  (Try uploading a document)

====================================================


====================================================

Doube click the document and it will Launch in a new window.

Next try to delete the document:

====================================================

 

You all Set. 
Now you can upload, delete, and view documents specified to a directory.

 

How Can This Control Be Userful to You?

This is a very simple control, which you can expand to keep file information in your database for your projects.  You can track files, who its uploaded by, etc....  This way, with little modification, they can see documents that they only uploaded.

The same idea can be applied to different roles, and various different requirements.  This control can server as a template which can be resused for different projects.

 

Good luck.

- See more at: http://www.progtalk.com/viewarticle.aspx?articleid=39#sthash.DfJJ7S5e.dpuf


Posted by 노을지기