'프로그래밍/C#'에 해당되는 글 53건

  1. 2013.03.01 dateTimePicker 포맷 변경
  2. 2013.03.01 C# String.format
  3. 2013.02.28 해당 월의 마지막 날자 구하기
  4. 2013.02.28 파일 업로드 소스
  5. 2013.02.23 datagridwivew 간 데이터 이동, 추가 삭제

출처: 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 노을지기

datagridview을 사용하여 이것 저것 해보았다.

서로 다른 datagridview을 이용하여 데이터 이동하는 방법이다.

인터넷에서 소스를 찾아서 했는데.. 사용을 안 하다가 다시 쓰려고 하니 다 잊어 버려서 이렇게 메모.


// data
            string strNo = dataGridView_lineup1.SelectedRows[0].Cells[0].Value.ToString();
            string strSrt = dataGridView_lineup1.SelectedRows[0].Cells[1].Value.ToString();
            string strCutoffNo = dataGridView_lineup1.SelectedRows[0].Cells[2].Value.ToString();
            string strPcs = dataGridView_lineup1.SelectedRows[0].Cells[3].Value.ToString();
            string strVolCBM = dataGridView_lineup1.SelectedRows[0].Cells[4].Value.ToString();
            string strVolMBF = dataGridView_lineup1.SelectedRows[0].Cells[5].Value.ToString();

            // add datagrivew
            dataGridView_lineup2.Rows.Add(strNo, strSrt, strCutoffNo, strPcs, strVolCBM, strVolMBF, "", "");
            // remove datagrivew
            dataGridView_lineup1.Rows.Remove(dataGridView_lineup1.SelectedRows[0]);
            // sort
            // this.dataGridView_lineup2.Sort(this.noDataGridViewTextBoxColumn, ListSortDirection.Descending);

            // total cnt
            this.label_totalrows.Text = "Total : " + this.dataGridView_lineup2.Rows.Count;

Posted by 노을지기