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

  1. 2013.02.28 파일 업로드 소스
  2. 2013.02.23 Like Query 사용시 주의점
  3. 2013.02.23 datagridwivew 간 데이터 이동, 추가 삭제
  4. 2013.02.21 SQL Joins
  5. 2013.02.21 SQL SERVER - CASE 문 - 중첩

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

이것때문에 좀 시간을 허비했다.

인터넷 검색 기술도 없어서 그런지. 아무리 구글을 뒤져도 나오지않는 현상..ㅡㅡ;;

피곤해서 그런지 이젠 검색하기도 귀찮다..


C#에서 Dataset을 이용하여 데이터를 쿼리하여 datagridview에 뿌려주었다.

Dataset 설정에서 fill 에서는 % 을 넣을 수 없는 관계로 꼼수를 이용하여 사용하였다.

Dataset에서는

SELECT * FROM [TABLE_NAME] WHERE [TABLE_COLUMN] LIKE @[SEARCH];

로 설정하였다.


그후 C#에서 TEXTBOX_TextChanged 이벤트에 넣어서 "%" + TEXTBOX.TEXT + '%' 을 이용하여 사용하였다.

몇 번 잘 사용했는데,

문제는

1. 검색하다 전체를 선택한 후 숫자를 넣었을 경우 에러 (try catch 문 안 넣었음.. 에러 잡기 위하여)

2. 처음에 숫자를 넣었을 경우.

에러가 발생하였다.

단독 테스트를 했을 경우 문제가 없었는데.. 실제 사용할 경우 문제가 발생하였다.


이런 저런 검색 후 생각해낸 꼼수는..

protected string GetSearchValue(string value)
        {
            if (value.Length > 1)
                return "%" + value + "%";
            else
                return value + "%";
        }

숫자일 경우 % 문자가 처음에 갈 경우 문제가 발생하였다.

그래서 입력 단어 개수를 파악하여 1나일 경우 뒤에 '%' 붙이고,

2개 이상일 경우 '%' + 입력 단어 + '%'로 처리하였다.


그후엔 특별한 문제가 없는듯..ㅡㅡ;;

수정.. 처음엔 잘 되다가.. 문제가 다시 발생..

null 값 체크를 했는데도 같은 현상이 발생하였다..

DataSet query configuration에서  ( TABLE_COLUMN LIKE RTRIM(@name))


이렇게 수정하니 제대로 작동.. ㅇ

어렵구나.. 프로그램하는 시간보다 툴 사용 방법 찾는데 시간이 더 오래 걸리는듯..ㅠㅠ

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 노을지기
2013. 2. 21. 03:52

출처: http://blog.daum.net/kkyagami/22

이 개념만 가지고 있으면 ... 문제 없을 듯.. Join에 대하여

이 아래 내용은 나중에 다시 정리해야겠다.


----------------- 참고 용 ===================

Mysql DB를 다룰 때 초보 수준에서 약간 중급으로 넘어가면서
흔히들 많이 어려워 하는 것이 Join 구문입니다.

먼저, 아래와 같은 테이블 두개가 있다고 합시다.
mysql> select * from demo_people;
+————+————–+——+
| name | phone | pid |
+————+————–+——+
| Mr Brown | 01225 708225 | 1 |
| Miss Smith | 01225 899360 | 2 |
| Mr Pullen | 01380 724040 | 3 |
+————+————–+——+

mysql> select * from demo_property;
+——+——+———————-+
| pid | spid | selling |
+——+——+———————-+
| 1 | 1 | Old House Farm |
| 3 | 2 | The Willows |
| 3 | 3 | Tall Trees |
| 3 | 4 | The Melksham Florist |
| 4 | 5 | Dun Roamin |
+——+——+———————-+

두 테이블은 pid 칼럼으로 엮여 있습니다.

먼저 두 테이블을 pid가 같은 것을 조건으로 일반적인 Join을 걸면
결과는 아래와 같습니다.

mysql> select name, phone, selling
from demo_people join demo_property
on demo_people.pid = demo_property.pid;

+———–+————–+———————-+
| name | phone | selling |
+———–+————–+———————-+
| Mr Brown | 01225 708225 | Old House Farm |
| Mr Pullen | 01380 724040 | The Willows |
| Mr Pullen | 01380 724040 | Tall Trees |
| Mr Pullen | 01380 724040 | The Melksham Florist |
+———–+————–+———————-+

pid가 같은 조건이 있는 줄은 두 테이블 모두에서 모조리 나오게 됩니다.
어느테이블이 기준이랄 것이 없이 양쪽에서 줄들이 추가되는
형국이죠. 이 때 서로 같은 것이 존재하지 않는 줄은 아예 출력이
되지 않습니다.

