DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit repbeiTemp1 = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit repbeiTemp2 = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();

gridView.CustomRowCellEdit += (s, e) =>
{
	if (e.Column.FieldName == "col1")
	{
		if (e.CellValue == null)
		{
			e.RepositoryItem = null;
		}
		else
		{
			e.RepositoryItem = repbeiTemp1;
		}
	}
	else if (e.Column.FieldName == "col2")
	{
		if (e.CellValue == null)
		{
			e.RepositoryItem = null;
		}
		else
		{
			e.RepositoryItem = repbeiTemp2;
		}
	}
}

 

참조

: https://docs.devexpress.com/WindowsForms/DevExpress.XtraGrid.Views.Grid.GridView.CustomRowCellEdit

https://docs.devexpress.com/WindowsForms/DevExpress.XtraGrid.Views.Grid.GridView.CustomRowCellEditForEditing

/**
// KeyDown : 컨트롤에 포커스가 있을 때 키를 누르면 발생합니다.
//   - https://docs.microsoft.com/ko-kr/dotnet/api/system.windows.forms.control.keydown?view=net-5.0
// KeyPress : 컨트롤에 포커스가 있을 때 문자, 스페이스 또는 백스페이스 키를 누르면 발생합니다.
//   - https://docs.microsoft.com/ko-kr/dotnet/api/system.windows.forms.control.keypress?view=net-5.0
// KeyUp : 컨트롤에 포커스가 있을 때 키를 눌렀다 놓으면 발생합니다.
//   - https://docs.microsoft.com/ko-kr/dotnet/api/system.windows.forms.control.keyup?view=net-5.0
 */

//===========================================================

edtSampleControl.KeyDown += OnKeyDown_Enter; //엔터값 확인 
private void OnKeyDown_Enter(object sender, KeyEventArgs e)
{

	Console.WriteLine($"KeyDown code: {e.KeyCode}, value: {e.KeyValue}, modifiers: {e.Modifiers}" + "\r\n");
    
	if (e.KeyCode == Keys.Enter)
	{
		//엔터입력 처리
		e.Handled = true;
	}
}

//===========================================================

edtSampleControl.KeyPress += OnKeyPress_OnlyNumberic; //숫자, 백스페이스, 삭제만 허용
private void OnKeyPress_OnlyNumberic(object sender, KeyPressEventArgs e)
{
	Console.WriteLine($"KeyPress keychar: {e.KeyChar}" + "\r\n");

	//숫자, 백스페이스, 삭제만 허용
	char keyChar = e.KeyChar;
	if (!(char.IsDigit(keyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || e.KeyChar == Convert.ToChar(Keys.Delete)))    //숫자와 백스페이스, 삭제를 제외한 나머지를 바로 처리
	{
		e.Handled = true;
	}
}

//===========================================================

edtSampleControl.KeyPress += OnKeyPress_EscapeToClear; //Escape(ESC) 입력시 Text지우기
private void OnKeyPress_OnlyNumberic(object sender, KeyPressEventArgs e)
{

	Console.WriteLine($"KeyPress keychar: {e.KeyChar}" + "\r\n");
    
	//Escape(ESC) 입력시 Text지우기
	if (e.KeyChar == Convert.ToChar(Keys.Escape))
	{
		Control cmp = sender as Control;
		if(cmp != null)
		{
			cmp.Text = null;
			e.Handled = true;
		}
	}
}

//===========================================================

edtSampleControl.KeyPress += OnKeyUp_Sample;
private void OnKeyUp_Sample(object sender, KeyEventArgs e)
{
	Console.WriteLine( $"KeyUp code: {e.KeyCode}, value: {e.KeyValue}, modifiers: {e.Modifiers}" + "\r\n");
}

 

void SetMultiSelectMode(GridView view, DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode multiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect) {
	view.OptionsSelection.MultiSelectMode = multiSelectMode;
}

string GetSelectedRows(GridView view) {
	//출처 : DevExpress - "Demo Center 19.2" / WinForms Demos / Data Grid and Editors / UI CUSTOMIZATION / Cell Selection 
    string ret = "";
    int rowIndex = -1;
    if(view.OptionsSelection.MultiSelectMode != GridMultiSelectMode.CellSelect) {
        foreach(int i in gridView1.GetSelectedRows()) {
            DataRow row = gridView1.GetDataRow(i);
            if(ret != "") ret += "\r\n";
            ret += string.Format("{2}: {0} (#{1})", row["CompanyName"], i, Properties.Resources.CompanyName);
        }
    }
    else {
        foreach(GridCell cell in view.GetSelectedCells()) {
            if(rowIndex != cell.RowHandle) {
                if(ret != "") ret += "\r\n";
                ret += string.Format("{1}: #{0}", cell.RowHandle, Properties.Resources.Row);
            }
            ret += "\r\n    " + view.GetRowCellDisplayText(cell.RowHandle, cell.Column);
            rowIndex = cell.RowHandle;
        }
    }
    return ret;
}

 

무지개참조 : http://documentation.devexpress.com/#WindowsForms/clsDevExpressSkinsSkinManagertopic

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace UserPark
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //DevExpress 보너스 스킨 등록(활성화)
            DevExpress.UserSkins.BonusSkins.Register();
            //DevExpress.XtraEditors.XtraForm(SDI Form) 스킨기능 활성화
            DevExpress.Skins.SkinManager.EnableFormSkins();
            //DevExpress.XtraEditors.XtraForm(MDI Form) 스킨기능 활성화
            DevExpress.Skins.SkinManager.EnableMdiFormSkins();
           
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new TfrmMain());
        }
    }
}