반면, Left 혹은 right join은 기준 테이블, 즉 반드시 출력되는
테이블을 잡아 줍니다.
위의 SQL 구문에서 Left Join을 걸어 보면 아래와 같은 결과가 나옵니다.

mysql> select name, phone, selling
from demo_people left join demo_property
on demo_people.pid = demo_property.pid;
+————+————–+———————-+
| name | phone | selling |
+————+————–+———————-+
| Mr Brown | 01225 708225 | Old House Farm |
| Miss Smith | 01225 899360 | NULL |
| Mr Pullen | 01380 724040 | The Willows |
| Mr Pullen | 01380 724040 | Tall Trees |
| Mr Pullen | 01380 724040 | The Melksham Florist |
+————+————–+———————-+

이 때 Left Join이기 때문에 왼쪽 테이블이 기준이 됩니다.
따라서, 왼쪽 테이블의 모든 Row가 결과값에 반드시 한줄 이상
나오는 보장을 받게 됩니다. 왼쪽 테이블(demo_people)에 해당하는
오른쪽 테이블의 pid가 여러개일경우 위와 같이 여러줄이 나옵니다.

반면, right join은 left join과 반대로 기준이 오른쪽 테이블입니다.
오른쪽 테이블은 반드시 한줄 이상 나오는 보장을 받게 되는 것이죠.
결과 값을 한번 보시죠.

mysql> select name, phone, selling
from demo_people right join demo_property
on demo_people.pid = demo_property.pid;

+———–+————–+———————-+
| name | phone | selling |
+———–+————–+———————-+
| Mr Brown | 01225 708225 | Old House Farm |
| Mr Pullen | 01380 724040 | The Willows |
| Mr Pullen | 01380 724040 | Tall Trees |
| Mr Pullen | 01380 724040 | The Melksham Florist |
| NULL | NULL | Dun Roamin |
+———–+————–+———————-+

왼쪽 테이블(demo_people)에 해당 pid 값이 같은 줄이 없어도,
오른쪽 테이블(demo_property)이 모두 나와야 하기 때문에,
null, null 값이 출력되게 된 것입니다.

INNER JOIN은 JOIN과 같고,
LEFT OUTER JOIN은 LEFT JOIN과 같고,
RIGHT OUTER JOIN은 RIGHT OUTER JOIN과 같습니다.

Posted by 노을지기

속도는 느리지만, 가끔 필요한 소스이다.

다른 방법이 있으면 알려주세요!!

CASE @TestVal
WHEN 1 THEN

            CASE @TestVal2
            WHEN 1 THEN 'First'
            ELSE
@TestVal2 END

WHEN 2 THEN 'Second'
WHEN 3 THEN 'Third'
ELSE 'Other'
END


일을 하다보니, 가끔 내부적으로 특정 데이터만 다시 뽑길 원해서 사용한다..ㅠㅠ

야매인듯..


CASE expressions can be used in SQL anywhere an expression can be used. Example of where CASE expressions can be used include in the SELECT list, WHERE clauses, HAVING clauses, IN lists, DELETE and UPDATE statements, and inside of built-in functions.

Two basic formulations for CASE expression
1) Simple CASE expressions
A simple CASE expression checks one expression against multiple values. Within a SELECT statement, a simple CASE expression allows only an equality check; no other comparisons are made. A simple CASE expression operates by comparing the first expression to the expression in each WHEN clause for equivalency. If these expressions are equivalent, the expression in the THEN clause will be returned.

Syntax:
CASE expression
WHEN expression1 THEN expression1
[[WHEN expression2 THEN expression2] [...]]
[ELSE expressionN]
END

Example:
DECLARE @TestVal INT
SET
@TestVal = 3
SELECT
CASE @TestVal
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 3 THEN 'Third'
ELSE 'Other'
END


2) Searched CASE expressions

A searched CASE expression allows comparison operators, and the use of AND and/or OR between each Boolean expression. The simple CASE expression checks only for equivalent values and can not contain Boolean expressions. The basic syntax for a searched CASE expressions is shown below:

Syntax:
CASE
WHEN Boolean_expression1 THEN expression1
[[WHEN Boolean_expression2 THEN expression2] [...]]
[ELSE expressionN]
END

Example:
DECLARE @TestVal INT
SET
@TestVal = 5
SELECT
CASE
WHEN @TestVal <=3 THEN 'Top 3'
ELSE 'Other'
END

Reference : Pinal Dave (http://blog.SQLAuthority.com)

Posted by 노을지기