Program.cs 파일에 Line 16~21 코드를 추가한다.

※ 반드시는 아니나…. 추천….

자세한 설명은 생략

  • Main 폼에 아래 소스 추가하면 스킨갤러리를 사용할 수 있다.
    • “DevExpress.XtraBars.RibbonGalleryBarItem” or “DevExpress.XtraBars.Ribbon.GalleryControl” 타입으로 “GalleryItemSkins”명으로 생성(추가) 하였을 경우 아래 코드를 소스에 추가하여 준다.
DevExpress.XtraBars.Helpers.SkinHelper.InitSkinGallery(GalleryItemSkins, true);

  • 스킨 종류 선언
    • Program.cs에 아래 소수 추가(“DevExpress Dark Style” 사용시)    ※반드시는 아니나…. 추천….
DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle("DevExpress Dark Style");
// or
DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = "DevExpress Dark Style";

DevExpress.LookAndFeel.UserLookAndFeel.Default.UseWindowsXPTheme = false;

별Link : How to Integrate Excel in a Windows Form Application using the WebBrowser

 

 

Sample Image - Embedding_Excel.jpg

Introduction

With Automation, you are able to drive any Office application from your .NET application. This is really powerful. It may happen that one time, you would like to integrate such an application (Excel, for example) in your own application, and handle it like a control. A first approach has already been published on The Code Project (see the Background section in this article). The other method I will describe here uses the Microsoft WebBrowser control as a host for the document.

Background

You can study Anup Shinde's article. His method works fine. Instead of the WebBrowser control, it is based on Windows Win32 API.

If you are interested in the original publication of the WebBrowser method, you can see the Microsoft KB.

Starting from scratch

Create a new form MyForm, and add a new WebBrowser control, named webBrowser1. Add the m_ExcelFileNamefield :

Collapse | Copy Code

// Contains the path to the workbook file
private string m_ExcelFileName="test.xls"; // Replace here with an existing file

Then create a function OpenFile like this :

Collapse | Copy Code

public void OpenFile(string filename) 
{
    // Check the file exists
    if(!System.IO.File.Exists(filename)) throw new Exception();
        m_ExcelFileName=filename;
    // Load the workbook in the WebBrowser control
    this.webBrowser1.Navigate(filename,false);
}

You can try and run your application, giving the filename an existing excel file path. You'll see that it works perfectly. Really easy, don't you think?

In fact, you will quickly get into trouble if you try to run the application a second time with the same Excel file. An error message tells you that your file is already in use. This may be strange because you think that you closed your application, and you did. So where is the problem?

Let's see what happened in the background. While the WebBrowser was navigating, it opened an invisible Excel application, and loaded the workbook inside it. And when you closed your application, the WebBrowser didn't close either its Excel application or the workbook. So we must do it, and this is the most difficult part of our job.

Solving the problem step by step

Before further reading, you have to load the following Office COM library references for Office Automation :

  • Microsoft Excel 11.0 Object Library
  • Microsoft Office 11.0 Object Library

and use them in your file :

Collapse | Copy Code

using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;

You'll need these assemblies too :

Collapse | Copy Code

using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;

Declare these two Excel fields :

Collapse | Copy Code

// Contains a reference to the hosting application
private Microsoft.Office.Interop.Excel.Application m_XlApplication=null;
// Contains a reference to the active workbook
private Workbook m_Workbook=null;

Before trying to close the workbook, we need a handle on it. For convenience, the best moment to do this is just after the document has been loaded in the WebBrowser. So we have to generate a webBrowser1_Navigated event handler and its matching function, like this :

Collapse | Copy Code

private void webBrowser1_Navigated(object sender,WebBrowserNavigatedEventArgs e) 
{
    // Creation of the workbook object
    if((m_Workbook=RetrieveWorkbook(m_ExcelFileName))==null)return;
    // Create the Excel.Application
    m_XlApplication=(Microsoft.Office.Interop.Excel.Application)m_Workbook.Application;
}

Then we define the RetrieveWorkbook function. It is based on two imported Win32 API functions, that retrieve all the programs that are running on our computer. Our job is to search among them the one that is working with the workbook that names xlfile. The code is like this :

Collapse | Copy Code

[DllImport("ole32.dll")] static extern int GetRunningObjectTable
                (uint reserved,out IRunningObjectTable pprot);
[DllImport("ole32.dll")] static extern int CreateBindCtx(uint reserved,out IBindCtx pctx);

public Workbook RetrieveWorkbook(string xlfile) 
{
        IRunningObjectTable prot=null;
        IEnumMoniker pmonkenum=null;
        try 
        {
            IntPtr pfetched=IntPtr.Zero;
            // Query the running object table (ROT)
            if(GetRunningObjectTable(0,out prot)!=0||prot==null) return null;
            prot.EnumRunning(out pmonkenum); pmonkenum.Reset();
            IMoniker[] monikers=new IMoniker[1];
            while(pmonkenum.Next(1,monikers,pfetched)==0) 
            {
                IBindCtx pctx; string filepathname;
                CreateBindCtx(0,out pctx);
                 // Get the name of the file
                 monikers[0].GetDisplayName(pctx,null,out filepathname);
                 // Clean up
                 Marshal.ReleaseComObject(pctx);
                 // Search for the workbook
                 if(filepathname.IndexOf(xlfile)!=-1) 
                 {
                     object roval;
                     // Get a handle on the workbook
                     prot.GetObject(monikers[0],out roval);
                     return roval as Workbook;
                 }
              }
         } 
         catch 
         {
             return null;
         } 
         finally 
         {
             // Clean up
             if(prot!=null) Marshal.ReleaseComObject(prot);
             if(pmonkenum!=null) Marshal.ReleaseComObject(pmonkenum);
         }
         return null;
}

Now we can write the code involved to close the background Excel application, while overriding the OnClose() event :

Collapse | Copy Code

protected override void OnClosed(object sender, EventArgs e) 
{
    try 
    {
        // Quit Excel and clean up.
        if(m_Workbook!=null) 
        {
            m_Workbook.Close(true,Missing.Value,Missing.Value);
            System.Runtime.InteropServices.Marshal.ReleaseComObject
                                    (m_Workbook);
            m_Workbook=null;
        }
        if(m_XlApplication!=null) 
        {
            m_XlApplication.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject
                                (m_XlApplication);
            m_XlApplication=null;
            System.GC.Collect();
        }
    } 
    catch 
    {
        MessageBox.Show("Failed to close the application");
    }
}

Using the code

You can use the code as written upper. Otherwise, it may be interesting to embed all the stuff in a .NET control. You'll be able to manage CommandBars, Menus, etc. inside the control. You will find some code in the downloadable package section.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

+ Recent posts